Compare commits
109
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6693a8816 | ||
|
|
be56fa43b0 | ||
|
|
eb5eb0d9fa | ||
|
|
621616268a | ||
|
|
630df6b986 | ||
|
|
569b3e5959 | ||
|
|
d7ff7e7333 | ||
|
|
bd8e3ee008 | ||
|
|
c1d8a22f07 | ||
|
|
7b791895ad | ||
|
|
4c16c66368 | ||
|
|
4407a5a6b7 | ||
|
|
c7b375e9b0 | ||
|
|
abc253d97d | ||
|
|
ce11e6facd | ||
|
|
f1052dd8b1 | ||
|
|
e85144a58c | ||
|
|
defd9dfe20 | ||
|
|
8c03188c1c | ||
|
|
3e5f9f2cdd | ||
|
|
6888276f19 | ||
|
|
e06c33c38d | ||
|
|
5f860439e9 | ||
|
|
c9159b67b3 | ||
|
|
a1b727f62d | ||
|
|
fdc1e8b3a2 | ||
|
|
c8454ad88a | ||
|
|
336d176027 | ||
|
|
204984bf8c | ||
|
|
be4a38e578 | ||
|
|
f50a7cddc1 | ||
|
|
97487d9959 | ||
|
|
d2e38c5373 | ||
|
|
90bd5ee0c1 | ||
|
|
430ece4c0a | ||
|
|
4238a0e769 | ||
|
|
ff0f702c7c | ||
|
|
1cbe8a7a90 | ||
|
|
46fdc769d9 | ||
|
|
0cd0ed1a3d | ||
|
|
d53237cbd1 | ||
|
|
0e718855b8 | ||
|
|
731b1a67ac | ||
|
|
cdfecb36a6 | ||
|
|
f4ef356215 | ||
|
|
d60f5c6101 | ||
|
|
eacceb9e7b | ||
|
|
13a4789a5d | ||
|
|
b6e384fb27 | ||
|
|
d8bf307d22 | ||
|
|
d512deac84 | ||
|
|
32c7f90d9e | ||
|
|
2c16edd0cb | ||
|
|
708bc7091d | ||
|
|
7eb7b4f4a3 | ||
|
|
e01b1903de | ||
|
|
1dc36cef73 | ||
|
|
833c8ab7c6 | ||
|
|
5b1b35c773 | ||
|
|
ee3e2dae78 | ||
|
|
9c98cd60e8 | ||
|
|
48f88d5220 | ||
|
|
2910d9ff01 | ||
|
|
2b8e012924 | ||
|
|
49c23221d8 | ||
|
|
5ca7676661 | ||
|
|
c3e3e26844 | ||
|
|
1486a4a2b9 | ||
|
|
1e5f62801b | ||
|
|
ed6ba7439d | ||
|
|
f98448e872 | ||
|
|
bfe61741b8 | ||
|
|
4d3fcacd84 | ||
|
|
4d790f0064 | ||
|
|
3ecf3685ba | ||
|
|
716ae73c40 | ||
|
|
300d4d566a | ||
|
|
53a477c2e9 | ||
|
|
d84ebe8319 | ||
|
|
5a2c92e86d | ||
|
|
61aade9ea4 | ||
|
|
04f82ae1f3 | ||
|
|
ce0c20b840 | ||
|
|
fccecd8749 | ||
|
|
30a084c463 | ||
|
|
9d5ca2cb7c | ||
|
|
ac77fe452b | ||
|
|
4fbc4f9b20 | ||
|
|
779c237487 | ||
|
|
350e229f7a | ||
|
|
8112aff7c2 | ||
|
|
b9e22de6a3 | ||
|
|
f3b43a148b | ||
|
|
8331511b97 | ||
|
|
08650a7424 | ||
|
|
40d14647db | ||
|
|
cc69aef4dd | ||
|
|
71608142c2 | ||
|
|
bf1a6501c7 | ||
|
|
f7867addbe | ||
|
|
7a8bab5d9d | ||
|
|
06752526b3 | ||
|
|
d87ec967bf | ||
|
|
e55dd0067d | ||
|
|
8c3755aecc | ||
|
|
b4fe8faa1d | ||
|
|
515303edf2 | ||
|
|
20734d4a78 | ||
|
|
86db35ca61 |
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: [],
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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
|
||||
>();
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -393,7 +393,21 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
|
||||
yield* Ref.set(failDecrypt, true);
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
|
||||
@@ -53,8 +53,6 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-catalog-file",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreWriteOperation =
|
||||
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"read-legacy-registry",
|
||||
@@ -62,8 +60,12 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"encode-catalog",
|
||||
"persist-catalog",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreMigrationOperation =
|
||||
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-catalog",
|
||||
"decrypt-catalog",
|
||||
]);
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
@@ -78,17 +80,6 @@ export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorC
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopConnectionCatalogStoreWriteError =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
{
|
||||
@@ -142,18 +133,18 @@ export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedEr
|
||||
}
|
||||
}
|
||||
|
||||
const migrationError = (
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: string,
|
||||
cause: unknown,
|
||||
environmentId?: string,
|
||||
): DesktopConnectionCatalogStoreMigrationError =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation,
|
||||
catalogPath,
|
||||
...(environmentId === undefined ? {} : { environmentId }),
|
||||
cause,
|
||||
});
|
||||
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
|
||||
"DesktopConnectionCatalogStoreProtectionError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreProtectionOperation,
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
DesktopConnectionCatalogStore,
|
||||
@@ -164,13 +155,13 @@ export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
| DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError
|
||||
| DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
|
||||
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
@@ -236,20 +227,46 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-document", input.catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.catalogPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-catalog-file", input.catalogPath, cause)),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "replace-catalog-file",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
input.fileSystem.remove(tempPath, { force: true }).pipe(
|
||||
@@ -330,13 +347,17 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments
|
||||
.getSecret(record.environmentId)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
|
||||
),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-secret",
|
||||
catalogPath,
|
||||
environmentId: record.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(token)) {
|
||||
credentials.push({
|
||||
connectionId: id,
|
||||
@@ -362,13 +383,41 @@ export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const encryptedCatalog = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(catalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "encrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
@@ -380,21 +429,42 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry.pipe(
|
||||
Effect.mapError((cause) => migrationError("read-legacy-registry", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-registry",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
|
||||
Effect.mapError((cause) => migrationError("encode-catalog", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "encode-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* writeCatalog(encoded).pipe(
|
||||
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "persist-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Option.some(encoded);
|
||||
});
|
||||
@@ -405,16 +475,27 @@ export const make = Effect.gen(function* () {
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
Effect.flatMap((encryptedCatalog) =>
|
||||
safeStorage.decryptString(encryptedCatalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "decrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
|
||||
@@ -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.');
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -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",
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,26 +1,39 @@
|
||||
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 type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
|
||||
appFocusMock: vi.fn(),
|
||||
getAllWindowsMock: vi.fn(),
|
||||
}));
|
||||
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
|
||||
() => ({
|
||||
appFocusMock: vi.fn(),
|
||||
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
|
||||
getAllWindowsMock: vi.fn(),
|
||||
getFocusedWindowMock: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
focus: appFocusMock,
|
||||
},
|
||||
BrowserWindow: {
|
||||
BrowserWindow: Object.assign(browserWindowMock, {
|
||||
getAllWindows: getAllWindowsMock,
|
||||
},
|
||||
getFocusedWindow: getFocusedWindowMock,
|
||||
}),
|
||||
}));
|
||||
|
||||
import * as ElectronWindow from "./ElectronWindow.ts";
|
||||
|
||||
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
|
||||
const TestLayer = ElectronWindow.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
|
||||
return {
|
||||
id: input.id,
|
||||
isDestroyed: vi.fn(() => input.destroyed),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
}
|
||||
@@ -28,13 +41,78 @@ function makeBrowserWindow(input: { readonly destroyed: boolean }) {
|
||||
describe("ElectronWindow", () => {
|
||||
beforeEach(() => {
|
||||
appFocusMock.mockReset();
|
||||
browserWindowMock.mockReset();
|
||||
getAllWindowsMock.mockReset();
|
||||
getFocusedWindowMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("preserves schema-safe creation context and the Electron cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("native BrowserWindow construction failed");
|
||||
browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() {
|
||||
throw cause;
|
||||
});
|
||||
const options = {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
modal: false,
|
||||
frame: true,
|
||||
transparent: false,
|
||||
backgroundColor: "#101010",
|
||||
icon: {} as Electron.NativeImage,
|
||||
webPreferences: {
|
||||
preload: "/tmp/preload.js",
|
||||
partition: "persist:t3code-preview-test",
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webviewTag: true,
|
||||
spellcheck: true,
|
||||
},
|
||||
} satisfies Electron.BrowserWindowConstructorOptions;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
|
||||
const error = yield* electronWindow.create(options).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
|
||||
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
|
||||
assert.deepEqual(error.options, {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
modal: false,
|
||||
frame: true,
|
||||
transparent: false,
|
||||
backgroundColor: "#101010",
|
||||
webPreferences: {
|
||||
preload: "/tmp/preload.js",
|
||||
partition: "persist:t3code-preview-test",
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webviewTag: true,
|
||||
},
|
||||
});
|
||||
assert.isFalse("icon" in error.options);
|
||||
assert.isFalse("spellcheck" in error.options.webPreferences);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).');
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.deepEqual(browserWindowMock.mock.calls, [[options]]);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("skips windows destroyed before appearance sync runs", () =>
|
||||
Effect.gen(function* () {
|
||||
const liveWindow = makeBrowserWindow({ destroyed: false });
|
||||
const destroyedWindow = makeBrowserWindow({ destroyed: true });
|
||||
const liveWindow = makeBrowserWindow({ id: 1, destroyed: false });
|
||||
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true });
|
||||
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
|
||||
|
||||
const syncedWindows: Electron.BrowserWindow[] = [];
|
||||
@@ -46,6 +124,112 @@ describe("ElectronWindow", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(syncedWindows, [liveWindow]);
|
||||
}).pipe(Effect.provide(ElectronWindow.layer)),
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves window enumeration failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window enumeration failed");
|
||||
getAllWindowsMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.currentMainOrFirst);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "list-windows");
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.isNull(error.windowId);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves reveal failures with the target window", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window restore failed");
|
||||
const window = {
|
||||
id: 41,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => true),
|
||||
restore: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.reveal(window));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "reveal-window");
|
||||
assert.equal(error.windowId, 41);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message delivery failures with window and channel context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("renderer send failed");
|
||||
const window = {
|
||||
id: 42,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
webContents: {
|
||||
send: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
},
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
getAllWindowsMock.mockReturnValueOnce([window]);
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true }));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "send-window-message");
|
||||
assert.equal(error.windowId, 42);
|
||||
assert.equal(error.channel, "desktop:update");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves destroy failures with the target window", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window destroy failed");
|
||||
const window = {
|
||||
id: 43,
|
||||
destroy: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
getAllWindowsMock.mockReturnValueOnce([window]);
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.destroyAll);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "destroy-window");
|
||||
assert.equal(error.windowId, 43);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
});
|
||||
@@ -8,14 +8,69 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const ElectronWindowCreateOptions = Schema.Struct({
|
||||
title: Schema.NullOr(Schema.String),
|
||||
width: Schema.NullOr(Schema.Number),
|
||||
height: Schema.NullOr(Schema.Number),
|
||||
minWidth: Schema.NullOr(Schema.Number),
|
||||
minHeight: Schema.NullOr(Schema.Number),
|
||||
show: Schema.NullOr(Schema.Boolean),
|
||||
modal: Schema.NullOr(Schema.Boolean),
|
||||
frame: Schema.NullOr(Schema.Boolean),
|
||||
transparent: Schema.NullOr(Schema.Boolean),
|
||||
backgroundColor: Schema.NullOr(Schema.String),
|
||||
webPreferences: Schema.Struct({
|
||||
preload: Schema.NullOr(Schema.String),
|
||||
partition: Schema.NullOr(Schema.String),
|
||||
sandbox: Schema.NullOr(Schema.Boolean),
|
||||
contextIsolation: Schema.NullOr(Schema.Boolean),
|
||||
nodeIntegration: Schema.NullOr(Schema.Boolean),
|
||||
webviewTag: Schema.NullOr(Schema.Boolean),
|
||||
}),
|
||||
});
|
||||
|
||||
const ElectronWindowOperation = Schema.Literals([
|
||||
"list-windows",
|
||||
"get-focused-window",
|
||||
"inspect-window",
|
||||
"reveal-window",
|
||||
"send-window-message",
|
||||
"destroy-window",
|
||||
]);
|
||||
|
||||
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
|
||||
"ElectronWindowCreateError",
|
||||
{
|
||||
options: ElectronWindowCreateOptions,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to create Electron BrowserWindow.";
|
||||
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
|
||||
const dimensions =
|
||||
this.options.width === null || this.options.height === null
|
||||
? ""
|
||||
: ` (${this.options.width}x${this.options.height})`;
|
||||
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
|
||||
|
||||
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
|
||||
"ElectronWindowOperationError",
|
||||
{
|
||||
operation: ElectronWindowOperation,
|
||||
platform: Schema.String,
|
||||
windowId: Schema.NullOr(Schema.Number),
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
|
||||
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
|
||||
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,9 +98,38 @@ export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
Effect.map(Option.filter((value) => !value.isDestroyed())),
|
||||
);
|
||||
const listWindows = Effect.try({
|
||||
try: () => Electron.BrowserWindow.getAllWindows(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "list-windows",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
|
||||
Effect.try({
|
||||
try: () => window.isDestroyed(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "inspect-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const liveMain = Effect.gen(function* () {
|
||||
const main = yield* Ref.get(mainWindowRef);
|
||||
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return main;
|
||||
});
|
||||
|
||||
const currentMainOrFirst = Effect.gen(function* () {
|
||||
const main = yield* liveMain;
|
||||
@@ -53,27 +137,60 @@ export const make = Effect.gen(function* () {
|
||||
return main;
|
||||
}
|
||||
|
||||
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
);
|
||||
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
|
||||
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return first;
|
||||
});
|
||||
|
||||
const focusedMainOrFirst = Effect.sync(() =>
|
||||
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
),
|
||||
).pipe(
|
||||
Effect.flatMap((focused) =>
|
||||
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
|
||||
),
|
||||
);
|
||||
const focusedMainOrFirst = Effect.gen(function* () {
|
||||
const focused = yield* Effect.try({
|
||||
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "get-focused-window",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
|
||||
return focused;
|
||||
}
|
||||
return yield* currentMainOrFirst;
|
||||
});
|
||||
|
||||
return ElectronWindow.of({
|
||||
create: (options) =>
|
||||
Effect.try({
|
||||
create: (options) => {
|
||||
const webPreferences = options.webPreferences;
|
||||
const diagnosticOptions = {
|
||||
title: options.title ?? null,
|
||||
width: options.width ?? null,
|
||||
height: options.height ?? null,
|
||||
minWidth: options.minWidth ?? null,
|
||||
minHeight: options.minHeight ?? null,
|
||||
show: options.show ?? null,
|
||||
modal: options.modal ?? null,
|
||||
frame: options.frame ?? null,
|
||||
transparent: options.transparent ?? null,
|
||||
backgroundColor: options.backgroundColor ?? null,
|
||||
webPreferences: {
|
||||
preload: webPreferences?.preload ?? null,
|
||||
partition: webPreferences?.partition ?? null,
|
||||
sandbox: webPreferences?.sandbox ?? null,
|
||||
contextIsolation: webPreferences?.contextIsolation ?? null,
|
||||
nodeIntegration: webPreferences?.nodeIntegration ?? null,
|
||||
webviewTag: webPreferences?.webviewTag ?? null,
|
||||
},
|
||||
} satisfies typeof ElectronWindowCreateOptions.Type;
|
||||
|
||||
return Effect.try({
|
||||
try: () => new Electron.BrowserWindow(options),
|
||||
catch: (cause) => new ElectronWindowCreateError({ cause }),
|
||||
}),
|
||||
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
|
||||
});
|
||||
},
|
||||
main: liveMain,
|
||||
currentMainOrFirst,
|
||||
focusedMainOrFirst,
|
||||
@@ -89,45 +206,75 @@ export const make = Effect.gen(function* () {
|
||||
return Option.none();
|
||||
}),
|
||||
reveal: (window) =>
|
||||
Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "reveal-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
continue;
|
||||
}
|
||||
window.webContents.send(channel, ...args);
|
||||
yield* Effect.try({
|
||||
try: () => window.webContents.send(channel, ...args),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
destroyAll: Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
window.destroy();
|
||||
destroyAll: Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
yield* Effect.try({
|
||||
try: () => window.destroy(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "destroy-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) {
|
||||
const windows = Electron.BrowserWindow.getAllWindows();
|
||||
const windows = yield* listWindows;
|
||||
for (const window of windows) {
|
||||
if (window.isDestroyed()) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
continue;
|
||||
}
|
||||
yield* sync(window);
|
||||
|
||||
@@ -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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { fromPartition, sessions } = vi.hoisted(() => ({
|
||||
@@ -59,6 +61,64 @@ describe("BrowserSession", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves partition scope and the platform failure chain", () => {
|
||||
const nativeCause = new Error("native digest failed");
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "Crypto",
|
||||
method: "digest",
|
||||
cause: nativeCause,
|
||||
});
|
||||
const failingCryptoLayer = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => new Uint8Array(size),
|
||||
digest: () => Effect.fail(platformCause),
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-a");
|
||||
assert.strictEqual(error.cause, platformCause);
|
||||
assert.strictEqual(error.cause.reason.cause, nativeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to derive a desktop preview browser partition for scope environment-a.",
|
||||
);
|
||||
assert.notInclude(error.message, nativeCause.message);
|
||||
}).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
|
||||
});
|
||||
|
||||
it.effect("preserves session scope, partition, and the Electron failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("Electron session failed");
|
||||
fromPartition.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const partition = yield* browserSessions.getPartition("environment-b");
|
||||
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-b");
|
||||
assert.equal(error.partition, partition);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("clears storage and cache for every created session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
@@ -80,4 +140,52 @@ describe("BrowserSession", () => {
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("correlates clear failures while still attempting every session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
yield* browserSessions.getSession("scope-b");
|
||||
const firstPartition = yield* browserSessions.getPartition("scope-a");
|
||||
const secondPartition = yield* browserSessions.getPartition("scope-b");
|
||||
const firstSession = sessions.get(firstPartition);
|
||||
const secondSession = sessions.get(secondPartition);
|
||||
assert.isDefined(firstSession);
|
||||
assert.isDefined(secondSession);
|
||||
|
||||
const storageCause = new Error("storage clear failed");
|
||||
secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
|
||||
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
|
||||
assert.equal(storageError.partition, secondPartition);
|
||||
assert.strictEqual(storageError.cause, storageCause);
|
||||
assert.equal(
|
||||
storageError.message,
|
||||
`Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
|
||||
);
|
||||
assert.notInclude(storageError.message, storageCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
|
||||
}
|
||||
|
||||
const cacheCause = new Error("cache clear failed");
|
||||
firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
|
||||
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
|
||||
assert.equal(cacheError.partition, firstPartition);
|
||||
assert.strictEqual(cacheError.cause, cacheCause);
|
||||
assert.equal(
|
||||
cacheError.message,
|
||||
`Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
|
||||
);
|
||||
assert.notInclude(cacheError.message, cacheCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -5,31 +5,87 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
|
||||
"BrowserSessionError",
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
"BrowserSessionPartitionDerivationError",
|
||||
{
|
||||
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
|
||||
scope: Schema.String,
|
||||
cause: Schema.instanceOf(PlatformError.PlatformError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
|
||||
"BrowserSessionCreationError",
|
||||
{
|
||||
scope: Schema.String,
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop preview browser session operation failed: ${this.operation}`;
|
||||
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
|
||||
"BrowserSessionStorageClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
|
||||
"BrowserSessionCacheClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BrowserSessionGetSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
]);
|
||||
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
|
||||
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
|
||||
|
||||
export const BrowserSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
BrowserSessionStorageClearError,
|
||||
BrowserSessionCacheClearError,
|
||||
]);
|
||||
export type BrowserSessionError = typeof BrowserSessionError.Type;
|
||||
export const isBrowserSessionError = Schema.is(BrowserSessionError);
|
||||
|
||||
export class BrowserSession extends Context.Service<
|
||||
BrowserSession,
|
||||
{
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly getPartition: (
|
||||
scope?: string,
|
||||
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserSession") {}
|
||||
|
||||
@@ -38,11 +94,15 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
|
||||
const digest = yield* crypto
|
||||
.digest("SHA-256", new TextEncoder().encode(scope))
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
|
||||
);
|
||||
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BrowserSessionPartitionDerivationError({
|
||||
scope,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
|
||||
});
|
||||
|
||||
@@ -67,7 +127,12 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
next.set(partition, browserSession);
|
||||
return [browserSession, next] as const;
|
||||
},
|
||||
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCreationError({
|
||||
scope,
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -79,13 +144,17 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
browserSession.clearStorageData({
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
}),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionStorageClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
@@ -94,10 +163,14 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () => browserSession.clearCache(),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCacheClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
+762
-357
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({
|
||||
|
||||
@@ -271,10 +271,11 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces typed safe storage availability failures", () => {
|
||||
it.effect("adds saved-environment context to safe storage availability failures", () => {
|
||||
const cause = new Error("safe storage unavailable");
|
||||
return withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
|
||||
|
||||
@@ -285,8 +286,22 @@ describe("DesktopSavedEnvironments", () => {
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentSecretProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "check-encryption-availability");
|
||||
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
|
||||
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
|
||||
const availabilityError =
|
||||
error.cause as ElectronSafeStorage.ElectronSafeStorageAvailabilityError;
|
||||
assert.strictEqual(availabilityError.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment secret protection failed during check-encryption-availability for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
|
||||
);
|
||||
assert.notEqual(error.message, availabilityError.message);
|
||||
}),
|
||||
{ availabilityError: cause },
|
||||
);
|
||||
|
||||
@@ -77,7 +77,12 @@ const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-registry-file",
|
||||
]);
|
||||
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
|
||||
|
||||
const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-secret",
|
||||
"decrypt-secret",
|
||||
]);
|
||||
|
||||
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
|
||||
"DesktopSavedEnvironmentsWriteError",
|
||||
@@ -92,17 +97,6 @@ export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSavedEnvironmentsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSavedEnvironmentsWriteError =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
|
||||
"DesktopSavedEnvironmentsReadError",
|
||||
{
|
||||
@@ -141,6 +135,20 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedError
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretProtectionError>()(
|
||||
"DesktopSavedEnvironmentSecretProtectionError",
|
||||
{
|
||||
operation: DesktopSavedEnvironmentSecretProtectionOperation,
|
||||
environmentId: Schema.String,
|
||||
registryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopSavedEnvironmentsReadRegistryError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
@@ -152,11 +160,11 @@ export type DesktopSavedEnvironmentsMutationError =
|
||||
export type DesktopSavedEnvironmentsGetSecretError =
|
||||
| DesktopSavedEnvironmentsReadRegistryError
|
||||
| DesktopSavedEnvironmentSecretDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
| DesktopSavedEnvironmentSecretProtectionError;
|
||||
|
||||
export type DesktopSavedEnvironmentsSetSecretError =
|
||||
| DesktopSavedEnvironmentsMutationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
| DesktopSavedEnvironmentSecretProtectionError;
|
||||
|
||||
export class DesktopSavedEnvironments extends Context.Service<
|
||||
DesktopSavedEnvironments,
|
||||
@@ -276,19 +284,45 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
|
||||
const directory = input.path.dirname(input.registryPath);
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-registry", input.registryPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "encode-registry",
|
||||
path: input.registryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "replace-registry-file",
|
||||
path: input.registryPath,
|
||||
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.registryPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-registry-file", input.registryPath, cause)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -341,8 +375,13 @@ export const make = Effect.gen(function* () {
|
||||
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeRegistryDocument({
|
||||
@@ -396,7 +435,21 @@ export const make = Effect.gen(function* () {
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
);
|
||||
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (Option.isNone(encoded)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!encryptionAvailable) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
@@ -405,7 +458,19 @@ export const make = Effect.gen(function* () {
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
encoded.value,
|
||||
);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
return Option.some(
|
||||
yield* safeStorage.decryptString(secretBytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "decrypt-secret",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
|
||||
const { environmentId, secret } = input;
|
||||
@@ -415,11 +480,34 @@ export const make = Effect.gen(function* () {
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!encryptionAvailable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
|
||||
const encryptedBearerToken = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(secret).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "encrypt-secret",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
let found = false;
|
||||
const nextDocument: SavedEnvironmentRegistryDocument = {
|
||||
version: document.version,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -23,6 +23,7 @@ describe("sshEnvironment", () => {
|
||||
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
|
||||
requestId: "prompt-1",
|
||||
destination: "devbox",
|
||||
operation: "send-prompt-request",
|
||||
cause: new Error("renderer send failed"),
|
||||
});
|
||||
|
||||
|
||||
@@ -17,7 +17,13 @@ interface SentMessage {
|
||||
readonly args: readonly unknown[];
|
||||
}
|
||||
|
||||
function makeTestWindow() {
|
||||
function makeTestWindow(
|
||||
options: {
|
||||
readonly isDestroyedError?: unknown;
|
||||
readonly isMinimizedError?: unknown;
|
||||
readonly sendError?: unknown;
|
||||
} = {},
|
||||
) {
|
||||
const listeners = new Map<string, Set<() => void>>();
|
||||
const sentMessages: SentMessage[] = [];
|
||||
let destroyed = false;
|
||||
@@ -26,8 +32,18 @@ function makeTestWindow() {
|
||||
let focused = false;
|
||||
|
||||
const window = {
|
||||
isDestroyed: () => destroyed,
|
||||
isMinimized: () => minimized,
|
||||
isDestroyed: () => {
|
||||
if (options.isDestroyedError !== undefined) {
|
||||
throw options.isDestroyedError;
|
||||
}
|
||||
return destroyed;
|
||||
},
|
||||
isMinimized: () => {
|
||||
if (options.isMinimizedError !== undefined) {
|
||||
throw options.isMinimizedError;
|
||||
}
|
||||
return minimized;
|
||||
},
|
||||
restore: () => {
|
||||
restored = true;
|
||||
minimized = false;
|
||||
@@ -45,7 +61,11 @@ function makeTestWindow() {
|
||||
},
|
||||
webContents: {
|
||||
send: (channel: string, ...args: readonly unknown[]) => {
|
||||
sentMessages.push({ channel, args });
|
||||
const message = { channel, args };
|
||||
sentMessages.push(message);
|
||||
if (options.sendError !== undefined) {
|
||||
throw options.sendError;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -55,6 +75,7 @@ function makeTestWindow() {
|
||||
sentMessages,
|
||||
isRestored: () => restored,
|
||||
isFocused: () => focused,
|
||||
closedListenerCount: () => listeners.get("closed")?.size ?? 0,
|
||||
close: () => {
|
||||
destroyed = true;
|
||||
const closedListeners = [...(listeners.get("closed") ?? [])];
|
||||
@@ -107,6 +128,7 @@ describe("DesktopSshPasswordPrompts", () => {
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(testWindow.sentMessages.length, 1);
|
||||
const sent = testWindow.sentMessages[0];
|
||||
@@ -143,4 +165,85 @@ describe("DesktopSshPasswordPrompts", () => {
|
||||
assert.equal(error.destination, "devbox");
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("cleans up a prompt that fails during renderer delivery", () => {
|
||||
const cause = new Error("renderer unavailable");
|
||||
const testWindow = makeTestWindow({ sendError: cause });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const error = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
|
||||
assert.equal(error.operation, "send-prompt-request");
|
||||
assert.equal(error.destination, "devbox");
|
||||
const requestId = error.requestId;
|
||||
if (requestId === null) {
|
||||
assert.fail("renderer delivery failures must retain their request id");
|
||||
}
|
||||
assert.equal(testWindow.closedListenerCount(), 0);
|
||||
|
||||
const resolveError = yield* prompts
|
||||
.resolve({ requestId, password: "secret" })
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(resolveError, DesktopSshPasswordPrompts.DesktopSshPromptExpiredError);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("keeps a submitted password when a later presentation step fails", () => {
|
||||
const testWindow = makeTestWindow({
|
||||
isMinimizedError: new Error("failed to read minimized state"),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const requestFiber = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
const sent = testWindow.sentMessages[0];
|
||||
assert.ok(sent);
|
||||
const request = sent.args[0] as { readonly requestId: string };
|
||||
yield* prompts.resolve({ requestId: request.requestId, password: "secret" });
|
||||
const password = yield* Fiber.join(requestFiber);
|
||||
|
||||
assert.equal(password, "secret");
|
||||
assert.equal(testWindow.isFocused(), false);
|
||||
assert.equal(testWindow.closedListenerCount(), 0);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("classifies a failed initial window availability check", () => {
|
||||
const testWindow = makeTestWindow({ isDestroyedError: new Error("window unavailable") });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const error = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
|
||||
assert.equal(error.operation, "check-window-before-request");
|
||||
assert.equal(error.requestId, null);
|
||||
assert.deepEqual(testWindow.sentMessages, []);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,26 @@ const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
|
||||
type DesktopSshPasswordPromptResolutionInput =
|
||||
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
|
||||
|
||||
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
|
||||
const DesktopSshPromptWindowAvailabilityStage = Schema.Literals([
|
||||
"before-request",
|
||||
"before-presentation",
|
||||
"after-send",
|
||||
"after-restore",
|
||||
]);
|
||||
|
||||
const DesktopSshPromptPresentationOperation = Schema.Literals([
|
||||
"check-window-before-request",
|
||||
"check-window-before-presentation",
|
||||
"register-window-close-listener",
|
||||
"send-prompt-request",
|
||||
"check-window-after-send",
|
||||
"check-window-minimized",
|
||||
"restore-window",
|
||||
"check-window-after-restore",
|
||||
"focus-window",
|
||||
"remove-window-close-listener",
|
||||
]);
|
||||
type DesktopSshPromptPresentationOperation = typeof DesktopSshPromptPresentationOperation.Type;
|
||||
|
||||
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
|
||||
"DesktopSshPromptRequestIdGenerationError",
|
||||
@@ -38,20 +57,22 @@ export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorCl
|
||||
"DesktopSshPromptWindowUnavailableError",
|
||||
{
|
||||
destination: Schema.String,
|
||||
requestId: Schema.NullOr(Schema.String),
|
||||
stage: DesktopSshPromptWindowAvailabilityStage,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return WINDOW_UNAVAILABLE_MESSAGE;
|
||||
const request = this.requestId === null ? "before a request id was assigned" : this.requestId;
|
||||
return `T3 Code window is unavailable during ${this.stage} for SSH authentication to ${this.destination} (request: ${request}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
|
||||
|
||||
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
|
||||
"DesktopSshPromptPresentationError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
requestId: Schema.NullOr(Schema.String),
|
||||
destination: Schema.String,
|
||||
operation: DesktopSshPromptPresentationOperation,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
@@ -263,9 +284,29 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
"desktop.sshPasswordPrompts.request",
|
||||
)(function* (input) {
|
||||
const window = yield* electronWindow.main;
|
||||
if (Option.isNone(window) || window.value.isDestroyed()) {
|
||||
if (Option.isNone(window)) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId: null,
|
||||
stage: "before-request",
|
||||
});
|
||||
}
|
||||
|
||||
const unavailableBeforeRequest = yield* Effect.try({
|
||||
try: () => window.value.isDestroyed(),
|
||||
catch: (cause) =>
|
||||
new DesktopSshPromptPresentationError({
|
||||
requestId: null,
|
||||
destination: input.destination,
|
||||
operation: "check-window-before-request",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (unavailableBeforeRequest) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId: null,
|
||||
stage: "before-request",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -319,11 +360,25 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
),
|
||||
);
|
||||
};
|
||||
const cleanup = Effect.sync(() => {
|
||||
const runPresentationOperation = <A>(
|
||||
operation: DesktopSshPromptPresentationOperation,
|
||||
evaluate: () => A,
|
||||
) =>
|
||||
Effect.try({
|
||||
try: evaluate,
|
||||
catch: (cause) =>
|
||||
new DesktopSshPromptPresentationError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
operation,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const cleanup = runPresentationOperation("remove-window-close-listener", () => {
|
||||
if (!window.value.isDestroyed()) {
|
||||
window.value.removeListener("closed", cancelOnWindowClosed);
|
||||
}
|
||||
}).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
|
||||
}).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid);
|
||||
const waitForPassword = Deferred.await(deferred).pipe(
|
||||
Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
|
||||
Effect.flatMap(
|
||||
@@ -339,40 +394,73 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
}),
|
||||
),
|
||||
);
|
||||
const preferSubmittedPassword = (error: DesktopSshPasswordPromptRequestError) =>
|
||||
Deferred.poll(deferred).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: (completion) => completion,
|
||||
onNone: () =>
|
||||
Ref.get(pendingRef).pipe(
|
||||
Effect.flatMap((entries) =>
|
||||
entries.has(requestId) ? Effect.fail(error) : Deferred.await(deferred),
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.try({
|
||||
try: () => {
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
return yield* Effect.gen(function* () {
|
||||
const unavailableBeforePresentation = yield* runPresentationOperation(
|
||||
"check-window-before-presentation",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableBeforePresentation) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "before-presentation",
|
||||
});
|
||||
}
|
||||
yield* runPresentationOperation("register-window-close-listener", () =>
|
||||
window.value.once("closed", cancelOnWindowClosed),
|
||||
);
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runPresentationOperation("send-prompt-request", () =>
|
||||
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest),
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
const unavailableAfterSend = yield* runPresentationOperation(
|
||||
"check-window-after-send",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableAfterSend) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "after-send",
|
||||
});
|
||||
}
|
||||
window.value.once("closed", cancelOnWindowClosed);
|
||||
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
const minimized = yield* runPresentationOperation("check-window-minimized", () =>
|
||||
window.value.isMinimized(),
|
||||
);
|
||||
if (minimized) {
|
||||
yield* runPresentationOperation("restore-window", () => window.value.restore());
|
||||
}
|
||||
const unavailableAfterRestore = yield* runPresentationOperation(
|
||||
"check-window-after-restore",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableAfterRestore) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "after-restore",
|
||||
});
|
||||
}
|
||||
if (window.value.isMinimized()) {
|
||||
window.value.restore();
|
||||
}
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
});
|
||||
}
|
||||
window.value.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
isDesktopSshPromptWindowUnavailableError(cause)
|
||||
? cause
|
||||
: new DesktopSshPromptPresentationError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
|
||||
yield* runPresentationOperation("focus-window", () => window.value.focus());
|
||||
return yield* waitForPassword;
|
||||
}).pipe(Effect.catch(preferSubmittedPassword));
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
return DesktopSshPasswordPrompts.of({
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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.",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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}.`;
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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({
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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"),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -173,6 +173,8 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
|
||||
}
|
||||
throw new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
});
|
||||
}
|
||||
@@ -480,6 +482,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
? error
|
||||
: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail:
|
||||
error instanceof Error
|
||||
? `Failed to simulate gh checkout: ${error.message}`
|
||||
@@ -496,6 +500,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected repository lookup: ${repository}`,
|
||||
}),
|
||||
);
|
||||
@@ -516,6 +522,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected gh command: ${args.join(" ")}`,
|
||||
}),
|
||||
);
|
||||
@@ -595,6 +603,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "createRepository",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
),
|
||||
@@ -1333,6 +1343,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
@@ -2471,6 +2483,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
@@ -2500,6 +2514,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
}),
|
||||
},
|
||||
@@ -3377,13 +3393,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",
|
||||
|
||||
@@ -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* () {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -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* () {
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
);
|
||||
@@ -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) =>
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import type { SqlError } from "effect/unstable/sql/SqlError";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -13,7 +14,7 @@ type RuntimeSqliteLayerConfig = {
|
||||
};
|
||||
|
||||
type Loader = {
|
||||
layer: (config: RuntimeSqliteLayerConfig) => Layer.Layer<SqlClient.SqlClient>;
|
||||
layer: (config: RuntimeSqliteLayerConfig) => Layer.Layer<SqlClient.SqlClient, SqlError>;
|
||||
};
|
||||
const defaultSqliteClientLoaders = {
|
||||
bun: () => import("@effect/sql-sqlite-bun/SqliteClient"),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as SqliteClient from "./NodeSqliteClient.ts";
|
||||
@@ -27,4 +28,25 @@ layer("NodeSqliteClient", (it) => {
|
||||
assert.equal(values[1]?.[1], "beta");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a typed failure when an unprepared statement cannot be prepared", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const error = yield* Effect.flip(sql.unsafe("SELECT FROM").unprepared);
|
||||
|
||||
assert.equal(error._tag, "SqlError");
|
||||
assert.equal(error.reason.operation, "prepare");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("returns a typed failure when the database cannot be opened", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
Layer.build(SqliteClient.layer({ filename: "\0" })).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "SqlError");
|
||||
assert.equal(error.reason.operation, "open");
|
||||
}),
|
||||
);
|
||||
@@ -13,6 +13,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -45,6 +46,27 @@ export interface SqliteMemoryClientConfig extends Omit<
|
||||
"filename" | "readonly"
|
||||
> {}
|
||||
|
||||
export class UnsupportedNodeSqliteVersionError extends Schema.TaggedErrorClass<UnsupportedNodeSqliteVersionError>()(
|
||||
"UnsupportedNodeSqliteVersionError",
|
||||
{
|
||||
nodeVersion: Schema.String,
|
||||
requirement: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class UnsupportedNodeSqliteOperationError extends Schema.TaggedErrorClass<UnsupportedNodeSqliteOperationError>()(
|
||||
"UnsupportedNodeSqliteOperationError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Node SQLite does not support executeStream.";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the current Node.js version includes the `node:sqlite` APIs
|
||||
* used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
|
||||
@@ -60,8 +82,10 @@ const checkNodeSqliteCompat = () => {
|
||||
|
||||
if (!supported) {
|
||||
return Effect.die(
|
||||
`Node.js ${process.versions.node} is missing required node:sqlite APIs ` +
|
||||
`(StatementSync.columns). Upgrade to Node.js >=22.16, >=23.11, or >=24.`,
|
||||
new UnsupportedNodeSqliteVersionError({
|
||||
nodeVersion: process.versions.node,
|
||||
requirement: "Node.js >=22.16, >=23.11, or >=24",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -70,7 +94,7 @@ const checkNodeSqliteCompat = () => {
|
||||
const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
options: SqliteClientConfig,
|
||||
openDatabase: () => NodeSqlite.DatabaseSync,
|
||||
): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
|
||||
): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
|
||||
yield* checkNodeSqliteCompat();
|
||||
|
||||
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
|
||||
@@ -80,10 +104,28 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
|
||||
const makeConnection = Effect.gen(function* () {
|
||||
const scope = yield* Effect.scope;
|
||||
const db = openDatabase();
|
||||
const db = yield* Effect.try({
|
||||
try: openDatabase,
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to open database",
|
||||
operation: "open",
|
||||
}),
|
||||
}),
|
||||
});
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Effect.sync(() => db.close()),
|
||||
Effect.try({
|
||||
try: () => db.close(),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to close database",
|
||||
operation: "close",
|
||||
}),
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
|
||||
const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
|
||||
@@ -119,8 +161,8 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
raw: boolean,
|
||||
) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
|
||||
try {
|
||||
statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
}
|
||||
@@ -166,11 +208,20 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
}),
|
||||
}),
|
||||
(statement) =>
|
||||
Effect.sync(() => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(false);
|
||||
}
|
||||
}),
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(false);
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to reset statement result mode",
|
||||
operation: "resetResultMode",
|
||||
}),
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
|
||||
return identity<Connection>({
|
||||
@@ -184,11 +235,20 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
return runValues(sql, params);
|
||||
},
|
||||
executeUnprepared(sql, params, rowTransform) {
|
||||
const effect = runStatement(db.prepare(sql), params ?? [], false);
|
||||
const effect = Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
}),
|
||||
}),
|
||||
}).pipe(Effect.flatMap((statement) => runStatement(statement, params ?? [], false)));
|
||||
return rowTransform ? Effect.map(effect, rowTransform) : effect;
|
||||
},
|
||||
executeStream(_sql, _params) {
|
||||
return Stream.die("executeStream not implemented");
|
||||
return Stream.die(new UnsupportedNodeSqliteOperationError());
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -220,7 +280,7 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
|
||||
const make = (
|
||||
options: SqliteClientConfig,
|
||||
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
|
||||
): Effect.Effect<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
|
||||
makeWithDatabase(
|
||||
options,
|
||||
() =>
|
||||
@@ -232,7 +292,7 @@ const make = (
|
||||
|
||||
const makeMemory = (
|
||||
config: SqliteMemoryClientConfig = {},
|
||||
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
|
||||
): Effect.Effect<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
|
||||
makeWithDatabase(
|
||||
{
|
||||
...config,
|
||||
@@ -249,13 +309,15 @@ const makeMemory = (
|
||||
|
||||
export const layerConfig = (
|
||||
config: Config.Wrap<SqliteClientConfig>,
|
||||
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
|
||||
): Layer.Layer<Client.SqlClient, Config.ConfigError | SqlError> =>
|
||||
Layer.effect(Client.SqlClient, Config.unwrap(config).pipe(Effect.flatMap(make))).pipe(
|
||||
Layer.provide(Reactivity.layer),
|
||||
);
|
||||
|
||||
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
|
||||
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
|
||||
Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));
|
||||
|
||||
export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
|
||||
export const layerMemory = (
|
||||
config: SqliteMemoryClientConfig = {},
|
||||
): Layer.Layer<Client.SqlClient, SqlError> =>
|
||||
Layer.effect(Client.SqlClient, makeMemory(config)).pipe(Layer.provide(Reactivity.layer));
|
||||
@@ -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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -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/);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -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));
|
||||
|
||||
Loaded 100 of 326 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user