Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex d0debd7905 fix(server): sanitize Bitbucket HTTP errors
Co-authored-by: codex <[email protected]>
2026-06-20 12:10:24 -07:00
Julius Marmingeandcodex f1052dd8b1 [codex] Structure Discord release webhook failures (#3285)
Co-authored-by: codex <[email protected]>
2026-06-20 12:09:34 -07:00
Julius Marmingeandcodex e85144a58c [codex] Structure relay delivery attempt errors (#3312)
Co-authored-by: codex <[email protected]>
2026-06-20 12:08:37 -07:00
Julius Marmingeandcodex defd9dfe20 [codex] Structure Electron menu failures (#3317)
Co-authored-by: codex <[email protected]>
2026-06-20 12:07:57 -07:00
Julius Marmingeandcodex 8c03188c1c [codex] Structure preview automation failures (#3333)
Co-authored-by: codex <[email protected]>
2026-06-20 12:07:09 -07:00
Julius Marmingeandcodex 3e5f9f2cdd [codex] Structure browser recording failures (#3330)
Co-authored-by: codex <[email protected]>
2026-06-20 12:06:31 -07:00
Julius Marmingeandcodex 6888276f19 [codex] Sanitize YAML schema diagnostics (#3427)
Co-authored-by: codex <[email protected]>
2026-06-20 12:05:35 -07:00
Julius Marmingeandcodex e06c33c38d [codex] Structure relay Live Activity errors (#3314)
Co-authored-by: codex <[email protected]>
2026-06-20 12:05:13 -07:00
Julius Marmingeandcodex 5f860439e9 [codex] Structure APNs delivery job errors (#3322)
Co-authored-by: codex <[email protected]>
2026-06-20 12:04:27 -07:00
Julius Marmingeandcodex c9159b67b3 [codex] Structure APNs client errors (#3318)
Co-authored-by: codex <[email protected]>
2026-06-20 12:03:43 -07:00
Julius Marmingeandcodex a1b727f62d [codex] Structure relay device persistence errors (#3344)
Co-authored-by: codex <[email protected]>
2026-06-20 12:02:59 -07:00
Julius Marmingeandcodex fdc1e8b3a2 [codex] Structure pairing grant failures (#3386)
Co-authored-by: codex <[email protected]>
2026-06-20 12:02:16 -07:00
Julius Marmingeandcodex c8454ad88a [codex] structure workspace search failures (#3352)
Co-authored-by: codex <[email protected]>
2026-06-20 12:01:31 -07:00
Julius Marmingeandcodex 336d176027 [codex] Structure preview automation errors (#3272)
Co-authored-by: codex <[email protected]>
2026-06-20 12:00:54 -07:00
Julius Marmingeandcodex 204984bf8c [codex] Structure relay deploy output errors (#3340)
Co-authored-by: codex <[email protected]>
2026-06-20 12:00:04 -07:00
Julius Marmingeandcodex be4a38e578 [codex] add structured Electron dialog errors (#3284)
Co-authored-by: codex <[email protected]>
2026-06-20 11:59:27 -07:00
Julius Marmingeandcodex f50a7cddc1 [codex] Structure dev-runner failures (#3283)
Co-authored-by: codex <[email protected]>
2026-06-20 11:58:24 -07:00
Julius Marmingeandcodex 97487d9959 [codex] Structure reference repo sync failures (#3281)
Co-authored-by: codex <[email protected]>
2026-06-20 11:57:48 -07:00
Julius Marmingeandcodex d2e38c5373 [codex] Structure Tailscale command failures (#3257)
Co-authored-by: codex <[email protected]>
2026-06-20 11:56:52 -07:00
Julius Marmingeandcodex 90bd5ee0c1 [codex] structure desktop preview failures (#3244)
Co-authored-by: codex <[email protected]>
2026-06-20 11:55:10 -07:00
Julius Marmingeandcodex 430ece4c0a [codex] Structure Codex app-server request errors (#3258)
Co-authored-by: codex <[email protected]>
2026-06-20 11:54:38 -07:00
Julius Marmingeandcodex 4238a0e769 [codex] Enrich Git VCS driver errors (#3253)
Co-authored-by: codex <[email protected]>
2026-06-20 11:53:53 -07:00
Julius Marmingeandcodex ff0f702c7c [codex] Structure client VCS action errors (#3263)
Co-authored-by: codex <[email protected]>
2026-06-20 11:52:20 -07:00
Julius Marmingeandcodex 1cbe8a7a90 [codex] Structure VCS project config failures (#3315)
Co-authored-by: codex <[email protected]>
2026-06-20 11:51:52 -07:00
Julius Marmingeandcodex 46fdc769d9 [codex] Structure telemetry identity errors (#3306)
Co-authored-by: codex <[email protected]>
2026-06-20 11:50:58 -07:00
Julius Marmingeandcodex 0cd0ed1a3d [codex] Sanitize client error log diagnostics (#3405)
Co-authored-by: codex <[email protected]>
2026-06-20 11:50:46 -07:00
Julius Marmingeandcodex d53237cbd1 [codex] sanitize ACP native event diagnostics (#3417)
Co-authored-by: codex <[email protected]>
2026-06-20 11:50:14 -07:00
Julius Marmingeandcodex 0e718855b8 [codex] Structure primary environment target failures (#3413)
Co-authored-by: codex <[email protected]>
2026-06-20 11:49:21 -07:00
Julius Marmingeandcodex 731b1a67ac [codex] structure VCS process errors (#3408)
Co-authored-by: codex <[email protected]>
2026-06-20 11:49:08 -07:00
Julius Marmingeandcodex cdfecb36a6 [codex] Structure workspace file system errors (#3274)
Co-authored-by: codex <[email protected]>
2026-06-20 11:48:14 -07:00
Julius Marmingeandcodex f4ef356215 [codex] structure desktop IPC registration errors (#3291)
Co-authored-by: codex <[email protected]>
2026-06-20 11:43:21 -07:00
Julius Marmingeandcodex d60f5c6101 [codex] Structure mobile external link failures (#3363)
Co-authored-by: codex <[email protected]>
2026-06-20 11:42:41 -07:00
Julius Marmingeandcodex eacceb9e7b [codex] Bound shared schema diagnostics (#3424)
Co-authored-by: codex <[email protected]>
2026-06-20 11:41:29 -07:00
Julius Marmingeandcodex 13a4789a5d [codex] Structure terminal adapter startup defects (#3425)
Co-authored-by: codex <[email protected]>
2026-06-20 11:40:36 -07:00
Julius Marmingeandcodex b6e384fb27 [codex] Preserve trace IDs across error causes (#3426)
Co-authored-by: codex <[email protected]>
2026-06-20 11:40:08 -07:00
Julius Marmingeandcodex d8bf307d22 [codex] Enrich process runner errors (#3268)
Co-authored-by: codex <[email protected]>
2026-06-20 11:37:50 -07:00
Julius Marmingeandcodex d512deac84 [codex] Structure preview URL failures (#3275)
Co-authored-by: codex <[email protected]>
2026-06-20 11:37:01 -07:00
Julius Marmingeandcodex 32c7f90d9e [codex] Structure APNs delivery queue errors (#3326)
Co-authored-by: codex <[email protected]>
2026-06-20 11:36:08 -07:00
Julius Marmingeandcodex 2c16edd0cb [codex] Structure desktop bridge state errors (#3381)
Co-authored-by: codex <[email protected]>
2026-06-20 11:32:47 -07:00
Julius Marmingeandcodex 708bc7091d Structure server environment ID failures (#3286)
Co-authored-by: codex <[email protected]>
2026-06-20 11:31:57 -07:00
Julius Marmingeandcodex 7eb7b4f4a3 [codex] Structure release metadata failures (#3296)
Co-authored-by: codex <[email protected]>
2026-06-20 11:31:09 -07:00
Julius Marmingeandcodex e01b1903de [codex] Structure process diagnostics failures (#3389)
Co-authored-by: codex <[email protected]>
2026-06-20 11:30:17 -07:00
Julius Marmingeandcodex 1dc36cef73 Structure relay auth parsing errors (#3290)
Co-authored-by: codex <[email protected]>
2026-06-20 11:29:28 -07:00
Julius Marmingeandcodex 833c8ab7c6 [codex] Remove project setup error constructor wrappers (#3329)
Co-authored-by: codex <[email protected]>
2026-06-20 11:28:33 -07:00
Julius Marmingeandcodex 5b1b35c773 [codex] Preserve desktop shell environment probe failures (#3383)
Co-authored-by: codex <[email protected]>
2026-06-20 11:28:06 -07:00
Julius Marmingeandcodex ee3e2dae78 [codex] Structure remote pairing input errors (#3393)
Co-authored-by: codex <[email protected]>
2026-06-20 11:27:39 -07:00
Julius Marmingeandcodex 9c98cd60e8 Remove persistence error constructor wrappers (#3398)
Co-authored-by: codex <[email protected]>
2026-06-20 11:26:51 -07:00
Julius Marmingeandcodex 48f88d5220 [codex] Structure desktop Clerk bridge failures (#3308)
Co-authored-by: codex <[email protected]>
2026-06-20 11:26:03 -07:00
Julius Marmingeandcodex 2910d9ff01 [codex] Structure preview config failures (#3271)
Co-authored-by: codex <[email protected]>
2026-06-20 11:25:14 -07:00
Julius Marmingeandcodex 2b8e012924 [codex] Structure desktop server exposure errors (#3269)
Co-authored-by: codex <[email protected]>
2026-06-20 11:24:35 -07:00
Julius Marmingeandcodex 49c23221d8 [codex] Structure mobile secure storage failures (#3345)
Co-authored-by: codex <[email protected]>
2026-06-20 11:23:58 -07:00
Julius Marmingeandcodex 5ca7676661 [codex] Structure Claude adapter failures (#3406)
Co-authored-by: codex <[email protected]>
2026-06-20 11:22:57 -07:00
Julius Marmingeandcodex c3e3e26844 [codex] Structure primary environment request failures (#3409)
Co-authored-by: codex <[email protected]>
2026-06-20 11:22:28 -07:00
Julius Marmingeandcodex 1486a4a2b9 [codex] Structure Electron updater errors (#3280)
Co-authored-by: codex <[email protected]>
2026-06-20 11:20:46 -07:00
Julius Marmingeandcodex 1e5f62801b [codex] Structure MCP snapshot failures (#3423)
Co-authored-by: codex <[email protected]>
2026-06-20 11:20:14 -07:00
Julius Marmingeandcodex ed6ba7439d [codex] sanitize provider runtime failure diagnostics (#3414)
Co-authored-by: codex <[email protected]>
2026-06-20 11:19:57 -07:00
Julius Marmingeandcodex f98448e872 [codex] Structure relay JWT failures (#3270)
Co-authored-by: codex <[email protected]>
2026-06-20 11:19:39 -07:00
Julius Marmingeandcodex bfe61741b8 [codex] Simplify desktop client settings errors (#3265)
Co-authored-by: codex <[email protected]>
2026-06-20 11:19:11 -07:00
Julius Marmingeandcodex 4d3fcacd84 [codex] Type malformed Clerk public config failures (#3422)
Co-authored-by: codex <[email protected]>
2026-06-20 11:18:38 -07:00
Julius Marmingeandcodex 4d790f0064 [codex] Bound relay registration replay diagnostics (#3420)
Co-authored-by: codex <[email protected]>
2026-06-20 11:13:27 -07:00
Julius Marmingeandcodex 3ecf3685ba [codex] structure Bitbucket API failures (#3332)
Co-authored-by: codex <[email protected]>
2026-06-20 11:13:02 -07:00
Julius Marmingeandcodex 716ae73c40 [codex] Structure relay publish signature errors (#3335)
Co-authored-by: codex <[email protected]>
2026-06-20 11:12:31 -07:00
Julius Marmingeandcodex 300d4d566a [codex] Structure missing provider command failures (#3384)
Co-authored-by: codex <[email protected]>
2026-06-20 11:12:02 -07:00
Julius Marmingeandcodex 53a477c2e9 [codex] Structure desktop backend settings read errors (#3379)
Co-authored-by: codex <[email protected]>
2026-06-20 11:11:43 -07:00
Julius Marmingeandcodex d84ebe8319 [codex] Structure process resource sampling failures (#3415)
Co-authored-by: codex <[email protected]>
2026-06-20 11:11:15 -07:00
Julius Marmingeandcodex 5a2c92e86d [codex] Structure Electron app boundary failures (#3301)
Co-authored-by: codex <[email protected]>
2026-06-20 11:10:45 -07:00
Julius Marmingeandcodex 61aade9ea4 [codex] Preserve desktop asset probe failures (#3373)
Co-authored-by: codex <[email protected]>
2026-06-20 11:10:16 -07:00
Julius Marmingeandcodex 04f82ae1f3 [codex] Structure relay environment link errors (#3334)
Co-authored-by: codex <[email protected]>
2026-06-20 11:09:30 -07:00
Julius Marmingeandcodex ce0c20b840 [codex] Structure desktop network interface failures (#3313)
Co-authored-by: codex <[email protected]>
2026-06-20 11:09:02 -07:00
Julius Marmingeandcodex fccecd8749 [codex] Preserve detached desktop action causes (#3371)
Co-authored-by: codex <[email protected]>
2026-06-20 11:08:32 -07:00
Julius Marmingeandcodex 30a084c463 [codex] Preserve mobile composer draft failures (#3348)
Co-authored-by: codex <[email protected]>
2026-06-20 11:08:03 -07:00
Julius Marmingeandcodex 9d5ca2cb7c [codex] Structure Electron protocol teardown failures (#3310)
Co-authored-by: codex <[email protected]>
2026-06-20 11:07:35 -07:00
Julius Marmingeandcodex ac77fe452b [codex] Preserve relay trace error causes (#3377)
Co-authored-by: codex <[email protected]>
2026-06-20 11:07:06 -07:00
Julius Marmingeandcodex 4fbc4f9b20 [codex] Structure mobile project thread validation errors (#3387)
Co-authored-by: codex <[email protected]>
2026-06-20 11:06:38 -07:00
Julius Marmingeandcodex 779c237487 [codex] Structure native view resolution failures (#3353)
Co-authored-by: codex <[email protected]>
2026-06-20 11:06:08 -07:00
Julius Marmingeandcodex 350e229f7a [codex] Structure OAuth scope encoding failures (#3368)
Co-authored-by: codex <[email protected]>
2026-06-20 11:05:40 -07:00
Julius Marmingeandcodex 8112aff7c2 [codex] Structure relay install confirmation conflicts (#3365)
Co-authored-by: codex <[email protected]>
2026-06-20 11:05:24 -07:00
Julius Marmingeandcodex b9e22de6a3 [codex] Preserve desktop update state read failures (#3370)
Co-authored-by: codex <[email protected]>
2026-06-20 11:04:53 -07:00
Julius Marmingeandcodex f3b43a148b [codex] Structure missing client cloud config errors (#3346)
Co-authored-by: codex <[email protected]>
2026-06-20 11:03:09 -07:00
Julius Marmingeandcodex 8331511b97 [codex] structure Electron theme source errors (#3294)
Co-authored-by: codex <[email protected]>
2026-06-20 11:02:37 -07:00
Julius Marmingeandcodex 08650a7424 [codex] Structure web diff worker failures (#3356)
Co-authored-by: codex <[email protected]>
2026-06-20 11:02:07 -07:00
Julius Marmingeandcodex 40d14647db [codex] Structure catalog dependency resolution failures (#3298)
Co-authored-by: codex <[email protected]>
2026-06-20 11:01:36 -07:00
Julius Marmingeandcodex cc69aef4dd [codex] Structure relay domain label errors (#3347)
Co-authored-by: codex <[email protected]>
2026-06-20 11:00:42 -07:00
Julius Marmingeandcodex 71608142c2 [codex] Split preferred editor precondition errors (#3324)
Co-authored-by: codex <[email protected]>
2026-06-20 10:59:54 -07:00
Julius Marmingeandcodex bf1a6501c7 [codex] Preserve review path resolution failures (#3357)
Co-authored-by: codex <[email protected]>
2026-06-20 10:59:10 -07:00
Julius Marmingeandcodex f7867addbe [codex] Structure mobile notification setting failures (#3391)
Co-authored-by: codex <[email protected]>
2026-06-20 10:58:39 -07:00
Julius Marmingeandcodex 7a8bab5d9d [codex] Keep PTY spawn errors structural (#3325)
Co-authored-by: codex <[email protected]>
2026-06-20 10:58:03 -07:00
Julius Marmingeandcodex 06752526b3 [codex] Structure unavailable Bun PTY operations (#3394)
Co-authored-by: codex <[email protected]>
2026-06-20 10:57:33 -07:00
Julius Marmingeandcodex d87ec967bf [codex] Structure empty mobile pairing payload errors (#3372)
Co-authored-by: codex <[email protected]>
2026-06-20 10:56:12 -07:00
Julius Marmingeandcodex e55dd0067d [codex] Structure preview session key errors (#3388)
Co-authored-by: codex <[email protected]>
2026-06-20 10:54:56 -07:00
Julius Marmingeandcodex 8c3755aecc [codex] Structure bootstrap errors (#3256)
Co-authored-by: codex <[email protected]>
2026-06-20 10:54:12 -07:00
Julius Marmingeandcodex b4fe8faa1d [codex] Structure relay activity-row persistence errors (#3305)
Co-authored-by: codex <[email protected]>
2026-06-20 10:42:38 -07:00
Julius Marmingeandcodex 515303edf2 [codex] Preserve desktop user-data probe failures (#3304)
Co-authored-by: codex <[email protected]>
2026-06-20 10:41:55 -07:00
Julius Marmingeandcodex 20734d4a78 [codex] Structure macOS passkey signing failures (#3303)
Co-authored-by: codex <[email protected]>
2026-06-20 10:41:13 -07:00
Julius Marmingeandcodex 86db35ca61 [codex] Structure mobile native static-check failures (#3302)
Co-authored-by: codex <[email protected]>
2026-06-20 10:40:55 -07:00
254 changed files with 14773 additions and 3170 deletions

No files matched your search

@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import type * as Electron from "electron";
@@ -105,6 +106,7 @@ const withIdentity = <A, E, R>(
readonly calls?: ElectronAppCalls;
readonly environment?: TestEnvironmentInput;
readonly legacyPathExists?: boolean;
readonly legacyPathProbeError?: PlatformError.PlatformError;
readonly packageJson?: string;
readonly pngIconPath?: Option.Option<string>;
} = {},
@@ -121,7 +123,11 @@ const withIdentity = <A, E, R>(
Layer.provideMerge(
FileSystem.layerNoop({
exists: (path) =>
Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
input.legacyPathProbeError
? Effect.fail(input.legacyPathProbeError)
: Effect.succeed(
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
),
readFileString: () =>
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
}),
@@ -147,6 +153,33 @@ describe("DesktopAppIdentity", () => {
),
);
it.effect("preserves failures while inspecting the legacy userData path", () => {
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
description: "permission denied",
pathOrDescriptor: legacyPath,
});
return withIdentity(
Effect.gen(function* () {
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
const error = yield* identity.resolveUserDataPath.pipe(Effect.flip);
assert.instanceOf(error, DesktopAppIdentity.DesktopUserDataPathResolutionError);
assert.equal(error.legacyPath, legacyPath);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to inspect legacy desktop user-data path at "${legacyPath}".`,
);
}),
{ legacyPathProbeError: cause },
);
});
it.effect("configures app identity from the environment commit override", () => {
const calls: ElectronAppCalls = {
setAboutPanelOptions: [],
+23 -5
View File
@@ -18,10 +18,22 @@ const AppPackageMetadata = Schema.Struct({
});
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
export class DesktopUserDataPathResolutionError extends Schema.TaggedErrorClass<DesktopUserDataPathResolutionError>()(
"DesktopUserDataPathResolutionError",
{
legacyPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to inspect legacy desktop user-data path at "${this.legacyPath}".`;
}
}
export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity,
{
readonly resolveUserDataPath: Effect.Effect<string>;
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
readonly configure: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
@@ -33,7 +45,7 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none();
};
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -83,9 +95,15 @@ const make = Effect.gen(function* () {
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem
.exists(legacyPath)
.pipe(Effect.orElseSucceed(() => false));
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
@@ -0,0 +1,57 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as DesktopAssets from "./DesktopAssets.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
isPackaged: true,
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
runningUnderArm64Translation: false,
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
describe("DesktopAssets", () => {
it.effect("preserves the failed asset candidate and filesystem cause", () =>
Effect.gen(function* () {
const fileName = "custom.bin";
const candidatePath = "/repo/apps/desktop/resources/custom.bin";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
pathOrDescriptor: candidatePath,
description: "private filesystem diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
exists: (path) => (path === candidatePath ? Effect.fail(cause) : Effect.succeed(false)),
});
const assetsLayer = DesktopAssets.layer.pipe(
Layer.provide(Layer.merge(fileSystemLayer, environmentLayer)),
);
const assets = yield* DesktopAssets.DesktopAssets.pipe(Effect.provide(assetsLayer));
const error = yield* assets.resolveResourcePath(fileName).pipe(Effect.flip);
assert.instanceOf(error, DesktopAssets.DesktopAssetProbeError);
assert.equal(error.fileName, fileName);
assert.equal(error.candidatePath, candidatePath);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to probe desktop asset "${fileName}" at ${candidatePath}.`,
);
assert.notInclude(error.message, "private filesystem diagnostic");
}),
);
});
+37 -8
View File
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
@@ -12,11 +13,26 @@ export interface DesktopIconPaths {
readonly png: Option.Option<string>;
}
export class DesktopAssetProbeError extends Schema.TaggedErrorClass<DesktopAssetProbeError>()(
"DesktopAssetProbeError",
{
fileName: Schema.String,
candidatePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to probe desktop asset "${this.fileName}" at ${this.candidatePath}.`;
}
}
export class DesktopAssets extends Context.Service<
DesktopAssets,
{
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
readonly resolveResourcePath: (
fileName: string,
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
}
>()("@t3tools/desktop/app/DesktopAssets") {}
@@ -24,14 +40,20 @@ const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(func
fileName: string,
): Effect.fn.Return<
Option.Option<string>,
never,
DesktopAssetProbeError,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const candidates = environment.resolveResourcePathCandidates(fileName);
for (const candidate of candidates) {
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
const exists = yield* fileSystem
.exists(candidate)
.pipe(
Effect.mapError(
(cause) => new DesktopAssetProbeError({ fileName, candidatePath: candidate, cause }),
),
);
if (exists) {
return Option.some(candidate);
}
@@ -43,16 +65,23 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
ext: keyof DesktopIconPaths,
): Effect.fn.Return<
Option.Option<string>,
never,
DesktopAssetProbeError,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
const developmentDockIconPath = environment.developmentDockIconPath;
const developmentDockIconExists = yield* fileSystem
.exists(developmentDockIconPath)
.pipe(Effect.orElseSucceed(() => false));
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe(
Effect.mapError(
(cause) =>
new DesktopAssetProbeError({
fileName: "icon.png",
candidatePath: developmentDockIconPath,
cause,
}),
),
);
if (developmentDockIconExists) {
return Option.some(developmentDockIconPath);
}
@@ -61,7 +90,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
return yield* resolveResourcePath(`icon.${ext}`);
});
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const context = yield* Effect.context<
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
>();
+67 -12
View File
@@ -1,7 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { beforeEach, vi } from "vite-plus/test";
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
createClerkBridgeMock: vi.fn(),
@@ -24,7 +25,23 @@ vi.mock("@clerk/electron/storage", () => ({
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const makeDesktopClerkLayer = (isDevelopment = true) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
return DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
);
};
describe("DesktopClerk", () => {
beforeEach(() => {
createClerkBridgeMock.mockReset();
storageMock.mockReset();
});
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
@@ -40,19 +57,9 @@ describe("DesktopClerk", () => {
const cleanup = vi.fn();
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment: true,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
return Effect.gen(function* () {
yield* Effect.scoped(
Layer.build(
DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
),
),
);
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
@@ -69,6 +76,54 @@ describe("DesktopClerk", () => {
});
});
it.effect("preserves bridge initialization failures", () => {
const cause = new Error("bridge initialization failed");
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockImplementationOnce(() => {
throw cause;
});
return Effect.gen(function* () {
const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
assert.equal(error.stateDir, "/tmp/t3-state");
assert.equal(error.isDevelopment, true);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
);
});
});
it.effect("preserves bridge cleanup failures", () => {
const cause = new Error("bridge cleanup failed");
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({
cleanup: () => {
throw cause;
},
});
return Effect.gen(function* () {
const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
assert.equal(error.stateDir, "/tmp/t3-state");
assert.equal(error.isDevelopment, false);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
);
}
});
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
+47 -3
View File
@@ -4,6 +4,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
@@ -14,6 +15,32 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(
"DesktopClerkBridgeInitializationError",
{
stateDir: Schema.String,
isDevelopment: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
}
}
export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(
"DesktopClerkBridgeCleanupError",
{
stateDir: Schema.String,
isDevelopment: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
}
}
export class DesktopClerk extends Context.Service<
DesktopClerk,
{
@@ -55,11 +82,28 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
});
}
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
(bridge) => Effect.sync(() => bridge.cleanup()),
Effect.try({
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
catch: (cause) =>
new DesktopClerkBridgeInitializationError({
stateDir: environment.stateDir,
isDevelopment: environment.isDevelopment,
cause,
}),
}),
(bridge) =>
Effect.try({
try: () => bridge.cleanup(),
catch: (cause) =>
new DesktopClerkBridgeCleanupError({
stateDir: environment.stateDir,
isDevelopment: environment.isDevelopment,
cause,
}),
}).pipe(Effect.orDie),
);
return DesktopClerk.of({
@@ -0,0 +1,37 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import { DesktopLifecycleRelaunchError } from "./DesktopLifecycle.ts";
import { DesktopApplicationMenuActionError } from "../window/DesktopApplicationMenu.ts";
describe("desktop detached action errors", () => {
it("preserves the complete relaunch failure cause and reason", () => {
const cause = Cause.combine(
Cause.fail(new Error("shutdown failed")),
Cause.die(new Error("relaunch defect")),
);
const error = new DesktopLifecycleRelaunchError({
reason: "apply update",
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.reason, "apply update");
assert.equal(error.message, 'Desktop relaunch failed for reason "apply update".');
});
it("preserves the complete menu action failure cause and action", () => {
const cause = Cause.combine(
Cause.fail(new Error("window unavailable")),
Cause.die(new Error("dispatch defect")),
);
const error = new DesktopApplicationMenuActionError({
action: "open-settings",
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.action, "open-settings");
assert.equal(error.message, 'Desktop menu action "open-settings" failed.');
});
});
+17 -6
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import type * as Electron from "electron";
@@ -15,6 +15,18 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
export class DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()(
"DesktopLifecycleRelaunchError",
{
reason: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop relaunch failed for reason "${this.reason}".`;
}
}
export type DesktopLifecycleRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopShutdown.DesktopShutdown
@@ -142,11 +154,10 @@ export const make = DesktopLifecycle.of({
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) =>
logLifecycleError("desktop relaunch failed", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
const error = new DesktopLifecycleRelaunchError({ reason, cause });
return logLifecycleError(error.message, { error });
}),
Effect.forkDetach,
Effect.asVoid,
);
@@ -3,6 +3,8 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -21,6 +23,10 @@ const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
);
const isDesktopBackendObservabilitySettingsReadError = Schema.is(
DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
);
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"),
backendConfig: Effect.succeed({
@@ -166,6 +172,62 @@ describe("DesktopBackendConfiguration", () => {
),
);
it.effect("logs structured context when persisted observability settings cannot be read", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const settingsPath = `${baseDir}/userdata/settings.json`;
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: settingsPath,
});
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
const failingFileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(cause),
}),
);
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolve;
}).pipe(
Effect.provide(
Layer.mergeAll(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
Layer.provideMerge(failingFileSystemLayer),
),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
const error = messages
.flatMap((message) => (Array.isArray(message) ? message : [message]))
.find(isDesktopBackendObservabilitySettingsReadError);
assert.isDefined(error);
assert.equal(error.settingsPath, settingsPath);
assert.equal(error.cause, cause);
assert.equal(
error.message,
`Failed to read persisted backend observability settings at ${settingsPath}.`,
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("captures backend output in development so child process logs can be persisted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -8,12 +8,24 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
"DesktopBackendObservabilitySettingsReadError",
{
settingsPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
}
}
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
{
@@ -50,25 +62,34 @@ const DESKTOP_BACKEND_ENV_NAMES = [
const backendChildEnvPatch = (): Record<string, string | undefined> =>
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
const { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
"desktop-backend-configuration",
);
const logBackendObservabilitySettingsReadFailure = (
settingsPath: string,
cause: PlatformError.PlatformError,
) => {
const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
return Effect.logWarning(error).pipe(
Effect.annotateLogs({
component: "desktop-backend-configuration",
error,
}),
);
};
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const exists = yield* fileSystem
.exists(environment.serverSettingsPath)
.pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return emptyBackendObservabilitySettings;
}
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none())
: logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
Effect.as(Option.none()),
),
}),
);
if (Option.isNone(raw)) {
yield* logBackendConfigurationWarning(
"failed to read persisted backend observability settings",
);
return emptyBackendObservabilitySettings;
}
@@ -0,0 +1,65 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { networkInterfacesMock } = vi.hoisted(() => ({
networkInterfacesMock: vi.fn(),
}));
vi.mock("node:os", () => ({
networkInterfaces: networkInterfacesMock,
}));
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
const TestLayer = DesktopNetworkInterfaces.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
describe("DesktopNetworkInterfaces", () => {
beforeEach(() => {
networkInterfacesMock.mockReset();
});
it.effect("reads network interfaces through the service", () => {
const interfaces = {
en0: [
{
address: "192.168.1.10",
family: "IPv4",
internal: false,
},
],
};
networkInterfacesMock.mockReturnValueOnce(interfaces);
return Effect.gen(function* () {
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
assert.strictEqual(yield* service.read, interfaces);
}).pipe(Effect.provide(TestLayer));
});
it.effect("preserves network interface read failures as structured defects", () => {
const cause = new Error("network interface probe failed");
networkInterfacesMock.mockImplementationOnce(() => {
throw cause;
});
return Effect.gen(function* () {
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
const exit = yield* Effect.exit(service.read);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopNetworkInterfaces.DesktopNetworkInterfacesReadError);
assert.equal(error.platform, "linux");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Failed to read desktop network interfaces on linux.");
}
}).pipe(Effect.provide(TestLayer));
});
});
@@ -1,8 +1,10 @@
import * as NodeOS from "node:os";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
@@ -18,6 +20,18 @@ export type NetworkInterfaces = Readonly<
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
>;
export class DesktopNetworkInterfacesReadError extends Schema.TaggedErrorClass<DesktopNetworkInterfacesReadError>()(
"DesktopNetworkInterfacesReadError",
{
platform: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read desktop network interfaces on ${this.platform}.`;
}
}
export class DesktopNetworkInterfaces extends Context.Service<
DesktopNetworkInterfaces,
{
@@ -25,9 +39,14 @@ export class DesktopNetworkInterfaces extends Context.Service<
}
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
export const make = (): DesktopNetworkInterfaces["Service"] =>
DesktopNetworkInterfaces.of({
read: Effect.sync(() => NodeOS.networkInterfaces()),
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return DesktopNetworkInterfaces.of({
read: Effect.try({
try: () => NodeOS.networkInterfaces(),
catch: (cause) => new DesktopNetworkInterfacesReadError({ platform, cause }),
}).pipe(Effect.orDie),
});
});
export const layer = Layer.succeed(DesktopNetworkInterfaces, make());
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
@@ -91,6 +91,7 @@ function makeLayer(input: {
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
@@ -99,7 +100,7 @@ function makeLayer(input: {
});
return DesktopServerExposure.layer.pipe(
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
@@ -122,6 +123,7 @@ const withHarness = <A, E, R>(
>,
env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -135,6 +137,7 @@ const withHarness = <A, E, R>(
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
}),
),
);
@@ -237,6 +240,67 @@ describe("DesktopServerExposure", () => {
),
);
it.effect("preserves persistence request context and the settings failure chain", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
operation: "replace-settings-file",
path: "/tmp/desktop-settings.json",
cause: diskFailure,
});
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setServerExposureMode: () => Effect.fail(settingsFailure),
setTailscaleServe: () => Effect.fail(settingsFailure),
setUpdateChannel: () => Effect.die("unexpected update channel change"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
return withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
assert.instanceOf(
modeError,
DesktopServerExposure.DesktopServerExposureModePersistenceError,
);
assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
assert.equal(modeError.mode, "network-accessible");
assert.strictEqual(modeError.cause, settingsFailure);
assert.strictEqual(modeError.cause.cause, diskFailure);
assert.equal(
modeError.message,
"Failed to persist desktop server exposure mode network-accessible.",
);
assert.notInclude(modeError.message, diskFailure.message);
const tailscaleError = yield* serverExposure
.setTailscaleServeEnabled({ enabled: true, port: 8443 })
.pipe(Effect.flip);
assert.instanceOf(
tailscaleError,
DesktopServerExposure.DesktopTailscaleServePersistenceError,
);
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
assert.equal(tailscaleError.enabled, true);
assert.equal(tailscaleError.port, 8443);
assert.strictEqual(tailscaleError.cause, settingsFailure);
assert.strictEqual(tailscaleError.cause.cause, diskFailure);
assert.equal(
tailscaleError.message,
"Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).",
);
assert.notInclude(tailscaleError.message, diskFailure.message);
}),
{},
undefined,
settingsLayer,
);
});
it.effect("resolves advertised endpoints from the scoped runtime state", () =>
withHarness(
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
@@ -2,11 +2,12 @@ import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/shared/advertisedEndpoint";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
DesktopServerExposureState,
import {
DesktopServerExposureModeSchema,
type AdvertisedEndpoint,
type AdvertisedEndpointProvider,
type DesktopServerExposureMode,
type DesktopServerExposureState,
} from "@t3tools/contracts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as Context from "effect/Context";
@@ -213,23 +214,45 @@ export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErr
}
}
export class DesktopServerExposurePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposurePersistenceError>()(
"DesktopServerExposurePersistenceError",
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
"DesktopServerExposureModePersistenceError",
{
operation: Schema.Literals(["server-exposure-mode", "tailscale-serve"]),
mode: DesktopServerExposureModeSchema,
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop ${this.operation} settings.`;
return `Failed to persist desktop server exposure mode ${this.mode}.`;
}
}
export type DesktopServerExposureSetModeError =
| DesktopServerExposureNoNetworkAddressError
| DesktopServerExposurePersistenceError;
export class DesktopTailscaleServePersistenceError extends Schema.TaggedErrorClass<DesktopTailscaleServePersistenceError>()(
"DesktopTailscaleServePersistenceError",
{
enabled: Schema.Boolean,
port: Schema.NullOr(Schema.Number),
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop Tailscale Serve settings (enabled: ${this.enabled}, port: ${this.port ?? "unchanged"}).`;
}
}
export type DesktopServerExposureError = DesktopServerExposureSetModeError;
export const DesktopServerExposureSetModeError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
]);
export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
export const isDesktopServerExposureSetModeError = Schema.is(DesktopServerExposureSetModeError);
export const DesktopServerExposureError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
DesktopTailscaleServePersistenceError,
]);
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
export const isDesktopServerExposureError = Schema.is(DesktopServerExposureError);
export interface DesktopServerExposureBackendConfig {
readonly port: number;
@@ -258,7 +281,7 @@ export class DesktopServerExposure extends Context.Service<
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
@@ -449,8 +472,8 @@ export const make = Effect.gen(function* () {
const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
Effect.mapError(
(cause) =>
new DesktopServerExposurePersistenceError({
operation: "server-exposure-mode",
new DesktopServerExposureModePersistenceError({
mode,
cause,
}),
),
@@ -477,8 +500,9 @@ export const make = Effect.gen(function* () {
.pipe(
Effect.mapError(
(cause) =>
new DesktopServerExposurePersistenceError({
operation: "tailscale-serve",
new DesktopTailscaleServePersistenceError({
enabled: input.enabled,
port: input.port ?? null,
cause,
}),
),
@@ -100,6 +100,44 @@ describe("ElectronApp", () => {
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("reports which app metadata property failed", () =>
Effect.gen(function* () {
const cause = new Error("version unavailable");
getVersionMock.mockImplementationOnce(() => {
throw cause;
});
const electronApp = yield* ElectronApp.ElectronApp;
const error = yield* electronApp.metadata.pipe(Effect.flip);
assert.instanceOf(error, ElectronApp.ElectronAppMetadataReadError);
assert.strictEqual(error.property, "app-version");
assert.strictEqual(error.cause, cause);
assert.strictEqual(
error.message,
'Failed to read Electron app metadata property "app-version".',
);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("preserves Electron readiness failures", () =>
Effect.gen(function* () {
const cause = new Error("ready failed");
whenReadyMock.mockRejectedValueOnce(cause);
const electronApp = yield* ElectronApp.ElectronApp;
const error = yield* electronApp.whenReady.pipe(Effect.flip);
assert.instanceOf(error, ElectronApp.ElectronAppWhenReadyError);
assert.strictEqual(error.isPackaged, true);
assert.strictEqual(error.cause, cause);
assert.strictEqual(
error.message,
"Failed to wait for the Electron app to become ready (packaged: true).",
);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("scopes app event listeners", () =>
Effect.gen(function* () {
const listener = vi.fn();
+60 -10
View File
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
@@ -13,12 +14,36 @@ export interface ElectronAppMetadata {
readonly runningUnderArm64Translation: boolean;
}
export class ElectronAppMetadataReadError extends Schema.TaggedErrorClass<ElectronAppMetadataReadError>()(
"ElectronAppMetadataReadError",
{
property: Schema.Literals(["app-version", "app-path"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read Electron app metadata property "${this.property}".`;
}
}
export class ElectronAppWhenReadyError extends Schema.TaggedErrorClass<ElectronAppWhenReadyError>()(
"ElectronAppWhenReadyError",
{
isPackaged: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to wait for the Electron app to become ready (packaged: ${this.isPackaged}).`;
}
}
export class ElectronApp extends Context.Service<
ElectronApp,
{
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void>;
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
@@ -63,15 +88,40 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
).pipe(Effect.asVoid);
export const make = ElectronApp.of({
metadata: Effect.sync(() => ({
appVersion: Electron.app.getVersion(),
appPath: Electron.app.getAppPath(),
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
})),
metadata: Effect.gen(function* () {
const appVersion = yield* Effect.try({
try: () => Electron.app.getVersion(),
catch: (cause) =>
new ElectronAppMetadataReadError({
property: "app-version",
cause,
}),
});
const appPath = yield* Effect.try({
try: () => Electron.app.getAppPath(),
catch: (cause) =>
new ElectronAppMetadataReadError({
property: "app-path",
cause,
}),
});
return {
appVersion,
appPath,
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
};
}),
name: Effect.sync(() => Electron.app.name),
whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
whenReady: Effect.gen(function* () {
const isPackaged = Electron.app.isPackaged;
yield* Effect.tryPromise({
try: () => Electron.app.whenReady(),
catch: (cause) => new ElectronAppWhenReadyError({ isPackaged, cause }),
});
}),
quit: Effect.sync(() => {
Electron.app.quit();
}),
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type { BrowserWindow } from "electron";
@@ -90,4 +91,116 @@ describe("ElectronDialog", () => {
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves folder picker request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("folder picker failed");
const owner = { id: 7 } as BrowserWindow;
showOpenDialogMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.pickFolder({
owner: Option.some(owner),
defaultPath: Option.some("/workspace"),
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError);
assert.isTrue(ElectronDialog.isElectronDialogError(error));
assert.strictEqual(error.ownerWindowId, 7);
assert.strictEqual(error.defaultPath, "/workspace");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 7");
assert.include(error.message, "/workspace");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves confirmation request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("confirmation failed");
const owner = { id: 9 } as BrowserWindow;
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.confirm({
owner: Option.some(owner),
message: " Confirm removal? ",
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
assert.strictEqual(error.ownerWindowId, 9);
assert.strictEqual(error.promptLength, "Confirm removal?".length);
assert.notProperty(error, "promptMessage");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 9");
assert.notInclude(error.message, "Confirm removal?");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves message box request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("message box failed");
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.showMessageBox({
type: "warning",
title: "Unsaved changes",
message: "Discard changes?",
detail: "This cannot be undone.",
buttons: ["Cancel", "Discard"],
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogShowMessageBoxError);
assert.strictEqual(error.type, "warning");
assert.strictEqual(error.titleLength, "Unsaved changes".length);
assert.strictEqual(error.messageLength, "Discard changes?".length);
assert.strictEqual(error.detailLength, "This cannot be undone.".length);
assert.strictEqual(error.buttonCount, 2);
assert.notProperty(error, "title");
assert.notProperty(error, "dialogMessage");
assert.notProperty(error, "dialogDetail");
assert.notProperty(error, "buttons");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "warning");
assert.notInclude(error.message, "Unsaved changes");
assert.notInclude(error.message, "Discard changes?");
assert.notInclude(error.message, "This cannot be undone.");
assert.notInclude(error.message, "Cancel");
assert.notInclude(error.message, "Discard");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves error box request context and cause in the defect", () =>
Effect.gen(function* () {
const cause = new Error("error box failed");
showErrorBoxMock.mockImplementation(() => {
throw cause;
});
const dialog = yield* ElectronDialog.ElectronDialog;
const exit = yield* Effect.exit(dialog.showErrorBox("Startup failed", "Could not start."));
assert.isTrue(exit._tag === "Failure");
if (exit._tag === "Success") return;
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronDialog.ElectronDialogShowErrorBoxError);
assert.strictEqual(error.titleLength, "Startup failed".length);
assert.strictEqual(error.contentLength, "Could not start.".length);
assert.notProperty(error, "title");
assert.notProperty(error, "content");
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, "Startup failed");
assert.notInclude(error.message, "Could not start.");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
});
+129 -14
View File
@@ -2,11 +2,80 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
"ElectronDialogPickFolderError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
defaultPath: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
return `Failed to open the Electron folder picker for ${owner} with ${defaultPath}.`;
}
}
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
promptLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
}
}
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
"ElectronDialogShowMessageBoxError",
{
type: Schema.NullOr(Schema.Literals(["none", "info", "error", "question", "warning"])),
titleLength: Schema.NullOr(Schema.Number),
messageLength: Schema.Number,
detailLength: Schema.NullOr(Schema.Number),
buttonCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const type = this.type === null ? "untyped" : this.type;
return `Failed to show the Electron ${type} message box with ${this.buttonCount} buttons.`;
}
}
export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<ElectronDialogShowErrorBoxError>()(
"ElectronDialogShowErrorBoxError",
{
titleLength: Schema.Number,
contentLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to show the Electron error box with a ${this.titleLength}-character title and ${this.contentLength}-character content.`;
}
}
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
ElectronDialogConfirmError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
]);
export type ElectronDialogError = typeof ElectronDialogError.Type;
export const isElectronDialogError = Schema.is(ElectronDialogError);
export interface ElectronDialogPickFolderInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly defaultPath: Option.Option<string>;
@@ -22,17 +91,24 @@ export class ElectronDialog extends Context.Service<
{
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue>;
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronDialog") {}
export const make = ElectronDialog.of({
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const defaultPath = Option.getOrNull(input.defaultPath);
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
onNone: () => ({
properties: ["openDirectory", "createDirectory"],
@@ -42,10 +118,18 @@ export const make = ElectronDialog.of({
defaultPath,
}),
});
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
onSome: (owner) =>
Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
}),
catch: (cause) =>
new ElectronDialogPickFolderError({
ownerWindowId,
defaultPath,
cause,
}),
});
if (result.canceled) {
@@ -67,17 +151,48 @@ export const make = ElectronDialog.of({
noLink: true,
message: normalizedMessage,
};
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showMessageBox(options),
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
}),
catch: (cause) =>
new ElectronDialogConfirmError({
ownerWindowId,
promptLength: normalizedMessage.length,
cause,
}),
});
return result.response === CONFIRM_BUTTON_INDEX;
}),
showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
showErrorBox: (title, content) =>
Effect.sync(() => {
Electron.dialog.showErrorBox(title, content);
showMessageBox: (options) =>
Effect.tryPromise({
try: () => Electron.dialog.showMessageBox(options),
catch: (cause) =>
new ElectronDialogShowMessageBoxError({
type: options.type ?? null,
titleLength: options.title?.length ?? null,
messageLength: options.message.length,
detailLength: options.detail?.length ?? null,
buttonCount: options.buttons?.length ?? 0,
cause,
}),
}),
showErrorBox: (title, content) =>
Effect.try({
try: () => Electron.dialog.showErrorBox(title, content),
catch: (cause) =>
new ElectronDialogShowErrorBoxError({
titleLength: title.length,
contentLength: content.length,
cause,
}),
}).pipe(Effect.orDie),
});
export const layer = Layer.succeed(ElectronDialog, make);
+94 -4
View File
@@ -1,5 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
@@ -24,6 +27,10 @@ vi.mock("electron", () => ({
import * as ElectronMenu from "./ElectronMenu.ts";
const TestLayer = ElectronMenu.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
describe("ElectronMenu", () => {
beforeEach(() => {
buildFromTemplateMock.mockReset();
@@ -42,7 +49,7 @@ describe("ElectronMenu", () => {
assert.isTrue(Option.isNone(selectedItemId));
assert.equal(buildFromTemplateMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronMenu.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("resolves with the clicked leaf item id", () =>
@@ -69,7 +76,7 @@ describe("ElectronMenu", () => {
});
assert.equal(Option.getOrNull(selectedItemId), "copy");
}).pipe(Effect.provide(ElectronMenu.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("resolves with none when the menu closes without a click", () =>
@@ -93,7 +100,7 @@ describe("ElectronMenu", () => {
enabled: true,
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
});
}).pipe(Effect.provide(ElectronMenu.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("defers popupTemplate side effects until the returned Effect runs", () =>
@@ -114,6 +121,89 @@ describe("ElectronMenu", () => {
assert.equal(buildFromTemplateMock.mock.calls.length, 1);
assert.equal(popupMock.mock.calls.length, 1);
}).pipe(Effect.provide(ElectronMenu.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves application-menu failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("application menu build failed");
buildFromTemplateMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.setApplicationMenu([{ label: "File" }, { label: "Edit" }]),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "set-application-menu");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.equal(error.itemCount, 2);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves popup-template failures with window context", () =>
Effect.gen(function* () {
const cause = new Error("popup failed");
buildFromTemplateMock.mockReturnValueOnce({
popup: () => {
throw cause;
},
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.popupTemplate({
window: { id: 41 } as Electron.BrowserWindow,
template: [{ label: "Copy" }],
}),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "popup-template");
assert.equal(error.windowId, 41);
assert.equal(error.itemCount, 1);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves context-menu failures with normalized item context", () =>
Effect.gen(function* () {
const cause = new Error("context menu build failed");
buildFromTemplateMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.showContextMenu({
window: { id: 42 } as Electron.BrowserWindow,
items: [{ id: "copy", label: "Copy" }],
position: Option.none(),
}),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "show-context-menu");
assert.equal(error.windowId, 42);
assert.equal(error.itemCount, 1);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
});
+85 -24
View File
@@ -4,6 +4,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
@@ -23,6 +24,28 @@ export interface ElectronMenuTemplateInput {
readonly template: readonly Electron.MenuItemConstructorOptions[];
}
const ElectronMenuOperation = Schema.Literals([
"set-application-menu",
"popup-template",
"show-context-menu",
]);
export class ElectronMenuOperationError extends Schema.TaggedErrorClass<ElectronMenuOperationError>()(
"ElectronMenuOperationError",
{
operation: ElectronMenuOperation,
platform: Schema.String,
windowId: Schema.NullOr(Schema.Number),
itemCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
}
}
export class ElectronMenu extends Context.Service<
ElectronMenu,
{
@@ -142,16 +165,36 @@ export const make = Effect.gen(function* () {
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
Effect.try({
try: () => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
},
catch: (cause) =>
new ElectronMenuOperationError({
operation: "set-application-menu",
platform,
windowId: null,
itemCount: template.length,
cause,
}),
}).pipe(Effect.orDie),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
input.template.length === 0
? Effect.void
: Effect.try({
try: () =>
Electron.Menu.buildFromTemplate([...input.template]).popup({
window: input.window,
}),
catch: (cause) =>
new ElectronMenuOperationError({
operation: "popup-template",
platform,
windowId: input.window.id,
itemCount: input.template.length,
cause,
}),
}).pipe(Effect.orDie),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
@@ -169,21 +212,39 @@ export const make = Effect.gen(function* () {
resume(Effect.succeed(selectedItemId));
};
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
try {
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
} catch (cause) {
if (completed) {
return;
}
completed = true;
resume(
Effect.die(
new ElectronMenuOperationError({
operation: "show-context-menu",
platform,
windowId: input.window.id,
itemCount: normalizedItems.length,
cause,
}),
),
);
}
}),
});
});
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
@@ -98,6 +99,60 @@ describe("ElectronProtocol", () => {
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
handleMock.mockImplementationOnce(() => {
throw cause;
});
const protocol = yield* ElectronProtocol.ElectronProtocol;
const error = yield* Effect.scoped(
protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: undefined,
}),
).pipe(Effect.flip);
assert.instanceOf(error, ElectronProtocol.ElectronProtocolRegistrationError);
assert.equal(error.scheme, "t3code-dev");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to register Electron protocol scheme "t3code-dev".');
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol unregistration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol unregistration failed");
unhandleMock.mockImplementationOnce(() => {
throw cause;
});
const protocol = yield* ElectronProtocol.ElectronProtocol;
const exit = yield* Effect.exit(
Effect.scoped(
protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
}),
),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronProtocol.ElectronProtocolUnregistrationError);
assert.equal(error.scheme, "t3code");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to unregister Electron protocol scheme "t3code".');
}
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
scheme: "t3code",
+21 -4
View File
@@ -31,7 +31,19 @@ export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<E
},
) {
override get message(): string {
return `Failed to register ${this.scheme}: protocol.`;
return `Failed to register Electron protocol scheme "${this.scheme}".`;
}
}
export class ElectronProtocolUnregistrationError extends Schema.TaggedErrorClass<ElectronProtocolUnregistrationError>()(
"ElectronProtocolUnregistrationError",
{
scheme: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
}
}
@@ -133,9 +145,14 @@ export const make = Effect.gen(function* () {
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
}).pipe(Effect.andThen(Ref.set(registered, true))),
() =>
Effect.sync(() => {
Electron.protocol.unhandle(input.scheme);
}).pipe(Effect.andThen(Ref.set(registered, false))),
Effect.try({
try: () => Electron.protocol.unhandle(input.scheme),
catch: (cause) =>
new ElectronProtocolUnregistrationError({
scheme: input.scheme,
cause,
}),
}).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
);
},
);
@@ -8,6 +8,7 @@ const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
themeState: {
shouldUseDarkColors: true,
themeSource: "system",
setSourceError: null as unknown,
},
}));
@@ -17,6 +18,9 @@ vi.mock("electron", () => ({
return themeState.shouldUseDarkColors;
},
set themeSource(value: string) {
if (themeState.setSourceError !== null) {
throw themeState.setSourceError;
}
themeState.themeSource = value;
},
on: onMock,
@@ -32,6 +36,7 @@ describe("ElectronTheme", () => {
removeListenerMock.mockClear();
themeState.shouldUseDarkColors = true;
themeState.themeSource = "system";
themeState.setSourceError = null;
});
it.effect("scopes native theme update listeners", () =>
@@ -49,4 +54,21 @@ describe("ElectronTheme", () => {
assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]);
}).pipe(Effect.provide(ElectronTheme.layer)),
);
it.effect("preserves the requested source and cause when setting the theme fails", () =>
Effect.gen(function* () {
const cause = new Error("theme source failed");
themeState.setSourceError = cause;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const error = yield* Effect.flip(electronTheme.setSource("dark"));
assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError);
assert.isTrue(ElectronTheme.isElectronThemeSetSourceError(error));
assert.strictEqual(error.source, "dark");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "dark");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronTheme.layer)),
);
});
+22 -5
View File
@@ -1,16 +1,31 @@
import type { DesktopTheme } from "@t3tools/contracts";
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export class ElectronThemeSetSourceError extends Schema.TaggedErrorClass<ElectronThemeSetSourceError>()(
"ElectronThemeSetSourceError",
{
source: DesktopThemeSchema,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to set the Electron theme source to ${this.source}.`;
}
}
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
export class ElectronTheme extends Context.Service<
ElectronTheme,
{
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronTheme") {}
@@ -18,9 +33,11 @@ export class ElectronTheme extends Context.Service<
export const make = ElectronTheme.of({
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
setSource: (theme) =>
Effect.suspend(() => {
Electron.nativeTheme.themeSource = theme;
return Effect.void;
Effect.try({
try: () => {
Electron.nativeTheme.themeSource = theme;
},
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
}),
onUpdated: (listener) =>
Effect.acquireRelease(
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
@@ -65,16 +64,65 @@ describe("ElectronUpdater", () => {
const cause = new Error("network unavailable");
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "beta";
const exit = yield* Effect.exit(updater.checkForUpdates);
const error = yield* updater.checkForUpdates.pipe(Effect.flip);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.equal(error.cause, cause);
assert.equal(error.message, "Electron updater failed to check for updates.");
}
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "beta");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Electron updater failed to check for updates on channel beta.");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves the execution-time channel on download failures", () =>
Effect.gen(function* () {
const cause = new Error("download unavailable");
autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "nightly";
const error = yield* updater.downloadUpdate.pipe(Effect.flip);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "nightly");
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Electron updater failed to download the update on channel nightly.",
);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
Effect.gen(function* () {
const cause = new Error("quit and install failed");
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
throw cause;
});
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "alpha";
const error = yield* updater
.quitAndInstall({ isSilent: true, isForceRunAfter: false })
.pipe(Effect.flip);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "alpha");
assert.equal(error.isSilent, true);
assert.equal(error.isForceRunAfter, false);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Electron updater failed to quit and install the update on channel alpha (silent: true, force run after: false).",
);
assert.notInclude(error.message, cause.message);
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
});
+37 -21
View File
@@ -10,40 +10,41 @@ type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
const electronUpdaterErrorFields = {
cause: Schema.Defect(),
};
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
"ElectronUpdaterCheckForUpdatesError",
{
...electronUpdaterErrorFields,
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Electron updater failed to check for updates.";
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
}
}
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
"ElectronUpdaterDownloadUpdateError",
{
...electronUpdaterErrorFields,
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Electron updater failed to download the update.";
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
}
}
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
"ElectronUpdaterQuitAndInstallError",
{
...electronUpdaterErrorFields,
channel: Schema.NullOr(Schema.String),
isSilent: Schema.Boolean,
isForceRunAfter: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Electron updater failed to quit and install the update.";
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
}
}
@@ -116,18 +117,33 @@ export const make = ElectronUpdater.of({
autoUpdater.disableDifferentialDownload = value;
return Effect.void;
}),
checkForUpdates: Effect.tryPromise({
try: () => autoUpdater.checkForUpdates(),
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ cause }),
}).pipe(Effect.asVoid),
downloadUpdate: Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ cause }),
}).pipe(Effect.asVoid),
checkForUpdates: Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.tryPromise({
try: () => autoUpdater.checkForUpdates(),
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ channel, cause }),
}).pipe(Effect.asVoid);
}),
downloadUpdate: Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
}).pipe(Effect.asVoid);
}),
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) =>
new ElectronUpdaterQuitAndInstallError({
channel,
isSilent,
isForceRunAfter,
cause,
}),
});
}),
on: (eventName, listener) => {
const eventTarget = autoUpdater as unknown as {
+79
View File
@@ -0,0 +1,79 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { vi } from "vite-plus/test";
import * as DesktopIpc from "./DesktopIpc.ts";
const invokeMethod: DesktopIpc.DesktopIpcMethod<never, never> = {
channel: "desktop.test.invoke",
handler: () => Effect.void,
};
const syncMethod: DesktopIpc.DesktopSyncIpcMethod<never, never> = {
channel: "desktop.test.sync",
handler: () => Effect.void,
};
function makeIpcMain(
overrides: Partial<DesktopIpc.DesktopIpcMain> = {},
): DesktopIpc.DesktopIpcMain {
return {
removeHandler: vi.fn(),
handle: vi.fn(),
removeAllListeners: vi.fn(),
on: vi.fn(),
...overrides,
};
}
describe("DesktopIpc", () => {
it.effect("preserves invoke registration context and cause", () =>
Effect.gen(function* () {
const cause = new Error("invoke registration failed");
const ipcMain = makeIpcMain({
handle: () => {
throw cause;
},
});
const ipc = DesktopIpc.make(ipcMain);
const error = yield* Effect.flip(Effect.scoped(ipc.handle(invokeMethod)));
assert.instanceOf(error, DesktopIpc.DesktopIpcRegistrationError);
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
assert.strictEqual(error.handlerKind, "invoke");
assert.strictEqual(error.channel, invokeMethod.channel);
assert.strictEqual(error.cause, cause);
assert.include(error.message, "invoke");
assert.include(error.message, invokeMethod.channel);
assert.notInclude(error.message, cause.message);
}),
);
it.effect("preserves sync unregistration context and cause in the finalizer defect", () =>
Effect.gen(function* () {
const cause = new Error("sync unregistration failed");
let removeCount = 0;
const ipcMain = makeIpcMain({
removeAllListeners: () => {
removeCount += 1;
if (removeCount === 2) throw cause;
},
});
const ipc = DesktopIpc.make(ipcMain);
const exit = yield* Effect.exit(Effect.scoped(ipc.handleSync(syncMethod)));
assert.isTrue(exit._tag === "Failure");
if (exit._tag === "Success") return;
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopIpc.DesktopIpcUnregistrationError);
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
assert.strictEqual(error.handlerKind, "sync");
assert.strictEqual(error.channel, syncMethod.channel);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}),
);
});
+78 -24
View File
@@ -24,6 +24,39 @@ export interface DesktopIpcMain {
on(channel: string, listener: DesktopIpcSyncListener): void;
}
export class DesktopIpcRegistrationError extends Schema.TaggedErrorClass<DesktopIpcRegistrationError>()(
"DesktopIpcRegistrationError",
{
handlerKind: Schema.Literals(["invoke", "sync"]),
channel: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to register the ${this.handlerKind} IPC handler for ${this.channel}.`;
}
}
export class DesktopIpcUnregistrationError extends Schema.TaggedErrorClass<DesktopIpcUnregistrationError>()(
"DesktopIpcUnregistrationError",
{
handlerKind: Schema.Literals(["invoke", "sync"]),
channel: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to unregister the ${this.handlerKind} IPC handler for ${this.channel}.`;
}
}
export const DesktopIpcError = Schema.Union([
DesktopIpcRegistrationError,
DesktopIpcUnregistrationError,
]);
export type DesktopIpcError = typeof DesktopIpcError.Type;
export const isDesktopIpcError = Schema.is(DesktopIpcError);
export interface DesktopIpcMethod<E, R> {
readonly channel: string;
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
@@ -39,10 +72,10 @@ export class DesktopIpc extends Context.Service<
{
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
}
>()("@t3tools/desktop/ipc/DesktopIpc") {}
@@ -57,18 +90,27 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease(
Effect.sync(() => {
ipcMain.removeHandler(channel);
ipcMain.handle(channel, (_event, raw) =>
runPromise(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler(raw);
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
),
);
Effect.try({
try: () => {
ipcMain.removeHandler(channel);
ipcMain.handle(channel, (_event, raw) =>
runPromise(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler(raw);
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
),
);
},
catch: (cause) =>
new DesktopIpcRegistrationError({ handlerKind: "invoke", channel, cause }),
}),
() => Effect.sync(() => ipcMain.removeHandler(channel)),
() =>
Effect.try({
try: () => ipcMain.removeHandler(channel),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
}).pipe(Effect.orDie),
);
}),
@@ -81,18 +123,30 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
const runSync = Effect.runSyncWith(context);
yield* Effect.acquireRelease(
Effect.sync(() => {
ipcMain.removeAllListeners(channel);
ipcMain.on(channel, (event) => {
event.returnValue = runSync(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler();
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync")),
);
});
Effect.try({
try: () => {
ipcMain.removeAllListeners(channel);
ipcMain.on(channel, (event) => {
event.returnValue = runSync(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler();
}).pipe(
Effect.annotateLogs({ channel }),
Effect.withSpan("desktop.ipc.invokeSync"),
),
);
});
},
catch: (cause) =>
new DesktopIpcRegistrationError({ handlerKind: "sync", channel, cause }),
}),
() => Effect.sync(() => ipcMain.removeAllListeners(channel)),
() =>
Effect.try({
try: () => ipcMain.removeAllListeners(channel),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
}).pipe(Effect.orDie),
);
}),
});
+203 -8
View File
@@ -7,9 +7,10 @@ import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import { TestClock } from "effect/testing";
import { beforeEach, describe, expect, vi } from "vite-plus/test";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as BrowserSession from "./BrowserSession.ts";
@@ -17,7 +18,7 @@ import * as PreviewManager from "./Manager.ts";
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
vi.hoisted(() => ({
createFromPath: vi.fn(() => ({ isEmpty: () => false })),
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
@@ -79,6 +80,7 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
const withManager = <A>(
use: (
@@ -237,6 +239,20 @@ describe("PreviewManager", () => {
expect(artifact.path).toMatch(
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
);
const captureCause = new Error("capture failed");
capturePage.mockRejectedValueOnce(captureCause);
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewOperationError",
operation: "captureScreenshot.capturePage",
tabId: "tab_1",
webContentsId: 42,
cause: captureCause,
});
}),
),
);
@@ -302,9 +318,12 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
expect(error).toMatchObject({
_tag: "PreviewArtifactPathOutsideDirectoryError",
artifactPath: "/tmp/t3/dev/settings.json",
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
});
expect("cause" in error).toBe(false);
}),
),
);
@@ -324,8 +343,20 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
expect(error).toMatchObject({
_tag: "PreviewArtifactPathOutsideDirectoryError",
artifactPath: "/tmp/t3/dev/settings.json",
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
});
expect("cause" in error).toBe(false);
createFromPath.mockReturnValueOnce({ isEmpty: () => true });
const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
expect(Exit.isFailure(invalidImageExit)).toBe(true);
if (Exit.isSuccess(invalidImageExit)) return;
expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({
_tag: "PreviewArtifactImageLoadError",
artifactPath,
});
}),
),
@@ -466,10 +497,174 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error.cause).toMatchObject({
name: "PreviewAutomationControlInterruptedError",
expect(error).toMatchObject({
_tag: "PreviewAutomationControlInterruptedError",
operation: "click",
tabId: "tab_1",
webContentsId: 42,
});
expect(error).toBeInstanceOf(Error);
if (error instanceof Error) {
expect(error.name).toBe("PreviewAutomationControlInterruptedError");
}
expect("cause" in error).toBe(false);
}),
),
);
effectIt.effect("derives evaluation detail kind and length from the same non-empty source", () =>
withManager((manager) =>
Effect.gen(function* () {
const text = "ReferenceError: fallbackDetail is not defined";
const exceptionDetails = {
text,
exception: { description: "" },
};
const sendCommand = vi.fn(async (method: string) =>
method === "Runtime.evaluate" ? { exceptionDetails } : undefined,
);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const exit = yield* Effect.exit(
manager.automationEvaluate("tab_1", { expression: "fallbackDetail" }),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewAutomationEvaluationError",
detailKind: "exception-text",
detailLength: text.length,
cause: exceptionDetails,
});
}),
),
);
});
describe("PreviewOperationError", () => {
it("keeps timeline detail separate from its structured message", () => {
const cause = new Error("CDP command failed with an invalid node id");
const error = new PreviewManager.PreviewOperationError({
operation: "click.DOM.resolveNode",
tabId: "tab_1",
webContentsId: 42,
cause,
});
expect(error.message).not.toContain(cause.message);
expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
});
});
describe("Preview automation diagnostics", () => {
it("keeps browser exception detail out of structural diagnostics", () => {
const secret = "unrelated-browser-payload-secret";
const detail = "ReferenceError: missingValue is not defined";
const cause = {
text: "Uncaught Error",
exception: { description: detail },
unsafePayload: secret,
};
const error = new PreviewManager.PreviewAutomationEvaluationError({
tabId: "tab_1",
detailKind: "exception-description",
detailLength: detail.length,
cause,
});
const encoded = encodePreviewManagerError(error);
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
readonly cause?: unknown;
};
expect(error.cause).toBe(cause);
expect(encodedCause).toStrictEqual(cause);
expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
expect(error.message).not.toContain(secret);
expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
expect("detail" in error).toBe(false);
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
secret,
);
});
it("retains bounded selector diagnostics without exposing selector or reason text", () => {
const selector = "role=button[name='selector-secret']";
const reason = "Unexpected token near reason-secret";
const cause = { invalidSelector: true as const, message: reason };
const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
operation: "click",
tabId: "tab_1",
selectorKind: "locator",
selectorLength: selector.length,
reasonLength: reason.length,
cause,
});
const encoded = encodePreviewManagerError(error);
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
readonly cause?: unknown;
};
expect(error.cause).toBe(cause);
expect(encodedCause).toStrictEqual(cause);
expect(error).toMatchObject({
selectorKind: "locator",
selectorLength: selector.length,
reasonLength: reason.length,
});
expect(error.detail).toEqual({
selectorKind: "locator",
selectorLength: selector.length,
});
expect(error.message).not.toContain("secret");
expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
expect("selector" in error).toBe(false);
expect("reason" in error).toBe(false);
expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
reason,
);
});
it("does not retain a missing target locator", () => {
const selector = "[data-token='target-secret']";
const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
operation: "scroll",
tabId: "tab_1",
selectorKind: "selector",
selectorLength: selector.length,
});
expect(error.message).not.toContain(selector);
expect(JSON.stringify(error)).not.toContain(selector);
expect("locator" in error).toBe(false);
});
});
File diff suppressed because it is too large. Load diff
@@ -3,10 +3,14 @@ import * as Effect from "effect/Effect";
import { describe, expect } from "vite-plus/test";
import {
extractPlaywrightInjectedRuntimeSource,
playwrightInjectedRuntimeInstallExpression,
playwrightInjectedRuntimeSource,
} from "./PlaywrightInjectedRuntime.ts";
const bundleWithSourceLiteral = (literal: string): string =>
`const source3 = ${literal};\n }\n});`;
describe("playwright injected runtime", () => {
effectIt.effect("extracts the pinned runtime from playwright-core", () =>
Effect.gen(function* () {
@@ -23,4 +27,54 @@ describe("playwright injected runtime", () => {
expect(expression).toContain('testIdAttributeName":"data-testid');
}),
);
effectIt.effect("reports a missing source marker without an artificial cause", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource("const source = 'missing';", "/tmp/coreBundle.js"),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceMarkerNotFoundError",
bundlePath: "/tmp/coreBundle.js",
marker: "source3 = ",
});
expect("cause" in error).toBe(false);
}),
);
effectIt.effect("keeps source validation metadata cause-free", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource(
bundleWithSourceLiteral('"short"'),
"/tmp/coreBundle.js",
),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceValidationError",
bundlePath: "/tmp/coreBundle.js",
actualType: "string",
actualLength: 5,
minimumLength: 100_000,
});
expect("cause" in error).toBe(false);
}),
);
effectIt.effect("preserves the source evaluation cause", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource(bundleWithSourceLiteral("("), "/tmp/coreBundle.js"),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceEvaluationError",
bundlePath: "/tmp/coreBundle.js",
timeoutMs: 1_000,
cause: expect.objectContaining({ name: "SyntaxError" }),
});
}),
);
});
@@ -4,69 +4,180 @@ import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeVM from "node:vm";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
const PLAYWRIGHT_SOURCE_MINIMUM_LENGTH = 100_000;
const PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS = 1_000;
const PLAYWRIGHT_SDK_LANGUAGE = "javascript";
const PLAYWRIGHT_BROWSER_NAME = "chromium";
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
"PlaywrightInjectedRuntimeError",
)<{
readonly operation: string;
readonly cause: unknown;
}> {
override get message() {
return `Playwright injected runtime operation failed: ${this.operation}`;
export class PlaywrightPackageResolveError extends Schema.TaggedErrorClass<PlaywrightPackageResolveError>()(
"PlaywrightPackageResolveError",
{
specifier: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to resolve Playwright package: ${this.specifier}`;
}
}
const fail = (operation: string, cause: unknown) =>
new PlaywrightInjectedRuntimeError({ operation, cause });
export class PlaywrightCoreBundleReadError extends Schema.TaggedErrorClass<PlaywrightCoreBundleReadError>()(
"PlaywrightCoreBundleReadError",
{
bundlePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read Playwright core bundle: ${this.bundlePath}`;
}
}
export class PlaywrightSourceMarkerNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceMarkerNotFoundError>()(
"PlaywrightSourceMarkerNotFoundError",
{
bundlePath: Schema.String,
marker: Schema.String,
},
) {
override get message(): string {
return `Playwright injected runtime marker ${JSON.stringify(this.marker)} was not found in ${this.bundlePath}`;
}
}
export class PlaywrightSourceTerminatorNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceTerminatorNotFoundError>()(
"PlaywrightSourceTerminatorNotFoundError",
{
bundlePath: Schema.String,
terminator: Schema.String,
},
) {
override get message(): string {
return `Playwright injected runtime terminator ${JSON.stringify(this.terminator)} was not found in ${this.bundlePath}`;
}
}
export class PlaywrightSourceEvaluationError extends Schema.TaggedErrorClass<PlaywrightSourceEvaluationError>()(
"PlaywrightSourceEvaluationError",
{
bundlePath: Schema.String,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to evaluate the Playwright injected runtime literal from ${this.bundlePath} within ${this.timeoutMs}ms`;
}
}
export class PlaywrightSourceValidationError extends Schema.TaggedErrorClass<PlaywrightSourceValidationError>()(
"PlaywrightSourceValidationError",
{
bundlePath: Schema.String,
actualType: Schema.String,
actualLength: Schema.NullOr(Schema.Number),
minimumLength: Schema.Number,
},
) {
override get message(): string {
const actual =
this.actualLength === null
? this.actualType
: `${this.actualType} with ${this.actualLength} characters`;
return `Playwright injected runtime from ${this.bundlePath} was ${actual}; expected a string with at least ${this.minimumLength} characters`;
}
}
export class PlaywrightOptionsEncodeError extends Schema.TaggedErrorClass<PlaywrightOptionsEncodeError>()(
"PlaywrightOptionsEncodeError",
{
sdkLanguage: Schema.String,
browserName: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode ${this.browserName} Playwright injected runtime options for ${this.sdkLanguage}`;
}
}
export const PlaywrightInjectedRuntimeError = Schema.Union([
PlaywrightPackageResolveError,
PlaywrightCoreBundleReadError,
PlaywrightSourceMarkerNotFoundError,
PlaywrightSourceTerminatorNotFoundError,
PlaywrightSourceEvaluationError,
PlaywrightSourceValidationError,
PlaywrightOptionsEncodeError,
]);
export type PlaywrightInjectedRuntimeError = typeof PlaywrightInjectedRuntimeError.Type;
export const extractPlaywrightInjectedRuntimeSource = Effect.fn(
"PlaywrightInjectedRuntime.extractSource",
)(function* (coreBundle: string, bundlePath: string) {
const start = coreBundle.indexOf(PLAYWRIGHT_SOURCE_MARKER);
if (start < 0) {
return yield* new PlaywrightSourceMarkerNotFoundError({
bundlePath,
marker: PLAYWRIGHT_SOURCE_MARKER,
});
}
const literalStart = start + PLAYWRIGHT_SOURCE_MARKER.length;
const literalEnd = coreBundle.indexOf(PLAYWRIGHT_SOURCE_TERMINATOR, literalStart);
if (literalEnd < 0) {
return yield* new PlaywrightSourceTerminatorNotFoundError({
bundlePath,
terminator: PLAYWRIGHT_SOURCE_TERMINATOR,
});
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () =>
NodeVM.runInNewContext(literal, Object.create(null), {
timeout: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
}),
catch: (cause) =>
new PlaywrightSourceEvaluationError({
bundlePath,
timeoutMs: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
cause,
}),
});
if (typeof source !== "string" || source.length < PLAYWRIGHT_SOURCE_MINIMUM_LENGTH) {
return yield* new PlaywrightSourceValidationError({
bundlePath,
actualType: typeof source,
actualLength: typeof source === "string" ? source.length : null,
minimumLength: PLAYWRIGHT_SOURCE_MINIMUM_LENGTH,
});
}
return source;
});
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
function* () {
const packageJsonPath = yield* Effect.try({
try: () => require.resolve("playwright-core/package.json"),
catch: (cause) => fail("resolvePackage", cause),
try: () => require.resolve(PLAYWRIGHT_PACKAGE_SPECIFIER),
catch: (cause) =>
new PlaywrightPackageResolveError({
specifier: PLAYWRIGHT_PACKAGE_SPECIFIER,
cause,
}),
});
const bundlePath = NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js");
const coreBundle = yield* Effect.tryPromise({
try: () =>
NodeFSP.readFile(
NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js"),
"utf8",
),
catch: (cause) => fail("readCoreBundle", cause),
try: () => NodeFSP.readFile(bundlePath, "utf8"),
catch: (cause) => new PlaywrightCoreBundleReadError({ bundlePath, cause }),
});
const marker = "source3 = ";
const start = coreBundle.indexOf(marker);
if (start < 0) {
return yield* fail(
"findSourceMarker",
new Error("Playwright injected runtime marker was not found."),
);
}
const literalStart = start + marker.length;
const literalEnd = coreBundle.indexOf(";\n }\n});", literalStart);
if (literalEnd < 0) {
return yield* fail(
"findSourceTerminator",
new Error("Playwright injected runtime terminator was not found."),
);
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () => NodeVM.runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
catch: (cause) => fail("evaluateSourceLiteral", cause),
});
if (typeof source !== "string" || source.length < 100_000) {
return yield* fail(
"validateSource",
new Error("Playwright injected runtime extraction returned invalid source."),
);
}
return source;
return yield* extractPlaywrightInjectedRuntimeSource(coreBundle, bundlePath);
},
);
@@ -76,14 +187,23 @@ export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
const source = yield* playwrightInjectedRuntimeSource();
const options = yield* encodeUnknownJson({
isUnderTest: false,
sdkLanguage: "javascript",
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
testIdAttributeName: "data-testid",
stableRafCount: 1,
browserName: "chromium",
browserName: PLAYWRIGHT_BROWSER_NAME,
shouldPrependErrorPrefix: false,
isUtilityWorld: false,
customEngines: [],
}).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
}).pipe(
Effect.mapError(
(cause) =>
new PlaywrightOptionsEncodeError({
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
browserName: PLAYWRIGHT_BROWSER_NAME,
cause,
}),
),
);
return `(() => {
if (globalThis.__t3PlaywrightInjected) return true;
const module = { exports: {} };
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts";
@@ -117,11 +118,13 @@ describe("DesktopClientSettings", () => {
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsWriteError);
assert.equal(error.operation, "replace-settings-file");
assert.equal(error.path, environment.clientSettingsPath);
assert.exists(error.cause);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.isString(error.cause.stack);
assert.equal(
error.message,
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
);
assert.notInclude(error.message, error.cause.message);
}),
),
);
@@ -25,7 +25,9 @@ const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
decodeLegacyClientSettingsDocumentJson(raw).pipe(
Effect.map((document) => document.settings),
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
Effect.catchTags({
SchemaError: () => decodeClientSettingsJsonValue(raw),
}),
);
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
@@ -36,7 +38,6 @@ const DesktopClientSettingsWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-settings-file",
]);
type DesktopClientSettingsWriteOperation = typeof DesktopClientSettingsWriteOperation.Type;
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
"DesktopClientSettingsWriteError",
@@ -51,13 +52,6 @@ export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<Des
}
}
const writeError = (
operation: DesktopClientSettingsWriteOperation,
path: string,
cause: unknown,
): DesktopClientSettingsWriteError =>
new DesktopClientSettingsWriteError({ operation, path, cause });
export class DesktopClientSettings extends Context.Service<
DesktopClientSettings,
{
@@ -96,19 +90,45 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)),
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "encode-document",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "replace-settings-file",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.settingsPath)
.pipe(
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
);
});
export const make = Effect.gen(function* () {
@@ -124,8 +144,13 @@ export const make = Effect.gen(function* () {
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.clientSettingsPath, cause),
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "create-temporary-file-name",
path: environment.clientSettingsPath,
cause,
}),
),
Effect.flatMap((suffix) =>
writeClientSettings({
@@ -1,15 +1,23 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
const textEncoder = new TextEncoder();
const isDesktopShellEnvironmentCommandError = Schema.is(
DesktopShellEnvironment.DesktopShellEnvironmentCommandError,
);
function envOutput(values: Readonly<Record<string, string>>): string {
return Object.entries(values)
.flatMap(([name, value]) => [
@@ -59,6 +67,7 @@ function runShellEnvironment(input: {
readonly env: NodeJS.ProcessEnv;
readonly platform: NodeJS.Platform;
readonly handler: (command: ChildProcess.Command) => string;
readonly failure?: PlatformError.PlatformError;
}) {
const environmentLayer = Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
@@ -68,7 +77,11 @@ function runShellEnvironment(input: {
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => Effect.succeed(makeProcess(input.handler(command)))),
ChildProcessSpawner.make((command) =>
input.failure === undefined
? Effect.succeed(makeProcess(input.handler(command)))
: Effect.fail(input.failure),
),
);
const program = Effect.gen(function* () {
@@ -229,4 +242,44 @@ describe("DesktopShellEnvironment", () => {
);
}),
);
it.effect("logs command failures with safe probe context and the exact cause", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/bash",
PATH: "/usr/bin",
};
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "spawn",
pathOrDescriptor: "/bin/bash",
});
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
return runShellEnvironment({
env,
platform: "linux",
handler: () => "",
failure: cause,
}).pipe(
Effect.andThen(
Effect.sync(() => {
const errors = messages
.flatMap((message) => (Array.isArray(message) ? message : [message]))
.filter(isDesktopShellEnvironmentCommandError);
assert.lengthOf(errors, 1);
assert.equal(errors[0]?.probe, "login-shell");
assert.equal(errors[0]?.executable, "bash");
assert.equal(errors[0]?.argumentCount, 2);
assert.notProperty(errors[0] ?? {}, "args");
assert.equal(errors[0]?.cause, cause);
assert.notInclude(errors[0]?.message ?? "", cause.message);
}),
),
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
);
});
});
@@ -3,6 +3,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -20,6 +21,44 @@ interface WindowsProbeOptions {
readonly loadProfile: boolean;
}
const DesktopShellEnvironmentProbe = Schema.Literals([
"login-shell",
"launchctl-path",
"powershell-profile",
"powershell-no-profile",
]);
type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
const desktopShellEnvironmentCommandFields = {
probe: DesktopShellEnvironmentProbe,
executable: Schema.String,
argumentCount: Schema.Number,
};
export class DesktopShellEnvironmentCommandError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandError>()(
"DesktopShellEnvironmentCommandError",
{
...desktopShellEnvironmentCommandFields,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
}
}
export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandTimeoutError>()(
"DesktopShellEnvironmentCommandTimeoutError",
{
...desktopShellEnvironmentCommandFields,
timeoutMs: Schema.Number,
},
) {
override get message(): string {
return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
}
}
export class DesktopShellEnvironment extends Context.Service<
DesktopShellEnvironment,
{
@@ -127,6 +166,18 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
const logShellEnvironmentCommandError = (
error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
) =>
Effect.logWarning(error).pipe(
Effect.annotateLogs({
component: "desktop-shell-environment",
error,
}),
);
const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
names
.map((name) => {
@@ -175,13 +226,14 @@ const extractEnvironment = (output: string, names: ReadonlyArray<string>): Envir
};
const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
readonly probe: DesktopShellEnvironmentProbe;
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly timeout: Duration.Duration;
readonly shell?: boolean;
}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return yield* spawner
const output = yield* spawner
.string(
ChildProcess.make(input.command, input.args, {
shell: input.shell ?? false,
@@ -193,10 +245,33 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
}),
)
.pipe(
Effect.mapError(
(cause) =>
new DesktopShellEnvironmentCommandError({
probe: input.probe,
executable: executableName(input.command),
argumentCount: input.args.length,
cause,
}),
),
Effect.catchTags({
DesktopShellEnvironmentCommandError: (error) =>
logShellEnvironmentCommandError(error).pipe(Effect.as("")),
}),
Effect.timeoutOption(input.timeout),
Effect.map(Option.getOrElse(() => "")),
Effect.orElseSucceed(() => ""),
);
if (Option.isSome(output)) {
return output.value;
}
const error = new DesktopShellEnvironmentCommandTimeoutError({
probe: input.probe,
executable: executableName(input.command),
argumentCount: input.args.length,
timeoutMs: Duration.toMillis(input.timeout),
});
yield* logShellEnvironmentCommandError(error);
return "";
});
const readLoginShellEnvironment = (
@@ -206,12 +281,14 @@ const readLoginShellEnvironment = (
names.length === 0
? Effect.succeed({})
: runCommandOutput({
probe: "login-shell",
command: shell,
args: ["-ilc", capturePosixEnvironmentCommand(names)],
timeout: LOGIN_SHELL_TIMEOUT,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath = runCommandOutput({
probe: "launchctl-path",
command: "/bin/launchctl",
args: ["getenv", "PATH"],
timeout: LAUNCHCTL_TIMEOUT,
@@ -234,6 +311,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
for (const command of WINDOWS_SHELL_CANDIDATES) {
const output = yield* runCommandOutput({
probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
command,
args,
timeout: LOGIN_SHELL_TIMEOUT,
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type * as Electron from "electron";
@@ -14,6 +14,18 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
export class DesktopApplicationMenuActionError extends Schema.TaggedErrorClass<DesktopApplicationMenuActionError>()(
"DesktopApplicationMenuActionError",
{
action: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop menu action "${this.action}" failed.`;
}
}
export class DesktopApplicationMenu extends Context.Service<
DesktopApplicationMenu,
{
@@ -100,12 +112,10 @@ export const make = Effect.gen(function* () {
effect.pipe(
Effect.annotateLogs({ action }),
Effect.withSpan("desktop.menu.action"),
Effect.catchCause((cause) =>
logMenuError("desktop menu action failed", {
action,
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
const error = new DesktopApplicationMenuActionError({ action, cause });
return logMenuError(error.message, { error });
}),
),
);
};
@@ -1,4 +1,5 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
@@ -7,6 +8,18 @@ import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
export class LiveActivityPreferenceSaveError extends Schema.TaggedErrorClass<LiveActivityPreferenceSaveError>()(
"LiveActivityPreferenceSaveError",
{
enabled: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to save the Live Activity updates setting (enabled: ${this.enabled}).`;
}
}
export function setLiveActivityUpdatesEnabled(input: {
readonly enabled: boolean;
readonly clerkToken: string | null;
@@ -15,7 +28,7 @@ export function setLiveActivityUpdatesEnabled(input: {
return Effect.gen(function* () {
yield* Effect.tryPromise({
try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }),
catch: (error) => error,
catch: (cause) => new LiveActivityPreferenceSaveError({ enabled: input.enabled, cause }),
});
yield* refreshAgentAwarenessRegistration();
@@ -1,5 +1,6 @@
import * as Notifications from "expo-notifications";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Platform } from "react-native";
export type NotificationPermissionResult =
@@ -7,9 +8,31 @@ export type NotificationPermissionResult =
| { readonly type: "granted" }
| { readonly type: "denied"; readonly canAskAgain: boolean };
export class NotificationPermissionReadError extends Schema.TaggedErrorClass<NotificationPermissionReadError>()(
"NotificationPermissionReadError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to read notification permissions on iOS.";
}
}
export class NotificationPermissionRequestError extends Schema.TaggedErrorClass<NotificationPermissionRequestError>()(
"NotificationPermissionRequestError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to request notification permissions on iOS.";
}
}
export const requestAgentNotificationPermission: Effect.Effect<
NotificationPermissionResult,
unknown
NotificationPermissionReadError | NotificationPermissionRequestError
> = Effect.gen(function* () {
if (Platform.OS !== "ios") {
return { type: "unsupported" };
@@ -17,7 +40,7 @@ export const requestAgentNotificationPermission: Effect.Effect<
const existing = yield* Effect.tryPromise({
try: () => Notifications.getPermissionsAsync(),
catch: (error) => error,
catch: (cause) => new NotificationPermissionReadError({ cause }),
});
if (existing.granted) {
return { type: "granted" };
@@ -36,7 +59,7 @@ export const requestAgentNotificationPermission: Effect.Effect<
allowSound: true,
},
}),
catch: (error) => error,
catch: (cause) => new NotificationPermissionRequestError({ cause }),
});
return requested.granted
? { type: "granted" }
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { hasTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
import {
CloudPublicConfigMissingError,
hasTracingPublicConfig,
resolveCloudPublicConfig,
resolveRelayClerkTokenOptions,
} from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
@@ -11,6 +16,12 @@ vi.mock("expo-constants", () => ({
}));
describe("resolveCloudPublicConfig", () => {
it("reports the missing Clerk JWT template as structured configuration", () => {
expect(() => resolveRelayClerkTokenOptions()).toThrowError(
new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" }),
);
});
it("returns no cloud configuration for an unconfigured build", () => {
expect(resolveCloudPublicConfig({})).toEqual({
clerk: {
+13 -1
View File
@@ -1,6 +1,18 @@
import Constants from "expo-constants";
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Schema from "effect/Schema";
export class CloudPublicConfigMissingError extends Schema.TaggedErrorClass<CloudPublicConfigMissingError>()(
"CloudPublicConfigMissingError",
{
key: Schema.Literal("T3CODE_CLERK_JWT_TEMPLATE"),
},
) {
override get message(): string {
return `${this.key} is not configured.`;
}
}
export interface CloudPublicConfig {
readonly clerk: {
@@ -87,7 +99,7 @@ export function hasTracingPublicConfig(
export function resolveRelayClerkTokenOptions() {
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
if (!jwtTemplate) {
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
throw new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" });
}
return relayClerkTokenOptions(jwtTemplate);
}
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vite-plus/test";
import { extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
import {
extractPairingUrlFromQrPayload,
PairingQrPayloadEmptyError,
parsePairingUrl,
} from "./pairing";
describe("extractPairingUrlFromQrPayload", () => {
it("trims raw pairing urls from qr payloads", () => {
@@ -18,7 +22,8 @@ describe("extractPairingUrlFromQrPayload", () => {
});
it("rejects empty qr payloads", () => {
expect(() => extractPairingUrlFromQrPayload(" ")).toThrow(
expect(() => extractPairingUrlFromQrPayload(" ")).toThrowError(PairingQrPayloadEmptyError);
expect(() => extractPairingUrlFromQrPayload(" ")).toThrowError(
"Scanned QR code did not contain a pairing URL.",
);
});
+11 -1
View File
@@ -1,7 +1,17 @@
import { readHostedPairingRequest } from "@t3tools/shared/remote";
import * as Schema from "effect/Schema";
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
export class PairingQrPayloadEmptyError extends Schema.TaggedErrorClass<PairingQrPayloadEmptyError>()(
"PairingQrPayloadEmptyError",
{},
) {
override get message(): string {
return "Scanned QR code did not contain a pairing URL.";
}
}
export function buildPairingUrl(host: string, code: string): string {
const h = host.trim();
const c = code.trim();
@@ -48,7 +58,7 @@ export function parsePairingUrl(url: string): { host: string; code: string } {
export function extractPairingUrlFromQrPayload(payload: string): string {
const trimmed = payload.trim();
if (!trimmed) {
throw new Error("Scanned QR code did not contain a pairing URL.");
throw new PairingQrPayloadEmptyError({});
}
try {
@@ -58,10 +58,23 @@ describe("resolveNativeReviewDiffView", () => {
it("returns null when the view manager cannot be required", async () => {
setExpoViewConfigAvailable();
const cause = new Error("boom");
expoMocks.requireNativeView.mockImplementation(() => {
throw new Error("boom");
throw cause;
});
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
expect(resolveNativeReviewDiffView()).toBeNull();
expect(resolveNativeReviewDiffView()).toBeNull();
expect(expoMocks.requireNativeView).toHaveBeenCalledTimes(1);
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NativeViewResolutionError",
nativeModuleName: "T3ReviewDiffSurface",
cause,
}),
);
expect(consoleError).toHaveBeenCalledTimes(1);
});
});
@@ -2,6 +2,8 @@ import type { ComponentType } from "react";
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { requireNativeView } from "expo";
import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
interface ExpoGlobalWithViewConfig {
@@ -128,6 +130,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {
}
let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
let nativeReviewDiffViewResolutionFailed = false;
function getExpoViewConfig(moduleName: string) {
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
@@ -140,6 +143,10 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
return cachedNativeReviewDiffView;
}
if (nativeReviewDiffViewResolutionFailed) {
return null;
}
if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
return null;
}
@@ -148,7 +155,14 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
NATIVE_REVIEW_DIFF_MODULE_NAME,
);
} catch {
} catch (cause) {
nativeReviewDiffViewResolutionFailed = true;
console.error(
new NativeViewResolutionError({
nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
cause,
}),
);
return null;
}
@@ -1,12 +1,13 @@
import { useMemo } from "react";
import { useCallback, useMemo } from "react";
import {
Markdown,
type CustomRenderers,
type NodeStyleOverrides,
type PartialMarkdownTheme,
} from "react-native-nitro-markdown";
import { Linking, ScrollView, Text as NativeText, View } from "react-native";
import { ScrollView, Text as NativeText, View } from "react-native";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import {
@@ -38,7 +39,7 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
<NativeText
onPress={() => {
if (href) {
void Linking.openURL(href);
void tryOpenExternalUrl(href, "markdown-link");
}
}}
style={{
@@ -143,12 +144,19 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
export function FileMarkdownPreview(props: { readonly markdown: string }) {
const styles = useMarkdownPreviewStyles();
const onLinkPress = useCallback((href: string) => {
void tryOpenExternalUrl(href, "markdown-link");
}, []);
return (
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
<View className="mx-auto w-full max-w-[760px]">
{hasNativeSelectableMarkdownText() ? (
<SelectableMarkdownText markdown={props.markdown} textStyle={styles.nativeTextStyle} />
<SelectableMarkdownText
markdown={props.markdown}
onLinkPress={onLinkPress}
textStyle={styles.nativeTextStyle}
/>
) : (
<Markdown
options={{ gfm: true }}
@@ -2,14 +2,7 @@ import Stack from "expo-router/stack";
import { SymbolView } from "expo-symbols";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
Linking,
Pressable,
ScrollView,
Text as RNText,
View,
} from "react-native";
import { ActivityIndicator, Pressable, ScrollView, Text as RNText, View } from "react-native";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import {
EnvironmentId,
@@ -23,6 +16,7 @@ import { CopyTextButton } from "../../components/CopyTextButton";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { cn } from "../../lib/cn";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -255,7 +249,7 @@ function FilePreviewHeader(props: {
)}
onPress={() => {
if (typeof props.externalPreviewUri === "string") {
void Linking.openURL(props.externalPreviewUri);
void tryOpenExternalUrl(props.externalPreviewUri, "file-preview");
}
}}
>
@@ -43,10 +43,23 @@ describe("resolveNativeTerminalSurfaceView", () => {
it("returns null when the view manager cannot be required", async () => {
setExpoViewConfigAvailable();
const cause = new Error("boom");
expoMocks.requireNativeView.mockImplementation(() => {
throw new Error("boom");
throw cause;
});
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
expect(resolveNativeTerminalSurfaceView()).toBeNull();
expect(resolveNativeTerminalSurfaceView()).toBeNull();
expect(expoMocks.requireNativeView).toHaveBeenCalledTimes(1);
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NativeViewResolutionError",
nativeModuleName: "T3TerminalSurface",
cause,
}),
);
expect(consoleError).toHaveBeenCalledTimes(1);
});
});
@@ -2,6 +2,8 @@ import type { ComponentType } from "react";
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { requireNativeView } from "expo";
import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
const NATIVE_TERMINAL_MODULE_NAME = "T3TerminalSurface";
interface ExpoGlobalWithViewConfig {
@@ -33,6 +35,7 @@ export interface NativeTerminalSurfaceProps extends ViewProps {
}
let cachedNativeTerminalSurfaceView: ComponentType<NativeTerminalSurfaceProps> | undefined;
let nativeTerminalSurfaceViewResolutionFailed = false;
function getExpoViewConfig(moduleName: string) {
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
@@ -45,6 +48,10 @@ export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminal
return cachedNativeTerminalSurfaceView;
}
if (nativeTerminalSurfaceViewResolutionFailed) {
return null;
}
if (getExpoViewConfig(NATIVE_TERMINAL_MODULE_NAME) == null) {
return null;
}
@@ -53,7 +60,14 @@ export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminal
cachedNativeTerminalSurfaceView = requireNativeView<NativeTerminalSurfaceProps>(
NATIVE_TERMINAL_MODULE_NAME,
);
} catch {
} catch (cause) {
nativeTerminalSurfaceViewResolutionFailed = true;
console.error(
new NativeViewResolutionError({
nativeModuleName: NATIVE_TERMINAL_MODULE_NAME,
cause,
}),
);
return null;
}
@@ -1,11 +1,12 @@
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useRef } from "react";
import { ActivityIndicator, Linking, Pressable, View } from "react-native";
import { ActivityIndicator, Pressable, View } from "react-native";
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { useThemeColor } from "../../lib/useThemeColor";
import type { GitActionProgress } from "../../state/use-vcs-action-state";
@@ -30,7 +31,7 @@ export function GitActionProgressOverlay(props: {
const handlePress = useCallback(() => {
if (progress.prUrl) {
void Linking.openURL(progress.prUrl);
void tryOpenExternalUrl(progress.prUrl, "pull-request");
return;
}
if (progress.phase === "success" || progress.phase === "error") {
@@ -13,8 +13,9 @@ import {
import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback, useMemo } from "react";
import { Alert, Linking } from "react-native";
import { Alert } from "react-native";
import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import {
basename,
getTerminalStatusLabel,
@@ -125,13 +126,8 @@ export function ThreadGitControls(props: {
Alert.alert("No open PR", "This branch does not have an open pull request.");
return;
}
try {
await Linking.openURL(prUrl);
} catch (error) {
Alert.alert(
"Unable to open PR",
error instanceof Error ? error.message : "An error occurred.",
);
if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
Alert.alert("Unable to open PR", "The pull request could not be opened.");
}
}, [gitStatus]);
@@ -8,11 +8,12 @@ import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo } from "react";
import { Alert, Linking, Pressable, ScrollView, View } from "react-native";
import { Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText";
import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
import { buildThreadReviewRoutePath } from "../../../lib/routes";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
@@ -83,13 +84,8 @@ export function GitOverviewSheet() {
Alert.alert("No open PR", "This branch does not have an open pull request.");
return;
}
try {
await Linking.openURL(prUrl);
} catch (error) {
Alert.alert(
"Unable to open PR",
error instanceof Error ? error.message : "An error occurred.",
);
if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
Alert.alert("Unable to open PR", "The pull request could not be opened.");
}
}, [gitStatus.data]);
@@ -0,0 +1,56 @@
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
export class ProjectThreadTaskRequiredError extends Schema.TaggedErrorClass<ProjectThreadTaskRequiredError>()(
"ProjectThreadTaskRequiredError",
{
environmentId: EnvironmentId,
projectId: ProjectId,
environmentMode: Schema.Literals(["local", "worktree"]),
},
) {
override get message(): string {
return "Enter a task before starting the thread.";
}
}
export class ProjectThreadBaseBranchRequiredError extends Schema.TaggedErrorClass<ProjectThreadBaseBranchRequiredError>()(
"ProjectThreadBaseBranchRequiredError",
{
environmentId: EnvironmentId,
projectId: ProjectId,
},
) {
override get message(): string {
return "Select a base branch before creating a worktree.";
}
}
export const ProjectThreadCreationValidationError = Schema.Union([
ProjectThreadTaskRequiredError,
ProjectThreadBaseBranchRequiredError,
]);
export type ProjectThreadCreationValidationError = typeof ProjectThreadCreationValidationError.Type;
export function validateProjectThreadCreation(input: {
readonly environmentId: EnvironmentId;
readonly projectId: ProjectId;
readonly environmentMode: "local" | "worktree";
readonly branch: string | null;
readonly initialMessageText: string;
}): ProjectThreadCreationValidationError | null {
if (input.initialMessageText.trim().length === 0) {
return new ProjectThreadTaskRequiredError({
environmentId: input.environmentId,
projectId: input.projectId,
environmentMode: input.environmentMode,
});
}
if (input.environmentMode === "worktree" && !input.branch) {
return new ProjectThreadBaseBranchRequiredError({
environmentId: input.environmentId,
projectId: input.projectId,
});
}
return null;
}
@@ -21,6 +21,7 @@ import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
import { validateProjectThreadCreation } from "./projectThreadCreationValidation";
function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
@@ -52,15 +53,16 @@ export function useCreateProjectThread() {
const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
if (initialMessageText.length === 0) {
const error = new Error("Enter a task before starting the thread.");
setPendingConnectionError(error.message);
return AsyncResult.failure(Cause.fail(error));
}
if (input.envMode === "worktree" && !input.branch) {
const error = new Error("Select a base branch before creating a worktree.");
setPendingConnectionError(error.message);
return AsyncResult.failure(Cause.fail(error));
const validationError = validateProjectThreadCreation({
environmentId: input.project.environmentId,
projectId: input.project.id,
environmentMode: input.envMode,
branch: input.branch,
initialMessageText,
});
if (validationError !== null) {
setPendingConnectionError(validationError.message);
return AsyncResult.failure(Cause.fail(validationError));
}
const isWorktree = input.envMode === "worktree";
@@ -0,0 +1,58 @@
import { Linking } from "react-native";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { tryOpenExternalUrl } from "./openExternalUrl";
vi.mock("react-native", () => ({
Linking: { openURL: vi.fn() },
}));
const openURL = vi.mocked(Linking.openURL);
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("tryOpenExternalUrl", () => {
it("opens supported URLs", async () => {
openURL.mockResolvedValue(undefined);
await expect(
tryOpenExternalUrl("https://github.com/pingdotgg/t3code", "pull-request"),
).resolves.toBe(true);
});
it("logs stable URL context without exposing the opening failure", async () => {
const cause = new Error("browser-unavailable-secret-sentinel");
openURL.mockRejectedValue(cause);
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
await expect(
tryOpenExternalUrl("https://github.com/pingdotgg/t3code/pull/1?token=secret", "pull-request"),
).resolves.toBe(false);
expect(consoleError).toHaveBeenCalledTimes(1);
const [message, attributes] = consoleError.mock.calls[0] ?? [];
expect(message).toBe("Failed to open pull-request URL with the https scheme.");
expect(attributes).toEqual(
expect.objectContaining({
_tag: "ExternalUrlOpenError",
target: "pull-request",
scheme: "https",
host: "github.com",
stack: expect.stringContaining("ExternalUrlOpenError"),
}),
);
expect(attributes).not.toHaveProperty("url");
expect(attributes).not.toHaveProperty("cause");
const diagnosticText = [message, ...Object.values(attributes as Record<string, unknown>)]
.map(String)
.join("\n");
expect(diagnosticText).not.toContain("token=secret");
expect(diagnosticText).not.toContain("browser-unavailable-secret-sentinel");
});
});
+51
View File
@@ -0,0 +1,51 @@
import * as Schema from "effect/Schema";
import { Linking } from "react-native";
const ExternalUrlTarget = Schema.Literals(["file-preview", "markdown-link", "pull-request"]);
export type ExternalUrlTarget = typeof ExternalUrlTarget.Type;
export class ExternalUrlOpenError extends Schema.TaggedErrorClass<ExternalUrlOpenError>()(
"ExternalUrlOpenError",
{
target: ExternalUrlTarget,
scheme: Schema.String,
host: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to open ${this.target} URL with the ${this.scheme} scheme.`;
}
}
function externalUrlMetadata(url: string): { readonly scheme: string; readonly host?: string } {
try {
const parsed = new URL(url);
return {
scheme: parsed.protocol.replace(/:$/, "") || "unknown",
host: parsed.hostname || undefined,
};
} catch {
return {
scheme: /^([a-z][a-z\d+.-]*):/i.exec(url)?.[1]?.toLowerCase() ?? "unknown",
};
}
}
export async function tryOpenExternalUrl(url: string, target: ExternalUrlTarget): Promise<boolean> {
try {
await Linking.openURL(url);
return true;
} catch (cause) {
const error = new ExternalUrlOpenError({ target, ...externalUrlMetadata(url), cause });
console.error(error.message, {
_tag: error._tag,
target: error.target,
scheme: error.scheme,
host: error.host,
stack: error.stack,
});
return false;
}
}
+31
View File
@@ -69,4 +69,35 @@ describe("mobile connection storage", () => {
toStableSavedRemoteConnection(managedConnection),
]);
});
it("preserves secure-storage read failures with operation and key context", async () => {
const cause = new Error("keychain unavailable");
mocks.getItemAsync.mockRejectedValueOnce(cause);
await expect(loadSavedConnections()).rejects.toMatchObject({
_tag: "MobileSecureStorageError",
operation: "read",
key: "t3code.connections",
cause,
message: "Mobile secure storage operation read failed for key t3code.connections.",
});
});
it("logs structured decode failures before using the empty fallback", async () => {
await mocks.setItemAsync("t3code.connections", "{");
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
await expect(loadSavedConnections()).resolves.toEqual([]);
expect(warn).toHaveBeenCalledWith(
"[mobile-storage] ignored invalid JSON",
expect.objectContaining({
_tag: "MobileStorageDecodeError",
key: "t3code.connections",
cause: expect.any(SyntaxError),
message: "Failed to decode mobile storage value for key t3code.connections.",
}),
);
warn.mockRestore();
});
});
+84 -11
View File
@@ -1,5 +1,6 @@
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import { EnvironmentId } from "@t3tools/contracts";
@@ -12,21 +13,72 @@ import {
const CONNECTIONS_KEY = "t3code.connections";
const PREFERENCES_KEY = "t3code.preferences";
const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
const MobileStorageKey = Schema.Literals([
CONNECTIONS_KEY,
PREFERENCES_KEY,
AGENT_AWARENESS_DEVICE_ID_KEY,
]);
type MobileStorageKeyValue = typeof MobileStorageKey.Type;
export class MobileSecureStorageError extends Schema.TaggedErrorClass<MobileSecureStorageError>()(
"MobileSecureStorageError",
{
operation: Schema.Literals(["read", "write", "generate-device-id"]),
key: MobileStorageKey,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Mobile secure storage operation ${this.operation} failed for key ${this.key}.`;
}
}
export class MobileStorageDecodeError extends Schema.TaggedErrorClass<MobileStorageDecodeError>()(
"MobileStorageDecodeError",
{
key: MobileStorageKey,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode mobile storage value for key ${this.key}.`;
}
}
export class MobileStorageEncodeError extends Schema.TaggedErrorClass<MobileStorageEncodeError>()(
"MobileStorageEncodeError",
{
key: MobileStorageKey,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode mobile storage value for key ${this.key}.`;
}
}
export interface Preferences {
readonly liveActivitiesEnabled?: boolean;
readonly terminalFontSize?: number;
}
async function readStorageItem(key: string): Promise<string | null> {
return await SecureStore.getItemAsync(key);
async function readStorageItem(key: MobileStorageKeyValue): Promise<string | null> {
try {
return await SecureStore.getItemAsync(key);
} catch (cause) {
throw new MobileSecureStorageError({ operation: "read", key, cause });
}
}
async function writeStorageItem(key: string, value: string): Promise<void> {
await SecureStore.setItemAsync(key, value);
async function writeStorageItem(key: MobileStorageKeyValue, value: string): Promise<void> {
try {
await SecureStore.setItemAsync(key, value);
} catch (cause) {
throw new MobileSecureStorageError({ operation: "write", key, cause });
}
}
async function readJsonStorageItem<T>(key: string): Promise<T | null> {
async function readJsonStorageItem<T>(key: MobileStorageKeyValue): Promise<T | null> {
const raw = (await readStorageItem(key)) ?? "";
if (!raw.trim()) {
return null;
@@ -34,11 +86,25 @@ async function readJsonStorageItem<T>(key: string): Promise<T | null> {
try {
return JSON.parse(raw) as T;
} catch {
} catch (cause) {
console.warn(
"[mobile-storage] ignored invalid JSON",
new MobileStorageDecodeError({ key, cause }),
);
return null;
}
}
async function writeJsonStorageItem(key: MobileStorageKeyValue, value: unknown) {
let encoded: string;
try {
encoded = JSON.stringify(value);
} catch (cause) {
throw new MobileStorageEncodeError({ key, cause });
}
await writeStorageItem(key, encoded);
}
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
const parsed = await readJsonStorageItem<{
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
@@ -67,7 +133,7 @@ export async function saveConnection(connection: SavedRemoteConnection): Promise
)
: pipe(current, Arr.append(stableConnection));
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
}
export async function clearSavedConnection(environmentId: EnvironmentId): Promise<void> {
@@ -76,7 +142,7 @@ export async function clearSavedConnection(environmentId: EnvironmentId): Promis
current,
Arr.filter((entry) => entry.environmentId !== environmentId),
);
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
}
export async function loadPreferences(): Promise<Preferences> {
@@ -106,7 +172,7 @@ export async function savePreferencesPatch(patch: Partial<Preferences>): Promise
...current,
...patch,
};
await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next));
await writeJsonStorageItem(PREFERENCES_KEY, next);
return next;
}
@@ -116,8 +182,15 @@ export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
return existing;
}
const { uuidv4 } = await import("./uuid");
const deviceId = uuidv4();
const deviceId = await import("./uuid")
.then(({ uuidv4 }) => uuidv4())
.catch((cause) => {
throw new MobileSecureStorageError({
operation: "generate-device-id",
key: AGENT_AWARENESS_DEVICE_ID_KEY,
cause,
});
});
await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
return deviceId;
}
@@ -0,0 +1,13 @@
import * as Schema from "effect/Schema";
export class NativeViewResolutionError extends Schema.TaggedErrorClass<NativeViewResolutionError>()(
"NativeViewResolutionError",
{
nativeModuleName: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to resolve native view ${this.nativeModuleName}.`;
}
}
+66 -15
View File
@@ -1,5 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { useEffect } from "react";
import { Atom } from "effect/unstable/reactivity";
@@ -11,6 +12,20 @@ const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
const COMPOSER_DRAFTS_FILE = "drafts.json";
const PERSIST_DEBOUNCE_MS = 200;
export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<ComposerDraftPersistenceError>()(
"ComposerDraftPersistenceError",
{
operation: Schema.Literals(["open", "read", "decode", "encode", "write", "hydrate"]),
directory: Schema.String,
fileName: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Composer draft persistence operation ${this.operation} failed for ${this.directory}/${this.fileName}.`;
}
}
export interface ComposerDraft {
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
@@ -56,12 +71,16 @@ async function getComposerDraftsFile() {
}
async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDraft>> {
let operation: ComposerDraftPersistenceError["operation"] = "open";
try {
const file = await getComposerDraftsFile();
if (!file.exists) {
return {};
}
const parsed = JSON.parse(await file.text()) as Partial<PersistedComposerDrafts>;
operation = "read";
const raw = await file.text();
operation = "decode";
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
return {};
}
@@ -75,30 +94,53 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
);
}),
);
} catch {
} catch (cause) {
console.warn(
"[composer-drafts] ignored persisted draft failure",
new ComposerDraftPersistenceError({
operation,
directory: COMPOSER_DRAFTS_DIRECTORY,
fileName: COMPOSER_DRAFTS_FILE,
cause,
}),
);
return {};
}
}
async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
const file = await getComposerDraftsFile();
const nonEmptyDrafts = Object.fromEntries(
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
const document: PersistedComposerDrafts = {
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
drafts: nonEmptyDrafts,
};
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
let operation: ComposerDraftPersistenceError["operation"] = "open";
try {
const file = await getComposerDraftsFile();
operation = "encode";
const nonEmptyDrafts = Object.fromEntries(
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
const document: PersistedComposerDrafts = {
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
drafts: nonEmptyDrafts,
};
const encoded = JSON.stringify(document);
operation = "write";
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(encoded);
} catch (cause) {
throw new ComposerDraftPersistenceError({
operation,
directory: COMPOSER_DRAFTS_DIRECTORY,
fileName: COMPOSER_DRAFTS_FILE,
cause,
});
}
file.write(JSON.stringify(document));
}
async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
try {
await writePersistedComposerDrafts(drafts);
} catch {
} catch (error) {
console.warn("[composer-drafts] failed to persist drafts", error);
// Draft persistence is best-effort; in-memory drafts still keep working.
}
}
@@ -128,7 +170,16 @@ export function ensureComposerDraftsLoaded(): void {
...current,
});
})
.catch(() => {
.catch((cause) => {
console.warn(
"[composer-drafts] failed to hydrate drafts",
new ComposerDraftPersistenceError({
operation: "hydrate",
directory: COMPOSER_DRAFTS_DIRECTORY,
fileName: COMPOSER_DRAFTS_FILE,
cause,
}),
);
// Draft loading is best-effort; in-memory drafts still keep working.
});
}
@@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
@@ -231,7 +232,12 @@ export function useThreadComposerState() {
appendComposerDraftAttachments(threadKey, images);
}
} catch (error) {
console.error("[native paste] error converting images", error);
console.error("[native paste] error converting images", {
environmentId: selectedThreadShell.environmentId,
threadId: selectedThreadShell.id,
uriCount: uris.length,
...safeErrorLogAttributes(error),
});
}
},
[composerDrafts, selectedThreadShell],
@@ -3,9 +3,12 @@ import { expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as TestClock from "effect/testing/TestClock";
import * as ServerConfig from "../config.ts";
import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
import { PersistenceSqlError } from "../persistence/Errors.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
@@ -33,6 +36,26 @@ const makePairingGrantStoreLayer = (
Layer.provide(makeServerConfigLayer(overrides)),
);
const makePairingGrantStoreTestLayer = (
overrides: Partial<AuthPairingLinks.AuthPairingLinkRepository["Service"]>,
) =>
Layer.effect(PairingGrantStore.PairingGrantStore, PairingGrantStore.make).pipe(
Layer.provide(
Layer.succeed(
AuthPairingLinks.AuthPairingLinkRepository,
AuthPairingLinks.AuthPairingLinkRepository.of({
create: () => Effect.void,
consumeAvailable: () => Effect.succeed(Option.none()),
listActive: () => Effect.succeed([]),
revoke: () => Effect.succeed(false),
getByCredential: () => Effect.succeed(Option.none()),
...overrides,
}),
),
),
Layer.provide(makeServerConfigLayer()),
);
it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
it.effect("issues pairing tokens in a short manual-entry format", () =>
Effect.gen(function* () {
@@ -186,4 +209,28 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
expect(revokedConsume._tag).toBe("UnavailableBootstrapCredentialError");
}).pipe(Effect.provide(makePairingGrantStoreLayer())),
);
it.effect("identifies consume-available failures and preserves their cause", () => {
const repositoryFailure = new PersistenceSqlError({
operation: "consume-pairing-link",
detail: "Database unavailable",
cause: new Error("database unavailable"),
});
return Effect.gen(function* () {
const pairingGrants = yield* PairingGrantStore.PairingGrantStore;
const error = yield* Effect.flip(pairingGrants.consume("credential"));
if (error._tag !== "BootstrapCredentialConsumeAvailableError") {
return yield* Effect.die(error);
}
expect(error.cause).toBe(repositoryFailure);
}).pipe(
Effect.provide(
makePairingGrantStoreTestLayer({
consumeAvailable: () => Effect.fail(repositoryFailure),
}),
),
);
});
});
+112 -48
View File
@@ -88,22 +88,38 @@ export class ActivePairingLinksLoadError extends Schema.TaggedErrorClass<ActiveP
export class PairingLinkRevokeError extends Schema.TaggedErrorClass<PairingLinkRevokeError>()(
"PairingLinkRevokeError",
{
pairingLinkId: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to revoke pairing link.";
return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
}
}
export class PairingCredentialIssueError extends Schema.TaggedErrorClass<PairingCredentialIssueError>()(
"PairingCredentialIssueError",
{
pairingLinkId: Schema.String,
subject: Schema.String,
label: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to issue pairing credential.";
return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
}
}
export class PairingCredentialRandomGenerationError extends Schema.TaggedErrorClass<PairingCredentialRandomGenerationError>()(
"PairingCredentialRandomGenerationError",
{
operation: Schema.Literals(["generate-id", "generate-token"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to generate pairing credential data during '${this.operation}'.`;
}
}
@@ -118,11 +134,36 @@ export class BootstrapCredentialConsumeError extends Schema.TaggedErrorClass<Boo
}
}
export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeAvailableError>()(
"BootstrapCredentialConsumeAvailableError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to atomically consume an available bootstrap credential.";
}
}
export class BootstrapCredentialLookupError extends Schema.TaggedErrorClass<BootstrapCredentialLookupError>()(
"BootstrapCredentialLookupError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to look up bootstrap credential state.";
}
}
export const BootstrapCredentialInternalError = Schema.Union([
ActivePairingLinksLoadError,
PairingLinkRevokeError,
PairingCredentialIssueError,
PairingCredentialRandomGenerationError,
BootstrapCredentialConsumeError,
BootstrapCredentialConsumeAvailableError,
BootstrapCredentialLookupError,
]);
export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
@@ -207,7 +248,14 @@ export const make = Effect.gen(function* () {
const generatePairingToken = Effect.gen(function* () {
let credential = "";
while (credential.length < PAIRING_TOKEN_LENGTH) {
const bytes = yield* crypto.randomBytes(PAIRING_TOKEN_LENGTH);
const bytes = yield* crypto
.randomBytes(PAIRING_TOKEN_LENGTH)
.pipe(
Effect.mapError(
(cause) =>
new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
),
);
for (const byte of bytes) {
if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
continue;
@@ -287,58 +335,73 @@ export const make = Effect.gen(function* () {
const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
function* (id) {
const revokedAt = yield* DateTime.now;
const revoked = yield* pairingLinks.revoke({
id,
revokedAt,
});
const revoked = yield* pairingLinks
.revoke({
id,
revokedAt,
})
.pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
if (revoked) {
yield* emitRemoved(id);
}
return revoked;
},
Effect.mapError((cause) => new PairingLinkRevokeError({ cause })),
);
const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
"PairingGrantStore.issueOneTimeToken",
)(
function* (input) {
const id = yield* crypto.randomUUIDv4;
const credential = yield* generatePairingToken;
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
const issued: IssuedBootstrapCredential = {
id,
credential,
...(input?.label ? { label: input.label } : {}),
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
expiresAt,
};
yield* pairingLinks.create({
)(function* (input) {
const id = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
),
);
const credential = yield* generatePairingToken;
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
const issued: IssuedBootstrapCredential = {
id,
credential,
...(input?.label ? { label: input.label } : {}),
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
expiresAt,
};
const subject = input?.subject ?? "one-time-token";
yield* pairingLinks
.create({
id,
credential,
method: "one-time-token",
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
subject,
label: input?.label ?? null,
proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
createdAt: now,
expiresAt: expiresAt,
});
yield* emitUpsert({
id,
credential,
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
...(input?.label ? { label: input.label } : {}),
createdAt: now,
expiresAt,
});
return issued;
},
Effect.mapError((cause) => new PairingCredentialIssueError({ cause })),
);
})
.pipe(
Effect.mapError(
(cause) =>
new PairingCredentialIssueError({
pairingLinkId: id,
subject,
...(input?.label ? { label: input.label } : {}),
cause,
}),
),
);
yield* emitUpsert({
id,
credential,
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
...(input?.label ? { label: input.label } : {}),
createdAt: now,
expiresAt,
});
return issued;
});
const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
function* (credential, input) {
@@ -420,12 +483,14 @@ export const make = Effect.gen(function* () {
return yield* seededResult.error;
}
const consumed = yield* pairingLinks.consumeAvailable({
credential,
proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
consumedAt: now,
now,
});
const consumed = yield* pairingLinks
.consumeAvailable({
credential,
proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
consumedAt: now,
now,
})
.pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
if (Option.isSome(consumed)) {
yield* emitRemoved(consumed.value.id);
@@ -441,7 +506,9 @@ export const make = Effect.gen(function* () {
} satisfies BootstrapGrant;
}
const matching = yield* pairingLinks.getByCredential({ credential });
const matching = yield* pairingLinks
.getByCredential({ credential })
.pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
if (Option.isNone(matching)) {
return yield* new UnknownBootstrapCredentialError({});
}
@@ -467,9 +534,6 @@ export const make = Effect.gen(function* () {
return yield* new UnavailableBootstrapCredentialError({});
},
Effect.mapError((cause) =>
isBootstrapCredentialError(cause) ? cause : new BootstrapCredentialConsumeError({ cause }),
),
);
return PairingGrantStore.of({
+102 -5
View File
@@ -3,7 +3,7 @@ import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { assert, it } from "@effect/vitest";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";
import * as Duration from "effect/Duration";
@@ -13,10 +13,19 @@ import * as TestClock from "effect/testing/TestClock";
import { vi } from "vite-plus/test";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { readBootstrapEnvelope } from "./bootstrap.ts";
import {
BootstrapEnvelopeDecodeError,
BootstrapFdStatError,
BootstrapInputStreamOpenError,
readBootstrapEnvelope,
} from "./bootstrap.ts";
import { assertNone, assertSome } from "@effect/vitest/utils";
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
const openSyncInterceptor = vi.hoisted(() => ({
failPath: null as string | null,
errorCode: "ENXIO",
}));
const fstatSyncInterceptor = vi.hoisted(() => ({ failFd: null as number | null }));
vi.mock("node:fs", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs")>();
@@ -29,12 +38,20 @@ vi.mock("node:fs", async (importOriginal) => {
filePath === openSyncInterceptor.failPath &&
flags === "r"
) {
const error = new Error("no such device or address");
Object.assign(error, { code: "ENXIO" });
const error = new Error(`open failed with ${openSyncInterceptor.errorCode}`);
Object.assign(error, { code: openSyncInterceptor.errorCode });
throw error;
}
return (actual.openSync as (...a: typeof args) => number)(...args);
},
fstatSync: (...args: Parameters<typeof actual.fstatSync>) => {
if (args[0] === fstatSyncInterceptor.failFd) {
const error = new Error("permission denied");
Object.assign(error, { code: "EACCES" });
throw error;
}
return (actual.fstatSync as (...a: typeof args) => NodeFS.Stats)(...args);
},
};
});
@@ -94,6 +111,39 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
}),
);
it.effect("preserves fd path, platform, and cause when opening the input stream fails", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const fdPath = `/proc/self/fd/${fd}`;
openSyncInterceptor.failPath = fdPath;
openSyncInterceptor.errorCode = "EIO";
try {
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
}).pipe(Effect.provideService(HostProcessPlatform, "linux"), Effect.flip);
assert.instanceOf(error, BootstrapInputStreamOpenError);
assert.equal(error.fd, fd);
assert.equal(error.platform, "linux");
assert.equal(error.fdPath, fdPath);
assert.equal((error.cause as NodeJS.ErrnoException).code, "EIO");
assert.equal(
error.message,
`Failed to open bootstrap input stream for file descriptor ${fd} via '${fdPath}' on 'linux'.`,
);
} finally {
openSyncInterceptor.failPath = null;
openSyncInterceptor.errorCode = "ENXIO";
}
}),
);
it.effect("returns none when the fd is unavailable", () =>
Effect.gen(function* () {
const fd = NodeFS.openSync("/dev/null", "r");
@@ -104,6 +154,53 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
}),
);
it.effect("preserves fd and cause when stat fails for a non-availability reason", () =>
Effect.gen(function* () {
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync("/dev/null", "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
fstatSyncInterceptor.failFd = fd;
try {
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
}).pipe(Effect.flip);
assert.instanceOf(error, BootstrapFdStatError);
assert.equal(error.fd, fd);
assert.equal((error.cause as NodeJS.ErrnoException).code, "EACCES");
assert.equal(error.message, `Failed to stat bootstrap file descriptor ${fd}.`);
} finally {
fstatSyncInterceptor.failFd = null;
}
}),
);
it.effect("preserves fd and schema cause when decoding the envelope fails", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(filePath, '{"mode":42}\n');
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
}).pipe(Effect.flip);
assert.instanceOf(error, BootstrapEnvelopeDecodeError);
assert.equal(error.fd, fd);
assert.isDefined(error.cause);
assert.equal(
error.message,
`Failed to decode bootstrap envelope from file descriptor ${fd}.`,
);
}),
);
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+78 -20
View File
@@ -4,7 +4,6 @@ import * as NodeNet from "node:net";
import * as NodeReadline from "node:readline";
import type * as NodeStream from "node:stream";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
@@ -13,10 +12,64 @@ import * as Schema from "effect/Schema";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
class BootstrapError extends Data.TaggedError("BootstrapError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class BootstrapFdStatError extends Schema.TaggedErrorClass<BootstrapFdStatError>()(
"BootstrapFdStatError",
{
fd: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to stat bootstrap file descriptor ${this.fd}.`;
}
}
export class BootstrapInputStreamOpenError extends Schema.TaggedErrorClass<BootstrapInputStreamOpenError>()(
"BootstrapInputStreamOpenError",
{
fd: Schema.Number,
platform: Schema.String,
fdPath: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const path = this.fdPath === undefined ? "" : ` via '${this.fdPath}'`;
return `Failed to open bootstrap input stream for file descriptor ${this.fd}${path} on '${this.platform}'.`;
}
}
export class BootstrapEnvelopeReadError extends Schema.TaggedErrorClass<BootstrapEnvelopeReadError>()(
"BootstrapEnvelopeReadError",
{
fd: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read bootstrap envelope from file descriptor ${this.fd}.`;
}
}
export class BootstrapEnvelopeDecodeError extends Schema.TaggedErrorClass<BootstrapEnvelopeDecodeError>()(
"BootstrapEnvelopeDecodeError",
{
fd: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode bootstrap envelope from file descriptor ${this.fd}.`;
}
}
export const BootstrapError = Schema.Union([
BootstrapFdStatError,
BootstrapInputStreamOpenError,
BootstrapEnvelopeReadError,
BootstrapEnvelopeDecodeError,
]);
export type BootstrapError = typeof BootstrapError.Type;
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
schema: Schema.Codec<A, I>,
@@ -32,7 +85,10 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
const timeoutMs = options?.timeoutMs ?? 1000;
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
return yield* Effect.callback<
Option.Option<A>,
BootstrapEnvelopeReadError | BootstrapEnvelopeDecodeError
>((resume) => {
const input = NodeReadline.createInterface({
input: stream,
crlfDelay: Infinity,
@@ -53,8 +109,8 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
}
resume(
Effect.fail(
new BootstrapError({
message: "Failed to read bootstrap envelope.",
new BootstrapEnvelopeReadError({
fd,
cause: error,
}),
),
@@ -68,8 +124,8 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
} else {
resume(
Effect.fail(
new BootstrapError({
message: "Failed to decode bootstrap envelope.",
new BootstrapEnvelopeDecodeError({
fd,
cause: parsed.failure,
}),
),
@@ -98,24 +154,24 @@ const isFdReady = (fd: number) =>
Effect.try({
try: () => NodeFS.fstatSync(fd),
catch: (error) =>
new BootstrapError({
message: "Failed to stat bootstrap fd.",
new BootstrapFdStatError({
fd,
cause: error,
}),
}).pipe(
Effect.as(true),
Effect.catchIf(
(error) => isUnavailableBootstrapFdError(error.cause),
() => Effect.succeed(false),
),
Effect.catchTags({
BootstrapFdStatError: (error) =>
isUnavailableBootstrapFdError(error.cause) ? Effect.succeed(false) : Effect.fail(error),
}),
);
const makeBootstrapInputStream = (fd: number) =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* Effect.try<NodeStream.Readable, BootstrapError>({
const fdPath = resolveFdPath(fd, platform);
return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({
try: () => {
const fdPath = resolveFdPath(fd, platform);
if (fdPath === undefined) {
return makeDirectBootstrapStream(fd);
}
@@ -139,8 +195,10 @@ const makeBootstrapInputStream = (fd: number) =>
}
},
catch: (error) =>
new BootstrapError({
message: "Failed to duplicate bootstrap fd.",
new BootstrapInputStreamOpenError({
fd,
platform,
...(fdPath === undefined ? {} : { fdPath }),
cause: error,
}),
});
@@ -1,6 +1,7 @@
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Result from "effect/Result";
import {
makeCloudCliOAuthConfig,
@@ -88,6 +89,27 @@ it.effect("requires Clerk OAuth config when the server bundle has no injected va
}).pipe(provideEnv({}), Effect.flip),
);
it.effect("reports malformed Clerk publishable keys as typed configuration failures", () =>
Effect.gen(function* () {
const result = yield* makeCloudCliOAuthConfig({
clerkPublishableKeyFallback: "pk_test_not-base64!!",
clerkCliOAuthClientIdFallback: "oauth_client_embedded",
}).pipe(provideEnv({}), Effect.result);
assert.isTrue(Result.isFailure(result));
if (Result.isFailure(result)) {
assert.equal(result.failure.cause._tag, "SourceError");
if (result.failure.cause._tag === "SourceError") {
assert.equal(
result.failure.cause.message,
"Failed to derive Clerk Frontend API URL from the publishable key.",
);
assert.instanceOf(result.failure.cause.cause, Error);
}
}
}),
);
it("resolves relay client tracing from runtime config with build-time fallback", () => {
const fallback = {
tracesUrl: "https://embedded.example.test/v1/traces",
+24 -10
View File
@@ -1,6 +1,7 @@
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -131,16 +132,29 @@ export function makeCloudCliOAuthConfig({
clerkCliOAuthClientIdFallback,
),
}).pipe(
Config.map(({ clerkPublishableKey, clientId }) => {
const clerkFrontendApiUrl = clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey);
return {
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
clientId,
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
scopes: CLOUD_CLI_OAUTH_SCOPES,
} satisfies CloudCliOAuthConfig;
}),
Config.mapOrFail(({ clerkPublishableKey, clientId }) =>
Effect.try({
try: () => clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey),
catch: (cause) =>
new Config.ConfigError(
new ConfigProvider.SourceError({
message: "Failed to derive Clerk Frontend API URL from the publishable key.",
cause,
}),
),
}).pipe(
Effect.map(
(clerkFrontendApiUrl) =>
({
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
clientId,
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
scopes: CLOUD_CLI_OAUTH_SCOPES,
}) satisfies CloudCliOAuthConfig,
),
),
),
);
}
@@ -6,6 +6,7 @@ import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
@@ -219,6 +220,44 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("keeps bounded command diagnostics when the process query exits unsuccessfully", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
code: 17,
stdout: "partial process output",
stderr: "process access denied",
}),
),
),
);
const error = yield* ProcessDiagnostics.readProcessRows.pipe(
Effect.provide(spawnerLayer),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.flip,
);
expect(error).toMatchObject({
_tag: "ProcessDiagnosticsQueryFailedError",
command: "ps",
argCount: 2,
cwd: process.cwd(),
exitCode: 17,
stdoutBytes: 22,
stderrBytes: 21,
stdoutTruncated: false,
stderrTruncated: false,
});
expect(error.message).toBe(
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
);
}),
);
it.effect("does not allow signaling the diagnostics query process", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
@@ -45,10 +45,15 @@ export class ProcessDiagnostics extends Context.Service<
class ProcessDiagnosticsQueryTimeoutError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryTimeoutError>()(
"ProcessDiagnosticsQueryTimeoutError",
{ command: Schema.String },
{
command: Schema.String,
argCount: Schema.Number,
cwd: Schema.String,
timeoutMillis: Schema.Number,
},
) {
override get message(): string {
return `Process diagnostics query '${this.command}' timed out.`;
return `Process diagnostics query '${this.command}' timed out after ${this.timeoutMillis}ms in '${this.cwd}'.`;
}
}
@@ -56,12 +61,19 @@ class ProcessDiagnosticsQueryFailedError extends Schema.TaggedErrorClass<Process
"ProcessDiagnosticsQueryFailedError",
{
command: Schema.String,
stderr: Schema.optional(Schema.String),
argCount: Schema.Number,
cwd: Schema.String,
exitCode: Schema.optional(Schema.Number),
stdoutBytes: Schema.optional(Schema.Number),
stderrBytes: Schema.optional(Schema.Number),
stdoutTruncated: Schema.optional(Schema.Boolean),
stderrTruncated: Schema.optional(Schema.Boolean),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return this.stderr?.trim() || `Failed to query process diagnostics with '${this.command}'.`;
const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
return `Process diagnostics query '${this.command}' failed${exitCode} in '${this.cwd}'.`;
}
}
@@ -76,7 +88,10 @@ class ProcessDiagnosticsServerProcessSignalError extends Schema.TaggedErrorClass
class ProcessDiagnosticsNotDescendantError extends Schema.TaggedErrorClass<ProcessDiagnosticsNotDescendantError>()(
"ProcessDiagnosticsNotDescendantError",
{ pid: Schema.Number },
{
pid: Schema.Number,
serverPid: Schema.Number,
},
) {
override get message(): string {
return `Process ${this.pid} is not a live descendant of the T3 server.`;
@@ -312,20 +327,29 @@ function makeResult(input: {
}
interface ProcessOutput {
readonly cwd: string;
readonly exitCode: number;
readonly stdout: string;
readonly stdoutBytes: number;
readonly stdoutTruncated: boolean;
readonly stderr: string;
readonly stderrBytes: number;
readonly stderrTruncated: boolean;
}
const runProcess = Effect.fn("runProcess")(
function* (input: { readonly command: string; readonly args: ReadonlyArray<string> }) {
const runProcess = Effect.fn("runProcess")(function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
}) {
const cwd = process.cwd();
return yield* Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
// shell mode would re-tokenize the PowerShell `-Command` payload (which
// contains pipes) before PowerShell ever sees it.
const child = yield* spawner.spawn(
ChildProcess.make(input.command, input.args, {
cwd: process.cwd(),
cwd,
}),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
@@ -346,36 +370,44 @@ const runProcess = Effect.fn("runProcess")(
);
return {
cwd,
exitCode,
stdout: stdout.text,
stdoutBytes: stdout.bytes,
stdoutTruncated: stdout.truncated,
stderr: stderr.text,
stderrBytes: stderr.bytes,
stderrTruncated: stderr.truncated,
} satisfies ProcessOutput;
},
(effect, input) =>
effect.pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new ProcessDiagnosticsQueryTimeoutError({
command: input.command,
}),
),
onSome: Effect.succeed,
}),
),
Effect.mapError((cause) =>
isProcessDiagnosticsError(cause)
? cause
: new ProcessDiagnosticsQueryFailedError({
}).pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new ProcessDiagnosticsQueryTimeoutError({
command: input.command,
cause,
argCount: input.args.length,
cwd,
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
}),
),
),
onSome: Effect.succeed,
}),
),
);
Effect.mapError((cause) =>
isProcessDiagnosticsError(cause)
? cause
: new ProcessDiagnosticsQueryFailedError({
command: input.command,
argCount: input.args.length,
cwd,
cause,
}),
),
);
});
function readPosixProcessRows(): Effect.Effect<
ReadonlyArray<ProcessRow>,
@@ -391,7 +423,13 @@ function readPosixProcessRows(): Effect.Effect<
? Effect.fail(
new ProcessDiagnosticsQueryFailedError({
command: "ps",
stderr: result.stderr.trim() || "ps failed.",
argCount: 2,
cwd: result.cwd,
exitCode: result.exitCode,
stdoutBytes: result.stdoutBytes,
stderrBytes: result.stderrBytes,
stdoutTruncated: result.stdoutTruncated,
stderrTruncated: result.stderrTruncated,
}),
)
: Effect.succeed(parsePosixProcessRows(result.stdout)),
@@ -421,7 +459,13 @@ function readWindowsProcessRows(): Effect.Effect<
? Effect.fail(
new ProcessDiagnosticsQueryFailedError({
command: "powershell.exe",
stderr: result.stderr.trim() || "PowerShell process query failed.",
argCount: 4,
cwd: result.cwd,
exitCode: result.exitCode,
stdoutBytes: result.stdoutBytes,
stderrBytes: result.stderrBytes,
stdoutTruncated: result.stdoutTruncated,
stderrTruncated: result.stderrTruncated,
}),
)
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
@@ -464,6 +508,7 @@ function assertDescendantPid(
: Effect.fail(
new ProcessDiagnosticsNotDescendantError({
pid,
serverPid: process.pid,
}),
);
}),
@@ -111,7 +111,7 @@ describe("ProcessResourceMonitor", () => {
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
lastFailure: null,
});
expect(Option.isNone(result.error)).toBe(true);
@@ -171,7 +171,7 @@ describe("ProcessResourceMonitor", () => {
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
lastFailure: null,
});
expect(result.topProcesses).toHaveLength(1);
@@ -218,11 +218,38 @@ describe("ProcessResourceMonitor", () => {
readAtMs: DateTime.toEpochMillis(sampledAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
lastFailure: null,
});
expect(result.topProcesses).toHaveLength(36);
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
}),
);
it.effect("exposes bounded failure diagnostics while retaining the exact cause", () =>
Effect.sync(() => {
const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const cause = new Error("stderr included credential=secret-value");
const failure = new ProcessResourceMonitor.ProcessResourceSamplingError({
failureTag: "ProcessDiagnosticsQueryFailedError",
cause,
});
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
samples: [],
readAt,
readAtMs: DateTime.toEpochMillis(readAt),
windowMs: 60_000,
bucketMs: 10_000,
lastFailure: failure,
});
expect(failure.cause).toBe(cause);
expect(Option.getOrThrow(result.error)).toEqual({
failureTag: "ProcessDiagnosticsQueryFailedError",
message: "Failed to sample process resources (ProcessDiagnosticsQueryFailedError).",
});
expect(Option.getOrThrow(result.error).message).not.toContain("secret-value");
}),
);
});
@@ -1,8 +1,10 @@
import type {
ServerProcessResourceHistoryBucket,
ServerProcessResourceHistoryInput,
ServerProcessResourceHistoryResult,
ServerProcessResourceHistorySummary,
import {
ServerProcessResourceHistoryFailureTag,
type ServerProcessResourceHistoryBucket,
type ServerProcessResourceHistoryFailureTag as ServerProcessResourceHistoryFailureTagType,
type ServerProcessResourceHistoryInput,
type ServerProcessResourceHistoryResult,
type ServerProcessResourceHistorySummary,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -10,6 +12,7 @@ import * as Effect from "effect/Effect";
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 ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
@@ -31,9 +34,21 @@ export interface ProcessResourceSample {
readonly isServerRoot: boolean;
}
export class ProcessResourceSamplingError extends Schema.TaggedErrorClass<ProcessResourceSamplingError>()(
"ProcessResourceSamplingError",
{
failureTag: ServerProcessResourceHistoryFailureTag,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to sample process resources (${this.failureTag}).`;
}
}
interface MonitorState {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly lastError: string | null;
readonly lastFailure: ProcessResourceSamplingError | null;
}
export class ProcessResourceMonitor extends Context.Service<
@@ -218,7 +233,7 @@ export function aggregateProcessResourceHistory(input: {
readonly readAtMs: number;
readonly windowMs: number;
readonly bucketMs: number;
readonly lastError: string | null;
readonly lastFailure: ProcessResourceSamplingError | null;
}): ServerProcessResourceHistoryResult {
const windowMs = Math.max(1_000, input.windowMs);
const bucketMs = Math.max(1_000, input.bucketMs);
@@ -239,13 +254,29 @@ export function aggregateProcessResourceHistory(input: {
totalCpuSecondsApprox,
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
topProcesses,
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
error: input.lastFailure
? Option.some({
failureTag: input.lastFailure.failureTag,
message: input.lastFailure.message,
})
: Option.none(),
};
}
export const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
const state = yield* Ref.make<MonitorState>({ samples: [], lastFailure: null });
const recordSamplingFailure = (cause: {
readonly _tag: ServerProcessResourceHistoryFailureTagType;
}) =>
Ref.update(state, (current) => ({
...current,
lastFailure: new ProcessResourceSamplingError({
failureTag: cause._tag,
cause,
}),
}));
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
@@ -261,15 +292,16 @@ export const make = Effect.gen(function* () {
});
yield* Ref.update(state, (current) => ({
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
lastError: null,
lastFailure: null,
}));
}).pipe(
Effect.catch((error: unknown) =>
Ref.update(state, (current) => ({
...current,
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
})),
),
Effect.catchTags({
ProcessDiagnosticsQueryTimeoutError: recordSamplingFailure,
ProcessDiagnosticsQueryFailedError: recordSamplingFailure,
ProcessDiagnosticsServerProcessSignalError: recordSamplingFailure,
ProcessDiagnosticsNotDescendantError: recordSamplingFailure,
ProcessDiagnosticsSignalFailedError: recordSamplingFailure,
}),
);
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
@@ -287,7 +319,7 @@ export const make = Effect.gen(function* () {
readAtMs,
windowMs: input.windowMs,
bucketMs: input.bucketMs,
lastError: current.lastError,
lastFailure: current.lastFailure,
});
});
@@ -1,16 +1,18 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "./ServerEnvironment.ts";
const isServerEnvironmentIdPersistenceError = Schema.is(
ServerEnvironment.ServerEnvironmentIdPersistenceError,
);
const makeServerEnvironmentLayer = (baseDir: string) =>
ServerEnvironment.layer.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
@@ -68,62 +70,63 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
}),
);
it.effect("fails instead of overwriting a persisted id when reading the file errors", () =>
it.effect("structures persisted environment id filesystem failures", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-environment-read-error-test-",
prefix: "t3-server-environment-error-test-",
});
const serverConfig = yield* makeServerConfig(baseDir);
const environmentIdPath = serverConfig.environmentIdPath;
yield* fileSystem.makeDirectory(NodePath.dirname(environmentIdPath), { recursive: true });
yield* fileSystem.writeFileString(environmentIdPath, "persisted-environment-id\n");
const writeAttempts: string[] = [];
const failingFileSystemLayer = FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === environmentIdPath),
readFileString: (path) =>
path === environmentIdPath
? Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
description: "permission denied",
pathOrDescriptor: path,
}),
)
: Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "readFileString",
description: "not found",
pathOrDescriptor: path,
}),
),
writeFileString: (path) => {
writeAttempts.push(path);
return Effect.void;
},
});
const methodByOperation = {
check: "exists",
read: "readFileString",
write: "writeFileString",
} as const;
const exit = yield* Effect.gen(function* () {
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
return yield* serverEnvironment.getDescriptor;
}).pipe(
Effect.provide(
ServerEnvironment.layer.pipe(
Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
for (const operation of ["check", "read", "write"] as const) {
const writeAttempts: string[] = [];
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: methodByOperation[operation],
description: "permission denied",
pathOrDescriptor: environmentIdPath,
});
const failingFileSystemLayer = FileSystem.layerNoop({
exists: () =>
operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
readFileString: () => Effect.fail(cause),
writeFileString: (path) => {
writeAttempts.push(path);
return Effect.fail(cause);
},
});
const error = yield* Effect.gen(function* () {
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
return yield* serverEnvironment.getDescriptor;
}).pipe(
Effect.provide(
ServerEnvironment.layer.pipe(
Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
),
),
),
Effect.exit,
);
Effect.flip,
);
expect(Exit.isFailure(exit)).toBe(true);
expect(writeAttempts).toEqual([]);
expect(yield* fileSystem.readFileString(environmentIdPath)).toBe(
"persisted-environment-id\n",
);
expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
if (!isServerEnvironmentIdPersistenceError(error)) {
throw error;
}
expect(error.operation).toBe(operation);
expect(error.environmentIdPath).toBe(environmentIdPath);
expect(error.cause).toBe(cause);
expect(error.message).toBe(
`Server environment ID ${operation} failed at '${environmentIdPath}'.`,
);
expect(writeAttempts).toEqual(operation === "write" ? [environmentIdPath] : []);
}
}),
);
});
@@ -6,12 +6,26 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import packageJson from "../../package.json" with { type: "json" };
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
export class ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(
"ServerEnvironmentIdPersistenceError",
{
operation: Schema.Literals(["check", "read", "write"]),
environmentIdPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
}
}
export class ServerEnvironment extends Context.Service<
ServerEnvironment,
{
@@ -55,22 +69,46 @@ export const make = Effect.gen(function* () {
const hostArchitecture = yield* HostProcessArchitecture;
const readPersistedEnvironmentId = Effect.gen(function* () {
const exists = yield* fileSystem
.exists(serverConfig.environmentIdPath)
.pipe(Effect.orElseSucceed(() => false));
const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
Effect.mapError(
(cause) =>
new ServerEnvironmentIdPersistenceError({
operation: "check",
environmentIdPath: serverConfig.environmentIdPath,
cause,
}),
),
);
if (!exists) {
return null;
}
const raw = yield* fileSystem
.readFileString(serverConfig.environmentIdPath)
.pipe(Effect.map((value) => value.trim()));
const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(
Effect.map((value) => value.trim()),
Effect.mapError(
(cause) =>
new ServerEnvironmentIdPersistenceError({
operation: "read",
environmentIdPath: serverConfig.environmentIdPath,
cause,
}),
),
);
return raw.length > 0 ? raw : null;
});
const persistEnvironmentId = (value: string) =>
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`);
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`).pipe(
Effect.mapError(
(cause) =>
new ServerEnvironmentIdPersistenceError({
operation: "write",
environmentIdPath: serverConfig.environmentIdPath,
cause,
}),
),
);
const environmentIdRaw = yield* Effect.gen(function* () {
const persisted = yield* readPersistedEnvironmentId;
@@ -138,7 +138,7 @@ describe("resolveServerEnvironmentLabel", () => {
Effect.fail(
new ProcessRunner.ProcessSpawnError({
command: "scutil",
args: ["--get", "ComputerName"],
argumentCount: 2,
cause: new Error("spawn scutil ENOENT"),
}),
),
+6 -1
View File
@@ -3377,13 +3377,18 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("hook: fail");
expect(errorMessage).toContain("Git command failed in GitVcsDriver.commit.commit");
expect(errorMessage).not.toContain("hook: fail");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: fail",
}),
expect.objectContaining({
kind: "action_failed",
phase: "commit",
+56
View File
@@ -49,6 +49,62 @@ it("normalizes empty successful notification responses to accepted", () => {
expect(resultResponse.status).toBe(200);
});
it.effect("returns bounded structural preview snapshot failures", () =>
Effect.scoped(
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const requests = yield* broker.connect({
clientId: "mcp-failure-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
ok: false,
error: {
_tag: "PreviewAutomationExecutionError",
message: "sensitive renderer failure",
detail: { consoleOutput: "sensitive browser output" },
},
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "mcp-failure-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
const snapshot = yield* server
.callTool({ name: "preview_snapshot", arguments: {} })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(snapshot.isError).toBe(true);
expect(snapshot.content).toEqual([{ type: "text", text: "Preview snapshot failed." }]);
expect(snapshot.structuredContent).toEqual({
error: {
_tag: "PreviewAutomationExecutionError",
operation: "snapshot",
failureCount: 1,
},
});
}),
).pipe(Effect.provide(TestLayer)),
);
it.effect("terminates HTTP MCP sessions with DELETE", () =>
Effect.scoped(
Effect.gen(function* () {
+47 -18
View File
@@ -88,6 +88,37 @@ const McpAuthMiddlewareLive = HttpRouter.middleware<{
provides: McpInvocationContext.McpInvocationContext;
}>()(makeMcpAuthMiddleware).layer;
const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
return Effect.failCause(cause).pipe(Effect.orDie);
}
const failures = cause.reasons.filter(Cause.isFailReason);
const firstFailure = failures[0]?.error;
const errorTag =
typeof firstFailure === "object" &&
firstFailure !== null &&
"_tag" in firstFailure &&
typeof firstFailure._tag === "string"
? firstFailure._tag
: "PreviewSnapshotError";
const result = new McpSchema.CallToolResult({
isError: true,
structuredContent: {
error: {
_tag: errorTag,
operation: "snapshot",
failureCount: failures.length,
},
},
content: [{ type: "text", text: "Preview snapshot failed." }],
});
return Effect.logWarning("preview snapshot failed", {
operation: "snapshot",
errorTag,
failureCount: failures.length,
}).pipe(Effect.as(result));
};
const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
@@ -122,12 +153,8 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
Effect.flatMap(Effect.fromOption),
Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.matchCause({
onFailure: (cause) =>
new McpSchema.CallToolResult({
isError: true,
content: [{ type: "text", text: Cause.pretty(cause) }],
}),
Effect.matchCauseEffect({
onFailure: previewSnapshotFailure,
onSuccess: ({ encodedResult }) => {
const snapshot = encodedResult as {
readonly screenshot: {
@@ -147,18 +174,20 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
height: screenshot.height,
},
};
return new McpSchema.CallToolResult({
isError: false,
structuredContent: metadata,
content: [
{ type: "text", text: JSON.stringify(metadata) },
{
type: "image",
data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
mimeType: screenshot.mimeType,
},
],
});
return Effect.succeed(
new McpSchema.CallToolResult({
isError: false,
structuredContent: metadata,
content: [
{ type: "text", text: JSON.stringify(metadata) },
{
type: "image",
data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
mimeType: screenshot.mimeType,
},
],
}),
);
},
}),
);
@@ -1,8 +1,10 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationClientDisconnectedError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationMalformedResponseError,
PreviewAutomationNoFocusedOwnerError,
PreviewAutomationUnavailableError,
ProviderInstanceId,
ThreadId,
type PreviewAutomationOwner,
@@ -59,6 +61,95 @@ it.effect("atomically registers a connected owner and correlates its response",
),
);
it.effect("preserves bounded request and remote selector diagnostics", () => {
const locator = "role=button[name='request-secret']";
const remoteMessage = "Unexpected token near remote-secret.";
const remoteError = {
_tag: "PreviewAutomationInvalidSelectorError",
message: remoteMessage,
detail: { selector: "role=button[name='remote-secret']" },
} as const;
return Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
ok: false,
error: remoteError,
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const error = yield* broker
.invoke<void>({
scope,
operation: "click",
input: { locator },
timeoutMs: 1_234,
})
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationInvalidSelectorError);
expect(error).toMatchObject({
operation: "click",
environmentId: scope.environmentId,
threadId: scope.threadId,
providerSessionId: scope.providerSessionId,
providerInstanceId: scope.providerInstanceId,
clientId: "client-1",
requestId: "preview-0",
tabId: "tab-1",
timeoutMs: 1_234,
selectorKind: "locator",
selectorLength: locator.length,
remoteTag: "PreviewAutomationInvalidSelectorError",
remoteMessageLength: remoteMessage.length,
remoteDetailKind: "object",
});
expect(error.message).toBe(
`Preview automation click received an invalid locator (${locator.length} characters).`,
);
expect(error.message).not.toContain("secret");
expect(error.cause).toBe(remoteError);
expect("selector" in error).toBe(false);
expect("remoteMessage" in error).toBe(false);
expect("remoteDetail" in error).toBe(false);
}),
);
});
it.effect("distinguishes malformed remote failures", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: false }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const error = yield* broker
.invoke<void>({ scope, operation: "status", input: {}, timeoutMs: 2_000 })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationMalformedResponseError);
expect(error).toMatchObject({
operation: "status",
environmentId: scope.environmentId,
threadId: scope.threadId,
providerSessionId: scope.providerSessionId,
providerInstanceId: scope.providerInstanceId,
clientId: "client-1",
requestId: "preview-0",
timeoutMs: 2_000,
});
}),
),
);
it.effect("rejects calls when no focused owner exists", () =>
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.make;
@@ -66,6 +157,13 @@ it.effect("rejects calls when no focused owner exists", () =>
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
expect(error).toMatchObject({
operation: "status",
environmentId: scope.environmentId,
threadId: scope.threadId,
providerSessionId: scope.providerSessionId,
providerInstanceId: scope.providerInstanceId,
});
}),
);
@@ -162,7 +260,17 @@ it.effect("fails requests assigned to a browser stream when that stream reconnec
const _replacementRequests = yield* broker.connect(makeOwner());
const error = yield* Fiber.join(pending);
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
expect(error).toMatchObject({
operation: "status",
environmentId: scope.environmentId,
threadId: scope.threadId,
providerSessionId: scope.providerSessionId,
providerInstanceId: scope.providerInstanceId,
clientId: "client-1",
requestId: "preview-0",
timeoutMs: 15_000,
});
}),
),
);
+149 -52
View File
@@ -1,12 +1,16 @@
import {
PreviewAutomationClientDisconnectedError,
PreviewAutomationControlInterruptedError,
PreviewAutomationExecutionError,
PreviewAutomationHostNotConnectedError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationMalformedResponseError,
PreviewAutomationNoFocusedOwnerError,
PreviewAutomationRemoteUnavailableError,
PreviewAutomationRequestQueueClosedError,
PreviewAutomationResultTooLargeError,
PreviewAutomationTabNotFoundError,
PreviewAutomationTimeoutError,
PreviewAutomationUnavailableError,
PreviewAutomationUnsupportedClientError,
type PreviewAutomationError,
type PreviewAutomationOperation,
@@ -62,6 +66,21 @@ interface ClientConnection {
interface PendingRequest {
readonly queue: ClientConnection["queue"];
readonly deferred: Deferred.Deferred<unknown, PreviewAutomationError>;
readonly context: PreviewAutomationRequestErrorContext;
}
interface PreviewAutomationRequestErrorContext {
readonly operation: PreviewAutomationOperation;
readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
readonly threadId: McpInvocationContext.McpInvocationScope["threadId"];
readonly providerSessionId: string;
readonly providerInstanceId: McpInvocationContext.McpInvocationScope["providerInstanceId"];
readonly clientId: string;
readonly requestId: string;
readonly tabId?: PreviewTabId;
readonly timeoutMs: number;
readonly selectorKind?: "locator" | "selector";
readonly selectorLength?: number;
}
interface BrokerState {
@@ -71,48 +90,104 @@ interface BrokerState {
readonly requestSequence: number;
}
const makeResponseError = (
const selectorDiagnosticsFromInput = (
input: unknown,
): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
if (typeof input !== "object" || input === null) return {};
if ("locator" in input && typeof input.locator === "string") {
return { selectorKind: "locator", selectorLength: input.locator.length };
}
if ("selector" in input && typeof input.selector === "string") {
return { selectorKind: "selector", selectorLength: input.selector.length };
}
return {};
};
type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
function remoteDetailKind(detail: unknown): RemoteDetailKind {
if (detail === null) return "null";
if (Array.isArray(detail)) return "array";
switch (typeof detail) {
case "string":
return "string";
case "number":
return "number";
case "boolean":
return "boolean";
default:
return "object";
}
}
const classifyResponseError = (
context: PreviewAutomationRequestErrorContext,
error: NonNullable<PreviewAutomationResponse["error"]>,
): PreviewAutomationError => {
const remoteDiagnostics = {
remoteTag: error._tag,
remoteMessageLength: error.message.length,
...(error.detail === undefined ? {} : { remoteDetailKind: remoteDetailKind(error.detail) }),
cause: error,
};
switch (error._tag) {
case "PreviewAutomationNoFocusedOwnerError":
return new PreviewAutomationNoFocusedOwnerError({ message: error.message });
return new PreviewAutomationNoFocusedOwnerError({
...context,
...remoteDiagnostics,
});
case "PreviewAutomationUnsupportedClientError":
return new PreviewAutomationUnsupportedClientError({ message: error.message });
return new PreviewAutomationUnsupportedClientError({
...context,
...remoteDiagnostics,
});
case "PreviewAutomationTabNotFoundError":
return new PreviewAutomationTabNotFoundError({ message: error.message });
return new PreviewAutomationTabNotFoundError({
...context,
...remoteDiagnostics,
});
case "PreviewAutomationTimeoutError":
return new PreviewAutomationTimeoutError({ message: error.message });
return new PreviewAutomationTimeoutError({
...context,
...remoteDiagnostics,
});
case "PreviewAutomationControlInterruptedError":
return new PreviewAutomationControlInterruptedError({ message: error.message });
return new PreviewAutomationControlInterruptedError({
...context,
...remoteDiagnostics,
});
case "PreviewAutomationInvalidSelectorError": {
const detail =
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
return new PreviewAutomationInvalidSelectorError({
message: error.message,
selector:
detail && "selector" in detail && typeof detail.selector === "string"
? detail.selector
: "",
...context,
...remoteDiagnostics,
});
}
case "PreviewAutomationResultTooLargeError": {
const detail =
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
const maximumBytes =
detail &&
"maximumBytes" in detail &&
typeof detail.maximumBytes === "number" &&
Number.isInteger(detail.maximumBytes) &&
detail.maximumBytes > 0
? detail.maximumBytes
: undefined;
return new PreviewAutomationResultTooLargeError({
message: error.message,
maximumBytes:
detail && "maximumBytes" in detail && typeof detail.maximumBytes === "number"
? detail.maximumBytes
: 64_000,
...context,
...remoteDiagnostics,
...(maximumBytes === undefined ? {} : { maximumBytes }),
});
}
case "PreviewAutomationUnavailableError":
return new PreviewAutomationUnavailableError({ message: error.message });
return new PreviewAutomationRemoteUnavailableError({
...context,
...remoteDiagnostics,
});
default:
return new PreviewAutomationExecutionError({
message: error.message,
detail: error.detail,
...context,
...remoteDiagnostics,
});
}
};
@@ -148,13 +223,8 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
});
yield* Effect.forEach(
toFail,
({ deferred }) =>
Deferred.fail(
deferred,
new PreviewAutomationUnavailableError({
message: "The preview automation client disconnected.",
}),
),
({ deferred, context }) =>
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
{ discard: true },
);
yield* Queue.shutdown(queue);
@@ -228,10 +298,8 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
yield* Deferred.fail(
pending.deferred,
response.error
? makeResponseError(response.error)
: new PreviewAutomationExecutionError({
message: "Preview automation failed without an error payload.",
}),
? classifyResponseError(pending.context, response.error)
: new PreviewAutomationMalformedResponseError(pending.context),
);
}
});
@@ -250,28 +318,60 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
if (!owner) {
if (candidates.length > 0) {
return yield* new PreviewAutomationUnavailableError({
message: "The browser host is not connected.",
const disconnectedOwner = candidates[0];
if (disconnectedOwner) {
return yield* new PreviewAutomationHostNotConnectedError({
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: disconnectedOwner.clientId,
});
}
return yield* new PreviewAutomationNoFocusedOwnerError({
message: "No desktop browser host is available for this thread.",
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
});
}
const connection = current.clients.get(owner.clientId);
if (!connection) {
return yield* new PreviewAutomationUnavailableError({
message: "The browser host is not connected.",
return yield* new PreviewAutomationHostNotConnectedError({
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: owner.clientId,
});
}
const timeoutMs = input.timeoutMs ?? 15_000;
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
const requestId = yield* SynchronizedRef.modify(state, (next) => {
const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {
const requestId = `preview-${next.requestSequence}`;
const tabId = input.tabId ?? owner.tabId ?? undefined;
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
const context: PreviewAutomationRequestErrorContext = {
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: owner.clientId,
requestId,
...(tabId === undefined ? {} : { tabId }),
timeoutMs,
...selectorDiagnostics,
};
const pending = new Map(next.pending);
pending.set(requestId, { queue: connection.queue, deferred });
return [requestId, { ...next, pending, requestSequence: next.requestSequence + 1 }] as const;
pending.set(requestId, { queue: connection.queue, deferred, context });
return [
[requestId, context] as const,
{ ...next, pending, requestSequence: next.requestSequence + 1 },
] as const;
});
const removePending = SynchronizedRef.update(state, (next) => {
if (!next.pending.has(requestId)) return next;
@@ -283,24 +383,21 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
const offered = yield* Queue.offer(connection.queue, {
requestId,
threadId: input.scope.threadId,
tabId: input.tabId ?? owner.tabId ?? undefined,
tabId: requestContext.tabId,
operation: input.operation,
input: input.input,
timeoutMs,
});
if (!offered) {
return yield* new PreviewAutomationUnavailableError({
message: "The preview automation client is no longer accepting requests.",
});
const completion = yield* Deferred.poll(deferred);
if (Option.isSome(completion)) {
return (yield* completion.value) as A;
}
return yield* new PreviewAutomationRequestQueueClosedError(requestContext);
}
const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(timeoutMs));
return yield* Option.match(result, {
onNone: () =>
Effect.fail(
new PreviewAutomationTimeoutError({
message: `Preview automation timed out after ${timeoutMs}ms.`,
}),
),
onNone: () => Effect.fail(new PreviewAutomationTimeoutError(requestContext)),
onSome: (value) => Effect.succeed(value as A),
});
});
@@ -10,8 +10,8 @@ import { AuthEnvironmentScopes } from "@t3tools/contracts";
import {
type AuthPairingLinkRepositoryError,
toPersistenceDecodeError,
toPersistenceSqlError,
PersistenceDecodeError,
PersistenceSqlError,
} from "./Errors.ts";
export const AuthPairingLinkRecord = Schema.Struct({
@@ -90,8 +90,8 @@ export class AuthPairingLinkRepository extends Context.Service<
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): AuthPairingLinkRepositoryError =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
: toPersistenceSqlError(sqlOperation)(cause);
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
: new PersistenceSqlError({ operation: sqlOperation, cause });
}
export const make = Effect.gen(function* () {
+4 -4
View File
@@ -15,8 +15,8 @@ import {
import {
type AuthSessionRepositoryError,
toPersistenceDecodeError,
toPersistenceSqlError,
PersistenceDecodeError,
PersistenceSqlError,
} from "./Errors.ts";
export const AuthSessionClientMetadataRecord = Schema.Struct({
@@ -146,8 +146,8 @@ function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionReco
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): AuthSessionRepositoryError =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
: toPersistenceSqlError(sqlOperation)(cause);
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
: new PersistenceSqlError({ operation: sqlOperation, cause });
}
export const make = Effect.gen(function* () {
@@ -0,0 +1,49 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { PersistenceDecodeError, PersistenceSqlError } from "./Errors.ts";
const decodeRuntimePayload = Schema.decodeUnknownEffect(
Schema.Struct({
runtimePayload: Schema.Struct({
attempt: Schema.Number,
}),
}),
);
it("keeps SQL operation context without a tautological detail", () => {
const cause = new Error("database unavailable");
const error = new PersistenceSqlError({
operation: "AuthSessionRepository.list:query",
cause,
});
assert.equal(error.operation, "AuthSessionRepository.list:query");
assert.equal(error.detail, undefined);
assert.equal(error.cause, cause);
assert.equal(error.message, "SQL error in AuthSessionRepository.list:query");
});
it.effect("maps schema errors without copying rejected payloads into diagnostics", () =>
Effect.gen(function* () {
const rejectedPayload = "runtime-payload-secret-sentinel";
const cause = yield* Effect.flip(
decodeRuntimePayload({
runtimePayload: {
attempt: rejectedPayload,
},
}),
);
const error = PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.list:decodeRows",
cause,
);
assert.equal(error.operation, "ProviderSessionRuntimeRepository.list:decodeRows");
assert.equal(error.cause, cause);
assert.notInclude(error.issue, rejectedPayload);
assert.notInclude(error.message, rejectedPayload);
assert.include(error.issue, "InvalidType");
}),
);
+30 -17
View File
@@ -1,6 +1,20 @@
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
function summarizeSchemaIssue(issue: SchemaIssue.Issue): string {
switch (issue._tag) {
case "Filter":
case "Encoding":
case "Pointer":
return `${issue._tag}(${summarizeSchemaIssue(issue.issue)})`;
case "Composite":
case "AnyOf":
return `${issue._tag}(${issue.issues.map(summarizeSchemaIssue).join(",")})`;
default:
return issue._tag;
}
}
// ===============================
// Core Persistence Errors
// ===============================
@@ -9,12 +23,14 @@ export class PersistenceSqlError extends Schema.TaggedErrorClass<PersistenceSqlE
"PersistenceSqlError",
{
operation: Schema.String,
detail: Schema.String,
detail: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `SQL error in ${this.operation}: ${this.detail}`;
return this.detail === undefined
? `SQL error in ${this.operation}`
: `SQL error in ${this.operation}: ${this.detail}`;
}
}
@@ -26,6 +42,14 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
cause: Schema.optional(Schema.Defect()),
},
) {
static fromSchemaError(operation: string, cause: Schema.SchemaError): PersistenceDecodeError {
return new PersistenceDecodeError({
operation,
issue: summarizeSchemaIssue(cause.issue),
cause,
});
}
override get message(): string {
return `Decode error in ${this.operation}: ${this.issue}`;
}
@@ -33,6 +57,7 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
const isPersistenceSqlError = Schema.is(PersistenceSqlError);
const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
// Kept for orchestration/projection call sites, which are being revamped separately.
export function toPersistenceSqlError(operation: string) {
return (cause: unknown): PersistenceSqlError =>
new PersistenceSqlError({
@@ -42,22 +67,10 @@ export function toPersistenceSqlError(operation: string) {
});
}
// Kept for orchestration/projection call sites, which are being revamped separately.
export function toPersistenceDecodeError(operation: string) {
return (error: Schema.SchemaError): PersistenceDecodeError =>
new PersistenceDecodeError({
operation,
issue: SchemaIssue.makeFormatterDefault()(error.issue),
cause: error,
});
}
export function toPersistenceDecodeCauseError(operation: string) {
return (cause: unknown): PersistenceDecodeError =>
new PersistenceDecodeError({
operation,
issue: `Failed to execute ${operation}`,
cause,
});
return (cause: Schema.SchemaError): PersistenceDecodeError =>
PersistenceDecodeError.fromSchemaError(operation, cause);
}
export const isPersistenceError = (u: unknown) =>
@@ -16,9 +16,9 @@ import {
} from "@t3tools/contracts";
import {
PersistenceDecodeError,
PersistenceSqlError,
type ProviderSessionRuntimeRepositoryError,
toPersistenceDecodeError,
toPersistenceSqlError,
} from "./Errors.ts";
/**
@@ -117,8 +117,8 @@ const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
: toPersistenceSqlError(sqlOperation)(cause);
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
: new PersistenceSqlError({ operation: sqlOperation, cause });
}
export const make = Effect.gen(function* () {
@@ -235,9 +235,10 @@ export const make = Effect.gen(function* () {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeRuntime(row).pipe(
Effect.mapError(
toPersistenceDecodeError(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
cause,
),
),
Effect.map((runtime) => Option.some(runtime)),
@@ -259,8 +260,11 @@ export const make = Effect.gen(function* () {
rows,
(row) =>
decodeRuntime(row).pipe(
Effect.mapError(
toPersistenceDecodeError("ProviderSessionRuntimeRepository.list:rowToRuntime"),
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.list:rowToRuntime",
cause,
),
),
),
{ concurrency: "unbounded" },
@@ -273,7 +277,11 @@ export const make = Effect.gen(function* () {
) =>
deleteRuntimeByThreadId(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"),
(cause) =>
new PersistenceSqlError({
operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
cause,
}),
),
);
+26
View File
@@ -1,5 +1,6 @@
import { it } from "@effect/vitest";
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
import { PreviewUrlNormalizationError } from "@t3tools/shared/preview";
import { Effect, PubSub } from "effect";
import { expect } from "vite-plus/test";
@@ -83,6 +84,31 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
const manager = yield* PreviewManager.PreviewManager;
const error = yield* Effect.flip(manager.open({ threadId, url: " " }));
expect(error._tag).toBe("PreviewInvalidUrlError");
expect(error).toMatchObject({ inputLength: 3, reason: "empty" });
expect(error).not.toHaveProperty("rawUrl");
expect(error.cause).toBeInstanceOf(PreviewUrlNormalizationError);
expect((error.cause as PreviewUrlNormalizationError).reason).toBe("empty");
}),
);
it.effect("preserves URL parser failures as the invalid URL cause chain", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const rawUrl = "https://user:[email protected]:bad/path?access_token=secret#fragment";
const error = yield* Effect.flip(manager.open({ threadId, url: rawUrl }));
expect(error).toMatchObject({
inputLength: rawUrl.length,
reason: "parse",
protocol: "https:",
});
expect(error).not.toHaveProperty("rawUrl");
expect(error.cause).toBeInstanceOf(PreviewUrlNormalizationError);
const normalizationError = error.cause as PreviewUrlNormalizationError;
expect(normalizationError.cause).toBeInstanceOf(Error);
expect(error.message).not.toContain((normalizationError.cause as Error).message);
expect(error.message).not.toMatch(/user|password|access_token|secret|fragment/);
}),
);
+17 -11
View File
@@ -24,9 +24,9 @@ import {
type PreviewSessionSnapshot,
} from "@t3tools/contracts";
import {
isPreviewUrlNormalizationError,
newPreviewTabId,
normalizePreviewUrl,
PreviewUrlNormalizationError,
} from "@t3tools/shared/preview";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -82,16 +82,22 @@ const sessionsForThread = (
const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
Effect.try({
try: () => normalizePreviewUrl(rawUrl),
catch: (cause) =>
new PreviewInvalidUrlError({
rawUrl,
detail:
cause instanceof PreviewUrlNormalizationError
? cause.detail
: cause instanceof Error
? cause.message
: String(cause),
}),
catch: (cause) => {
if (isPreviewUrlNormalizationError(cause)) {
return new PreviewInvalidUrlError({
inputLength: cause.inputLength,
reason: cause.reason,
protocol: cause.protocol,
cause,
});
}
return new PreviewInvalidUrlError({
inputLength: rawUrl.length,
reason: "unexpected",
cause,
});
},
});
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
+89 -3
View File
@@ -4,6 +4,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
@@ -55,7 +56,9 @@ function makeHandle(input: {
}
function makeSpawner(
f: (command: ChildProcessCommand) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle>,
f: (
command: ChildProcessCommand,
) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
) {
return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
}
@@ -159,6 +162,44 @@ describe("runProcess", () => {
);
});
it.effect("preserves resolved spawn context and cause", () =>
Effect.gen(function* () {
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcessSpawner",
method: "spawn",
pathOrDescriptor: "/actual/fake",
});
const spawner = makeSpawner(() => Effect.fail(cause));
const error = yield* runWith(spawner)({
command: "fake",
args: ["--flag", "secret-token-value"],
cwd: "/logical",
spawnCwd: "/actual",
}).pipe(Effect.flip);
expect(error._tag).toBe("ProcessSpawnError");
if (error._tag !== "ProcessSpawnError") {
return expect.fail("Expected ProcessSpawnError");
}
expect(error).toMatchObject({
command: "fake",
argumentCount: 2,
cwd: "/logical",
spawnCwd: "/actual",
resolvedCommand: "fake",
resolvedArgumentCount: 2,
shell: false,
});
expect(error.cause).toBe(cause);
expect(error.message).toBe("Failed to spawn process 'fake' in '/actual'");
expect(error).not.toHaveProperty("args");
expect(error).not.toHaveProperty("resolvedArgs");
expect(error.message).not.toContain("secret-token-value");
}),
);
it.effect("fails when output exceeds max buffer in default mode", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
@@ -169,7 +210,39 @@ describe("runProcess", () => {
maxOutputBytes: 128,
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
expect(error._tag).toBe("ProcessOutputLimitError");
if (error._tag !== "ProcessOutputLimitError") {
return expect.fail("Expected ProcessOutputLimitError");
}
expect(error).toMatchObject({
stream: "stdout",
maxBytes: 128,
observedBytes: 2048,
});
expect(error.message).toBe(
"Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
);
}),
);
it.effect("accepts output at the byte limit followed by an empty chunk", () =>
Effect.gen(function* () {
const output = new TextEncoder().encode("exactly");
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
stdout: Stream.make(output, new Uint8Array()),
}),
),
);
const result = yield* runWith(spawner)({
command: "fake",
args: ["exact-limit"],
maxOutputBytes: output.byteLength,
});
expect(result.stdout).toBe("exactly");
}),
);
@@ -272,6 +345,8 @@ describe("runProcess", () => {
const errorFiber = yield* runWith(spawner)({
command: "fake",
args: ["sleep"],
cwd: "/logical",
spawnCwd: "/actual",
timeout: "50 millis",
}).pipe(Effect.flip, Effect.forkScoped);
@@ -279,7 +354,18 @@ describe("runProcess", () => {
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(errorFiber);
expect(error).toBeInstanceOf(ProcessRunner.ProcessTimeoutError);
expect(error._tag).toBe("ProcessTimeoutError");
if (error._tag !== "ProcessTimeoutError") {
return expect.fail("Expected ProcessTimeoutError");
}
expect(error).toMatchObject({
command: "fake",
argumentCount: 1,
cwd: "/logical",
spawnCwd: "/actual",
timeoutMs: 50,
});
expect(error.message).toBe("Process 'fake' in '/actual' timed out after 50ms");
}),
);
+45 -20
View File
@@ -45,23 +45,29 @@ export interface ProcessRunOutput {
const ProcessInvocationFields = {
command: Schema.String,
args: Schema.Array(Schema.String),
argumentCount: Schema.Number,
cwd: Schema.optional(Schema.String),
spawnCwd: Schema.optional(Schema.String),
};
const formatProcessInvocation = (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly spawnCwd?: string | undefined;
}): string => {
const command = [input.command, ...input.args].join(" ");
return input.cwd === undefined ? `'${command}'` : `'${command}' in '${input.cwd}'`;
const executionCwd = input.spawnCwd ?? input.cwd;
return executionCwd === undefined
? `'${input.command}'`
: `'${input.command}' in '${executionCwd}'`;
};
export class ProcessSpawnError extends Schema.TaggedErrorClass<ProcessSpawnError>()(
"ProcessSpawnError",
{
...ProcessInvocationFields,
resolvedCommand: Schema.optional(Schema.String),
resolvedArgumentCount: Schema.optional(Schema.Number),
shell: Schema.optional(Schema.Boolean),
cause: Schema.Defect(),
},
) {
@@ -74,6 +80,7 @@ export class ProcessStdinError extends Schema.TaggedErrorClass<ProcessStdinError
"ProcessStdinError",
{
...ProcessInvocationFields,
stdinBytes: Schema.Number,
cause: Schema.Defect(),
},
) {
@@ -88,10 +95,11 @@ export class ProcessOutputLimitError extends Schema.TaggedErrorClass<ProcessOutp
...ProcessInvocationFields,
stream: Schema.Literals(["stdout", "stderr"]),
maxBytes: Schema.Number,
observedBytes: Schema.Number,
},
) {
override get message(): string {
return `Process ${formatProcessInvocation(this)} ${this.stream} exceeded ${this.maxBytes} bytes`;
return `Process ${formatProcessInvocation(this)} ${this.stream} produced ${this.observedBytes} bytes, exceeding the ${this.maxBytes} byte limit`;
}
}
@@ -120,12 +128,14 @@ export class ProcessTimeoutError extends Schema.TaggedErrorClass<ProcessTimeoutE
}
}
export type ProcessRunError =
| ProcessSpawnError
| ProcessStdinError
| ProcessOutputLimitError
| ProcessReadError
| ProcessTimeoutError;
export const ProcessRunError = Schema.Union([
ProcessSpawnError,
ProcessStdinError,
ProcessOutputLimitError,
ProcessReadError,
ProcessTimeoutError,
]);
export type ProcessRunError = typeof ProcessRunError.Type;
export class ProcessRunner extends Context.Service<
ProcessRunner,
@@ -163,6 +173,7 @@ const collectText = Effect.fn("processRunner.collectText")(function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly spawnCwd?: string | undefined;
readonly streamName: "stdout" | "stderr";
readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly maxOutputBytes: number;
@@ -174,8 +185,9 @@ const collectText = Effect.fn("processRunner.collectText")(function* (input: {
(cause) =>
new ProcessReadError({
command: input.command,
args: input.args,
argumentCount: input.args.length,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
stream: input.streamName,
cause,
}),
@@ -203,14 +215,16 @@ const collectText = Effect.fn("processRunner.collectText")(function* (input: {
() => ({ chunks: [], bytes: 0 }),
(state, chunk) => {
const remainingBytes = input.maxOutputBytes - state.bytes;
if (remainingBytes <= 0 || chunk.byteLength > remainingBytes) {
if (chunk.byteLength > remainingBytes) {
return Effect.fail(
new ProcessOutputLimitError({
command: input.command,
args: input.args,
argumentCount: input.args.length,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
stream: input.streamName,
maxBytes: input.maxOutputBytes,
observedBytes: state.bytes + chunk.byteLength,
}),
);
}
@@ -259,8 +273,9 @@ function finalizeRunProcess<R>(
return Effect.fail(
new ProcessTimeoutError({
command: input.command,
args: input.args,
argumentCount: input.args.length,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
timeoutMs: Duration.toMillis(timeout),
}),
);
@@ -300,23 +315,30 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
(cause) =>
new ProcessSpawnError({
command: input.command,
args: input.args,
argumentCount: input.args.length,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
resolvedCommand: spawnCommand.command,
resolvedArgumentCount: spawnCommand.args.length,
shell: spawnCommand.shell,
cause,
}),
),
);
const stdin = input.stdin;
const writeStdin =
input.stdin === undefined
stdin === undefined
? Effect.void
: Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
: Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
Effect.mapError(
(cause) =>
new ProcessStdinError({
command: input.command,
args: input.args,
argumentCount: input.args.length,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
stdinBytes: Buffer.byteLength(stdin),
cause,
}),
),
@@ -328,6 +350,7 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
command: input.command,
args: input.args,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
streamName: "stdout",
stream: child.stdout,
maxOutputBytes,
@@ -338,6 +361,7 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
command: input.command,
args: input.args,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
streamName: "stderr",
stream: child.stderr,
maxOutputBytes,
@@ -354,8 +378,9 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
(cause) =>
new ProcessReadError({
command: input.command,
args: input.args,
argumentCount: input.args.length,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
stream: "exitCode",
cause,
}),
@@ -3,11 +3,16 @@ import { type OrchestrationProject, ProjectId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as TerminalManager from "../terminal/Manager.ts";
import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
const isProjectSetupScriptOperationError = Schema.is(
ProjectSetupScriptRunner.ProjectSetupScriptOperationError,
);
const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({
id: ProjectId.make("project-1"),
title: "Project",
@@ -145,4 +150,50 @@ describe("ProjectSetupScriptRunner", () => {
}).pipe(Effect.provide(testLayer(project, { open, write })));
},
);
it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
const rootCause = new Error("stat failed");
const terminalError = new TerminalManager.TerminalCwdError({
cwd: "/repo/worktrees/a",
reason: "statFailed",
cause: rootCause,
});
const project = makeProject([
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]);
return Effect.gen(function* () {
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
const error = yield* runner
.runForThread({
threadId: "thread-1",
projectId: "project-1",
worktreePath: "/repo/worktrees/a",
})
.pipe(Effect.flip);
expect(isProjectSetupScriptOperationError(error)).toBe(true);
if (isProjectSetupScriptOperationError(error)) {
expect(error.operation).toBe("openTerminal");
expect(error.threadId).toBe("thread-1");
expect(error.projectId).toBe("project-1");
expect(error.worktreePath).toBe("/repo/worktrees/a");
expect(error.cause).toBe(terminalError);
expect(terminalError.cause).toBe(rootCause);
}
}).pipe(
Effect.provide(
testLayer(project, {
open: () => Effect.fail(terminalError),
write: () => Effect.die("unexpected write"),
}),
),
);
});
});
@@ -59,7 +59,7 @@ export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedErrorCl
},
) {
override get message(): string {
return "Project was not found for setup script execution.";
return `Project was not found for setup script execution for thread '${this.threadId}' in '${this.worktreePath}'.`;
}
}
@@ -78,32 +78,6 @@ export class ProjectSetupScriptRunner extends Context.Service<
}
>()("t3/project/ProjectSetupScriptRunner") {}
const isProjectSetupScriptRunnerError = Schema.is(ProjectSetupScriptRunnerError);
function operationError(
input: ProjectSetupScriptRunnerInput,
operation: ProjectSetupScriptOperationError["operation"],
cause: unknown,
): ProjectSetupScriptOperationError {
return new ProjectSetupScriptOperationError({
threadId: input.threadId,
worktreePath: input.worktreePath,
operation,
cause,
...(input.projectId === undefined ? {} : { projectId: input.projectId }),
...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
});
}
function mapRunnerError(
input: ProjectSetupScriptRunnerInput,
operation: ProjectSetupScriptOperationError["operation"],
) {
return Effect.mapError((cause: unknown) =>
isProjectSetupScriptRunnerError(cause) ? cause : operationError(input, operation, cause),
);
}
export const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const terminalManager = yield* TerminalManager.TerminalManager;
@@ -111,26 +85,43 @@ export const make = Effect.gen(function* () {
const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
"ProjectSetupScriptRunner.runForThread",
)(function* (input) {
const errorContext = {
threadId: input.threadId,
worktreePath: input.worktreePath,
...(input.projectId === undefined ? {} : { projectId: input.projectId }),
...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
};
const projectById = input.projectId
? yield* projectionSnapshotQuery
.getProjectShellById(ProjectId.make(input.projectId))
.pipe(Effect.map(Option.getOrUndefined), mapRunnerError(input, "resolveProject"))
? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe(
Effect.map(Option.getOrUndefined),
Effect.mapError(
(cause) =>
new ProjectSetupScriptOperationError({
...errorContext,
operation: "resolveProject",
cause,
}),
),
)
: null;
const project =
projectById ??
(input.projectCwd
? yield* projectionSnapshotQuery
.getActiveProjectByWorkspaceRoot(input.projectCwd)
.pipe(Effect.map(Option.getOrUndefined), mapRunnerError(input, "resolveProject"))
? yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe(
Effect.map(Option.getOrUndefined),
Effect.mapError(
(cause) =>
new ProjectSetupScriptOperationError({
...errorContext,
operation: "resolveProject",
cause,
}),
),
)
: null);
if (!project) {
return yield* new ProjectSetupScriptProjectNotFoundError({
threadId: input.threadId,
worktreePath: input.worktreePath,
...(input.projectId === undefined ? {} : { projectId: input.projectId }),
...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
});
return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
}
const script = setupProjectScript(project.scripts);
@@ -155,14 +146,32 @@ export const make = Effect.gen(function* () {
worktreePath: input.worktreePath,
env,
})
.pipe(mapRunnerError(input, "openTerminal"));
.pipe(
Effect.mapError(
(cause) =>
new ProjectSetupScriptOperationError({
...errorContext,
operation: "openTerminal",
cause,
}),
),
);
yield* terminalManager
.write({
threadId: input.threadId,
terminalId,
data: `${script.command}\r`,
})
.pipe(mapRunnerError(input, "writeCommand"));
.pipe(
Effect.mapError(
(cause) =>
new ProjectSetupScriptOperationError({
...errorContext,
operation: "writeCommand",
cause,
}),
),
);
return {
status: "started",
@@ -35,7 +35,7 @@ import * as TestClock from "effect/testing/TestClock";
import { attachmentRelativePath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { ProviderAdapterProcessError, ProviderAdapterValidationError } from "../Errors.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { makeClaudeAdapter, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
@@ -298,6 +298,44 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("retains Claude session startup causes without exposing their messages", () => {
const cause = new Error("credential material that must remain in the cause chain");
const layer = Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = decodeClaudeSettings({});
return yield* makeClaudeAdapter(claudeConfig, {
createQuery: () => {
throw cause;
},
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const error = yield* adapter
.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
})
.pipe(Effect.flip);
assert.instanceOf(error, ProviderAdapterProcessError);
assert.equal(error.detail, "Failed to start Claude runtime session.");
assert.strictEqual(error.cause, cause);
assert.notMatch(error.message, /credential material/u);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(layer),
);
});
it.effect("derives bypass permission mode from full-access runtime policy", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1365,19 +1403,14 @@ describe("ClaudeAdapterLive", () => {
it.effect("closes the session when the Claude stream aborts after a turn starts", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const context = yield* Effect.context<never>();
const runFork = Effect.runForkWith(context);
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = runFork(
Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
),
);
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
@@ -1430,6 +1463,57 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("keeps Claude stream failure events structural", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: THREAD_ID,
input: "hello",
attachments: [],
});
harness.query.fail(new Error("credential material that must stay in the cause chain"));
yield* Effect.yieldNow;
yield* Effect.yieldNow;
yield* Effect.yieldNow;
runtimeEventsFiber.interruptUnsafe();
const runtimeError = runtimeEvents.find((event) => event.type === "runtime.error");
assert.equal(runtimeError?.type, "runtime.error");
if (runtimeError?.type === "runtime.error") {
assert.equal(runtimeError.payload.message, "Claude runtime stream failed.");
assert.deepEqual(runtimeError.payload.detail, {
failureCount: 1,
failureTags: ["ProviderAdapterProcessError"],
});
}
const completed = runtimeEvents.find((event) => event.type === "turn.completed");
assert.equal(completed?.type, "turn.completed");
if (completed?.type === "turn.completed") {
assert.equal(completed.payload.state, "failed");
assert.equal(completed.payload.errorMessage, "Claude runtime stream failed.");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("closes the previous session before replacing an existing thread session", () => {
const queries: FakeClaudeQuery[] = [];
const layer = Layer.effect(
@@ -1542,14 +1626,12 @@ describe("ClaudeAdapterLive", () => {
);
return Effect.gen(function* () {
const context = yield* Effect.context<never>();
const runFork = Effect.runForkWith(context);
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = runFork(
Stream.runForEach(adapter.streamEvents, () => Effect.void),
);
const runtimeEventsFiber = yield* Stream.runForEach(
adapter.streamEvents,
() => Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
@@ -249,21 +249,8 @@ function toMessage(cause: unknown, fallback: string): string {
return fallback;
}
function toProcessError(
cause: unknown,
fallback: string,
threadId: ThreadId,
): ProviderAdapterProcessError {
return new ProviderAdapterProcessError({
provider: PROVIDER,
threadId,
detail: toMessage(cause, fallback),
cause,
});
}
function normalizeClaudeStreamMessages(
cause: Cause.Cause<{ readonly message: string }>,
cause: Cause.Cause<ProviderAdapterProcessError>,
): ReadonlyArray<string> {
const errors: Array<string> = [];
for (const error of Cause.prettyErrors(cause)) {
@@ -297,27 +284,17 @@ function isClaudeInterruptedMessage(message: string): boolean {
);
}
function isClaudeInterruptedCause(cause: Cause.Cause<{ readonly message: string }>): boolean {
function isClaudeInterruptedCause(cause: Cause.Cause<ProviderAdapterProcessError>): boolean {
return (
Cause.hasInterruptsOnly(cause) ||
normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage)
normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage) ||
cause.reasons.some(
(reason) =>
Cause.isFailReason(reason) && isClaudeInterruptedMessage(toMessage(reason.error.cause, "")),
)
);
}
function messageFromClaudeStreamCause(
cause: Cause.Cause<{ readonly message: string }>,
fallback: string,
): string {
return normalizeClaudeStreamMessages(cause)[0] ?? fallback;
}
function interruptionMessageFromClaudeCause(
cause: Cause.Cause<{ readonly message: string }>,
): string {
const message = messageFromClaudeStreamCause(cause, "Claude runtime interrupted.");
return isClaudeInterruptedMessage(message) ? "Claude runtime interrupted." : message;
}
function resultErrorsText(result: SDKResultMessage): string {
return "errors" in result && Array.isArray(result.errors)
? result.errors.join(" ").toLowerCase()
@@ -1004,7 +981,7 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: toMessage(cause, "Failed to read attachment file."),
detail: "Failed to read attachment file.",
cause,
}),
),
@@ -1242,7 +1219,7 @@ function toRequestError(threadId: ThreadId, method: string, cause: unknown): Pro
return new ProviderAdapterRequestError({
provider: PROVIDER,
method,
detail: toMessage(cause, `${method} failed`),
detail: `${method} failed`,
cause,
});
}
@@ -2910,18 +2887,27 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const runSdkStream = (
context: ClaudeSessionContext,
): Effect.Effect<void, ProviderAdapterProcessError> =>
Stream.fromAsyncIterable(context.query, (cause) =>
toProcessError(cause, "Claude runtime stream failed.", context.session.threadId),
Stream.fromAsyncIterable(
context.query,
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: context.session.threadId,
detail: "Claude runtime stream failed.",
cause,
}),
).pipe(
Stream.takeWhile(() => !context.stopped),
Stream.runForEach((message) =>
handleSdkMessage(context, message).pipe(
Effect.mapError((cause) =>
toProcessError(
cause,
"Failed to process Claude runtime event.",
context.session.threadId,
),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: context.session.threadId,
detail: "Failed to process Claude runtime event.",
cause,
}),
),
),
),
@@ -2938,15 +2924,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
if (Exit.isFailure(exit)) {
if (isClaudeInterruptedCause(exit.cause)) {
if (context.turnState) {
yield* completeTurn(
context,
"interrupted",
interruptionMessageFromClaudeCause(exit.cause),
);
yield* completeTurn(context, "interrupted", "Claude runtime interrupted.");
}
} else {
const message = messageFromClaudeStreamCause(exit.cause, "Claude runtime stream failed.");
yield* emitRuntimeError(context, message, Cause.pretty(exit.cause));
const failures = exit.cause.reasons.flatMap((reason) =>
Cause.isFailReason(reason) ? [reason.error] : [],
);
const message = failures[0]?.detail ?? "Claude runtime stream failed.";
yield* emitRuntimeError(context, message, {
failureCount: failures.length,
failureTags: failures.map((failure) => failure._tag),
});
yield* completeTurn(context, "failed", message);
}
} else if (context.turnState) {
@@ -3004,12 +2992,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: context.session.threadId,
detail: toMessage(cause, "Failed to close Claude runtime query."),
detail: "Failed to close Claude runtime query.",
cause,
}),
}).pipe(
Effect.catch((cause) =>
emitRuntimeError(context, "Failed to close Claude runtime query.", cause),
Effect.catch((error) =>
emitRuntimeError(context, "Failed to close Claude runtime query.", {
errorTag: error._tag,
provider: error.provider,
threadId: error.threadId,
detail: error.detail,
}),
),
);
@@ -3522,7 +3515,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId,
detail: toMessage(cause, "Failed to start Claude runtime session."),
detail: "Failed to start Claude runtime session.",
cause,
}),
});
@@ -31,7 +31,6 @@ import {
buildSelectOptionDescriptor,
buildServerProvider,
DEFAULT_TIMEOUT_MS,
detailFromResult,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
@@ -661,6 +660,9 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
yield* Effect.logWarning("Claude Agent CLI health check failed.", {
errorTag: error._tag,
});
return buildServerProvider({
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
@@ -673,7 +675,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
: "Failed to execute Claude Agent CLI health check.",
},
});
}
@@ -698,7 +700,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
exitCode: version.code,
stdoutLength: version.stdout.length,
stderrLength: version.stderr.length,
});
return buildServerProvider({
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
@@ -709,9 +715,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
message: "Claude Agent CLI is installed but failed to run.",
},
});
}
@@ -1,8 +1,9 @@
import * as NodeAssert from "node:assert/strict";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { describe, it } from "vite-plus/test";
import { describe } from "vite-plus/test";
import { ThreadId } from "@t3tools/contracts";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexRpc from "effect-codex-app-server/rpc";
@@ -19,6 +20,23 @@ import {
} from "./CodexSessionRuntime.ts";
const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError);
describe("CodexSessionRuntimeIdentifierGenerationError", () => {
it("retains identifier purpose and the random source failure", () => {
const cause = new Error("random source unavailable");
const error = new CodexErrors.CodexAppServerIdentifierGenerationError({
purpose: "provider-event",
cause,
});
NodeAssert.equal(error.purpose, "provider-event");
NodeAssert.strictEqual(error.cause, cause);
NodeAssert.equal(
error.message,
"Failed to generate Codex App Server identifier for provider-event.",
);
});
});
function makeThreadOpenResponse(
threadId: string,
): CodexRpc.ClientRequestResponsesByMethod["thread/start"] {
@@ -43,6 +61,32 @@ function makeThreadOpenResponse(
}
describe("buildTurnStartParams", () => {
it("keeps invalid turn values only in the schema cause", () => {
const secret = "codex-turn-input-secret-sentinel";
const error = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "full-access",
attachments: [
{
type: "image",
url: { secret } as unknown as string,
},
],
}).pipe(Effect.flip),
);
const { cause, ...directDiagnostics } = error;
NodeAssert.equal(error.operation, "decode-request-payload");
NodeAssert.equal(error.method, "turn/start");
NodeAssert.ok((error.issueCount ?? 0) > 0);
NodeAssert.ok(error.issueKinds?.includes("Pointer"));
NodeAssert.ok((error.maximumPathDepth ?? 0) > 0);
NodeAssert.ok(Schema.isSchemaError(cause));
NodeAssert.doesNotMatch(error.message, new RegExp(secret));
NodeAssert.doesNotMatch(JSON.stringify(directDiagnostics), new RegExp(secret));
});
it("includes plan collaboration mode when requested", () => {
const params = Effect.runSync(
buildTurnStartParams({
@@ -223,29 +267,29 @@ describe("isRecoverableThreadResumeError", () => {
});
describe("openCodexThread", () => {
it("falls back to thread/start when resume fails recoverably", async () => {
const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
const started = makeThreadOpenResponse("fresh-thread");
const client = {
request: <M extends "thread/start" | "thread/resume">(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
) => {
calls.push({ method, payload });
if (method === "thread/resume") {
return Effect.fail(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "thread not found",
}),
);
}
return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
},
};
it.effect("falls back to thread/start when resume fails recoverably", () =>
Effect.gen(function* () {
const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
const started = makeThreadOpenResponse("fresh-thread");
const client = {
request: <M extends "thread/start" | "thread/resume">(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
) => {
calls.push({ method, payload });
if (method === "thread/resume") {
return Effect.fail(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "thread not found",
}),
);
}
return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
},
};
const opened = await Effect.runPromise(
openCodexThread({
const opened = yield* openCodexThread({
client,
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
@@ -253,51 +297,49 @@ describe("openCodexThread", () => {
requestedModel: "gpt-5.3-codex",
serviceTier: undefined,
resumeThreadId: "stale-thread",
}),
);
});
NodeAssert.equal(opened.thread.id, "fresh-thread");
NodeAssert.deepStrictEqual(
calls.map((call) => call.method),
["thread/resume", "thread/start"],
);
});
NodeAssert.equal(opened.thread.id, "fresh-thread");
NodeAssert.deepStrictEqual(
calls.map((call) => call.method),
["thread/resume", "thread/start"],
);
}),
);
it("propagates non-recoverable resume failures", async () => {
const client = {
request: <M extends "thread/start" | "thread/resume">(
method: M,
_payload: CodexRpc.ClientRequestParamsByMethod[M],
) => {
if (method === "thread/resume") {
return Effect.fail(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "timed out waiting for server",
}),
it.effect("propagates non-recoverable resume failures", () =>
Effect.gen(function* () {
const client = {
request: <M extends "thread/start" | "thread/resume">(
method: M,
_payload: CodexRpc.ClientRequestParamsByMethod[M],
) => {
if (method === "thread/resume") {
return Effect.fail(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "timed out waiting for server",
}),
);
}
return Effect.succeed(
makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
);
}
return Effect.succeed(
makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
);
},
};
},
};
await NodeAssert.rejects(
Effect.runPromise(
openCodexThread({
client,
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
cwd: "/tmp/project",
requestedModel: "gpt-5.3-codex",
serviceTier: undefined,
resumeThreadId: "stale-thread",
}),
),
(error: unknown) =>
isCodexAppServerRequestError(error) &&
error.errorMessage === "timed out waiting for server",
);
});
const error = yield* openCodexThread({
client,
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
cwd: "/tmp/project",
requestedModel: "gpt-5.3-codex",
serviceTier: undefined,
resumeThreadId: "stale-thread",
}).pipe(Effect.flip);
NodeAssert.ok(isCodexAppServerRequestError(error));
NodeAssert.equal(error.errorMessage, "timed out waiting for server");
}),
);
});
@@ -26,10 +26,9 @@ import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as SchemaIssue from "effect/SchemaIssue";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as CodexClient from "effect-codex-app-server/client";
import * as CodexErrors from "effect-codex-app-server/errors";
@@ -89,7 +88,6 @@ const decodeCodexTurnStartParamsWithCollaborationMode = Schema.decodeUnknownEffe
export type CodexTurnStartParamsWithCollaborationMode =
typeof CodexTurnStartParamsWithCollaborationMode.Type;
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
export type CodexResumeCursor = typeof CodexResumeCursorSchema.Type;
type CodexServiceTier = NonNullable<EffectCodexSchema.V2ThreadStartParams["serviceTier"]>;
@@ -390,7 +388,13 @@ export function buildTurnStartParams(input: {
...(input.effort ? { effort: input.effort } : {}),
...(collaborationMode ? { collaborationMode } : {}),
}).pipe(
Effect.mapError((error) => toProtocolParseError("Invalid turn/start request payload", error)),
Effect.mapError((cause) =>
CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(
"decode-request-payload",
cause,
{ method: "turn/start" },
),
),
);
}
@@ -468,7 +472,7 @@ export const openCodexThread = (input: {
requestedRuntimeMode: input.runtimeMode,
resumeThreadId,
recoverable: true,
cause: error.message,
cause: error,
}).pipe(Effect.andThen(input.client.request("thread/start", startParams))),
),
);
@@ -658,16 +662,6 @@ function toCodexUserInputAnswers(
).pipe(Effect.map((entries) => Object.fromEntries(entries)));
}
function toProtocolParseError(
detail: string,
cause: Schema.SchemaError,
): CodexErrors.CodexAppServerProtocolParseError {
return new CodexErrors.CodexAppServerProtocolParseError({
detail: `${detail}: ${formatSchemaIssue(cause.issue)}`,
cause,
});
}
function currentProviderThreadId(session: ProviderSession): string | undefined {
return readResumeCursorThreadId(session.resumeCursor);
}
@@ -760,15 +754,16 @@ export const makeCodexSessionRuntime = (
);
const serverNotifications = yield* Queue.unbounded<CodexServerNotification>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new CodexErrors.CodexAppServerTransportError({
detail: "Failed to generate Codex runtime identifier.",
cause,
}),
),
);
const randomUUIDv4 = (purpose: CodexErrors.CodexAppServerIdentifierPurpose) =>
crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new CodexErrors.CodexAppServerIdentifierGenerationError({
purpose,
cause,
}),
),
);
const sessionCreatedAt = yield* nowIso;
const initialSession = {
@@ -788,7 +783,7 @@ export const makeCodexSessionRuntime = (
const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
Effect.gen(function* () {
const id = yield* randomUUIDv4;
const id = yield* randomUUIDv4("provider-event");
return yield* offerEvent({
id: EventId.make(id),
provider: PROVIDER,
@@ -956,7 +951,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4("command-approval-request"));
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
@@ -1012,7 +1007,9 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const requestId = ApprovalRequestId.make(
yield* randomUUIDv4("file-change-approval-request"),
);
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
@@ -1068,7 +1065,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4("user-input-request"));
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
@@ -1293,7 +1290,11 @@ export const makeCodexSessionRuntime = (
const rawResponse = yield* client.raw.request("turn/start", params);
const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(
Effect.mapError((error) =>
toProtocolParseError("Invalid turn/start response payload", error),
CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(
"decode-response-payload",
error,
{ method: "turn/start" },
),
),
);
const turnId = TurnId.make(response.turn.id);
@@ -10,7 +10,7 @@ import type {
} from "@t3tools/contracts";
import { ProviderDriverKind } from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import * as Cause from "effect/Cause";
import { causeErrorTag } from "@t3tools/shared/observability";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -1006,6 +1006,9 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
if (Result.isFailure(aboutProbe)) {
const error = aboutProbe.failure;
yield* Effect.logWarning("Cursor Agent CLI health check failed.", {
errorTag: error._tag,
});
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
@@ -1018,7 +1021,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
: `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
: "Failed to execute Cursor Agent CLI health check.",
},
});
}
@@ -1074,7 +1077,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
);
if (Exit.isFailure(discoveryExit)) {
yield* Effect.logWarning("Cursor ACP model discovery failed", {
cause: Cause.pretty(discoveryExit.cause),
errorTag: causeErrorTag(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
} else if (Option.isNone(discoveryExit.value)) {
@@ -1130,7 +1133,7 @@ export const enrichCursorSnapshot = (input: {
),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor version advisory enrichment failed", {
cause: Cause.pretty(cause),
errorTag: causeErrorTag(cause),
}).pipe(Effect.asVoid),
),
);
@@ -6,9 +6,13 @@ import * as NodePath from "node:path";
import { ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Logger from "effect/Logger";
import * as Schema from "effect/Schema";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
function parseLogLine(line: string) {
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
assert.notEqual(match, null);
@@ -29,6 +33,38 @@ function parseLogLine(line: string) {
}
describe("EventNdjsonLogger", () => {
it.effect("logs bounded diagnostics when an event cannot be serialized", () => {
const messages: Array<unknown> = [];
const logCapture = Logger.make<unknown, void>(({ message }) => {
if (Array.isArray(message)) {
messages.push(...message);
} else {
messages.push(message);
}
});
const secret = "secret-circular-event-value";
return Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
const circular: Record<string, unknown> = { secret };
circular.self = circular;
try {
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
assert.exists(logger);
if (!logger) return;
yield* logger.write(circular, ThreadId.make("thread-1"));
const serialized = encodeUnknownJson(messages);
assert.notInclude(serialized, secret);
assert.include(serialized, '"errorTag":"SchemaError"');
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}).pipe(Effect.provide(Logger.layer([logCapture], { mergeWithExisting: false })));
});
it.effect("writes effect-style lines to thread-scoped files", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
@@ -11,6 +11,7 @@ import * as NodePath from "node:path";
import type { ThreadId } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { errorTag } from "@t3tools/shared/observability";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Logger from "effect/Logger";
@@ -31,8 +32,8 @@ export type EventNdjsonStream = "native" | "canonical" | "orchestration";
export interface EventNdjsonLogger {
readonly filePath: string;
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
close: () => Effect.Effect<void>;
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void, never, never>;
close: () => Effect.Effect<void, never, never>;
}
export interface EventNdjsonLoggerOptions {
@@ -91,9 +92,9 @@ const toLogMessage = Effect.fn("toLogMessage")(function* (
): Effect.fn.Return<string | undefined> {
return yield* encodeUnknownJsonString(event).pipe(
Effect.catch((error) =>
logWarning("failed to serialize provider event log record", { error }).pipe(
Effect.as(undefined),
),
logWarning("failed to serialize provider event log record", {
errorTag: errorTag(error),
}).pipe(Effect.as(undefined)),
),
);
});
@@ -124,7 +125,7 @@ const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
error: sinkResult.error,
errorTag: errorTag(sinkResult.error),
});
return undefined;
}
@@ -149,7 +150,7 @@ const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
error: flushResult.error,
errorTag: errorTag(flushResult.error),
});
}
}),
@@ -187,7 +188,7 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
error: directoryReady.error,
errorTag: errorTag(directoryReady.error),
});
return undefined;
}
@@ -54,6 +54,7 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () =>
Effect.gen(function* () {
const secretStderr = "broken grok install: secret-token-value";
const snapshot = yield* Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -62,7 +63,7 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
const grokPath = path.join(dir, "grok");
yield* fs.writeFileString(
grokPath,
["#!/bin/sh", 'printf "%s\\n" "broken grok install" >&2', "exit 2", ""].join("\n"),
["#!/bin/sh", `printf "%s\\n" "${secretStderr}" >&2`, "exit 2", ""].join("\n"),
);
yield* fs.chmod(grokPath, 0o755);
@@ -75,7 +76,8 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
expect(snapshot.enabled).toBe(true);
expect(snapshot.installed).toBe(true);
expect(snapshot.status).toBe("error");
expect(snapshot.message).toContain("broken grok install");
expect(snapshot.message).toBe("Grok CLI is installed but failed to run.");
expect(snapshot.message).not.toContain(secretStderr);
}),
);
+16 -11
View File
@@ -6,7 +6,7 @@ import {
type ServerProviderModel,
} from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import * as Cause from "effect/Cause";
import { causeErrorTag } from "@t3tools/shared/observability";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -19,7 +19,6 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell";
import {
buildServerProvider,
detailFromResult,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
@@ -195,6 +194,9 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
if (Result.isFailure(versionResult)) {
const error = versionResult.failure;
yield* Effect.logWarning("Grok CLI health check failed.", {
errorTag: error._tag,
});
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
@@ -207,7 +209,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Grok CLI (`grok`) is not installed or not on PATH."
: `Failed to execute Grok CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
: "Failed to execute Grok CLI health check.",
},
});
}
@@ -231,7 +233,11 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
const versionOutput = versionResult.success.value;
const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
if (versionOutput.code !== 0) {
const detail = detailFromResult(versionOutput);
yield* Effect.logWarning("Grok CLI version probe exited with a non-zero status.", {
exitCode: versionOutput.code,
stdoutLength: versionOutput.stdout.length,
stderrLength: versionOutput.stderr.length,
});
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
@@ -242,9 +248,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
version,
status: "error",
auth: { status: "unknown" },
message: detail
? `Grok CLI is installed but failed to run. ${detail}`
: "Grok CLI is installed but failed to run.",
message: "Grok CLI is installed but failed to run.",
},
});
}
@@ -254,8 +258,9 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
Effect.exit,
);
if (Exit.isFailure(discoveryExit)) {
const detail = Cause.pretty(discoveryExit.cause);
yield* Effect.logWarning("Grok ACP model discovery failed", { cause: detail });
yield* Effect.logWarning("Grok ACP model discovery failed", {
errorTag: causeErrorTag(discoveryExit.cause),
});
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
@@ -266,7 +271,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
version,
status: "error",
auth: { status: "unknown" },
message: `Grok CLI is installed but ACP startup failed. ${detail}`,
message: "Grok CLI is installed but ACP startup failed. Check server logs for details.",
},
});
}
@@ -324,7 +329,7 @@ export const enrichGrokSnapshot = (input: {
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
Effect.catchCause((cause) =>
Effect.logWarning("Grok version advisory enrichment failed", {
cause: Cause.pretty(cause),
errorTag: causeErrorTag(cause),
}),
),
Effect.asVoid,
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff. Show more