Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex b444300af0 refactor(web): structure desktop network access errors
Co-authored-by: codex <[email protected]>
2026-06-20 03:09:36 -07:00
432 changed files with 5978 additions and 27288 deletions

No files matched your search

+11 -13
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as NetService from "@t3tools/shared/Net";
import * as Crypto from "effect/Crypto";
@@ -33,24 +33,22 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
class DesktopBackendPortUnavailableError extends Data.TaggedError(
"DesktopBackendPortUnavailableError",
{
startPort: Schema.Int,
maxPort: Schema.Int,
hosts: Schema.Array(Schema.String),
},
) {
override get message(): string {
)<{
readonly startPort: number;
readonly maxPort: number;
readonly hosts: readonly string[];
}> {
override get message() {
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
}
}
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
"DesktopDevelopmentBackendPortRequiredError",
{},
) {
override get message(): string {
)<{}> {
override get message() {
return "T3CODE_PORT is required in desktop development.";
}
}
@@ -1,30 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import {
DesktopBackendPortUnavailableError,
DesktopDevelopmentBackendPortRequiredError,
} from "./DesktopApp.ts";
describe("DesktopApp errors", () => {
it("preserves unavailable backend port context", () => {
const error = new DesktopBackendPortUnavailableError({
startPort: 3_773,
maxPort: 65_535,
hosts: ["127.0.0.1", "0.0.0.0", "::"],
});
assert.equal(error.startPort, 3_773);
assert.equal(error.maxPort, 65_535);
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
assert.equal(
error.message,
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
);
});
it("reports the required development port", () => {
const error = new DesktopDevelopmentBackendPortRequiredError();
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
});
});
@@ -4,7 +4,6 @@ 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";
@@ -106,7 +105,6 @@ 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>;
} = {},
@@ -123,11 +121,7 @@ const withIdentity = <A, E, R>(
Layer.provideMerge(
FileSystem.layerNoop({
exists: (path) =>
input.legacyPathProbeError
? Effect.fail(input.legacyPathProbeError)
: Effect.succeed(
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
),
Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
readFileString: () =>
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
}),
@@ -153,33 +147,6 @@ 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: [],
+5 -23
View File
@@ -18,22 +18,10 @@ 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, DesktopUserDataPathResolutionError>;
readonly resolveUserDataPath: Effect.Effect<string>;
readonly configure: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
@@ -45,7 +33,7 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none();
};
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -95,15 +83,9 @@ export const make = Effect.gen(function* () {
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
const legacyPathExists = yield* fileSystem
.exists(legacyPath)
.pipe(Effect.orElseSucceed(() => false));
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
@@ -1,57 +0,0 @@
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");
}),
);
});
+8 -37
View File
@@ -3,7 +3,6 @@ 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";
@@ -13,26 +12,11 @@ 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>, DesktopAssetProbeError>;
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/app/DesktopAssets") {}
@@ -40,20 +24,14 @@ const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(func
fileName: string,
): Effect.fn.Return<
Option.Option<string>,
DesktopAssetProbeError,
never,
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.mapError(
(cause) => new DesktopAssetProbeError({ fileName, candidatePath: candidate, cause }),
),
);
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
if (exists) {
return Option.some(candidate);
}
@@ -65,23 +43,16 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
ext: keyof DesktopIconPaths,
): Effect.fn.Return<
Option.Option<string>,
DesktopAssetProbeError,
never,
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.mapError(
(cause) =>
new DesktopAssetProbeError({
fileName: "icon.png",
candidatePath: developmentDockIconPath,
cause,
}),
),
);
const developmentDockIconExists = yield* fileSystem
.exists(developmentDockIconPath)
.pipe(Effect.orElseSucceed(() => false));
if (developmentDockIconExists) {
return Option.some(developmentDockIconPath);
}
@@ -90,7 +61,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
return yield* resolveResourcePath(`icon.${ext}`);
});
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const context = yield* Effect.context<
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
>();
@@ -1,122 +0,0 @@
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 Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
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.merge(Path.layer, DesktopConfig.layerTest({}))));
const withOutputLog = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
messages: Array<ReadonlyArray<unknown>>,
) => {
const logger = Logger.make(({ message }) => {
messages.push(Array.isArray(message) ? message : [message]);
});
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
);
return effect.pipe(Effect.provide(outputLogLayer));
};
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
?.error;
describe("DesktopBackendOutputLog", () => {
it.effect("logs setup failures with the log path and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
description: "private setup diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.fail(cause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private setup diagnostic");
}),
fileSystemLayer,
messages,
);
});
it.effect("logs record write failures with the operation and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const missingCause = PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "stat",
pathOrDescriptor: LOG_FILE_PATH,
});
const writeCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFile",
pathOrDescriptor: LOG_FILE_PATH,
description: "private write diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.void,
stat: () => Effect.fail(missingCause),
readDirectory: () => Effect.succeed([]),
writeFile: () => Effect.fail(writeCause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
assert.equal(error.operation, "write-record");
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, writeCause);
assert.equal(
error.message,
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private write diagnostic");
}),
fileSystemLayer,
messages,
);
});
});
+46 -151
View File
@@ -19,75 +19,8 @@ export const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
interface RotatingLogFileWriter {
readonly filePath: string;
readonly writeBytes: (
chunk: Uint8Array,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
readonly writeText: (
chunk: string,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
"DesktopLogFileWriterRecoveryError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
recoveryCause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
"DesktopBackendOutputLogSetupError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
"DesktopBackendOutputLogWriteError",
{
operation: Schema.Literals(["encode-record", "write-record"]),
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
}
}
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
"DesktopBackendConsoleWriteError",
{
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to mirror desktop backend output to ${this.streamName}.`;
}
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
}
export class DesktopBackendOutputLog extends Context.Service<
@@ -104,6 +37,18 @@ export class DesktopBackendOutputLog extends Context.Service<
}
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
@@ -140,13 +85,10 @@ const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").t
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, PlatformError.PlatformError> =>
): Effect.Effect<number, never> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
}),
Effect.orElseSucceed(() => 0),
);
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
@@ -184,52 +126,41 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
const recoverCurrentSize = (
cause: PlatformError.PlatformError,
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.matchEffect({
onFailure: (recoveryCause) =>
Effect.fail(
new DesktopLogFileWriterRecoveryError({
logFilePath: input.filePath,
cause,
recoveryCause,
}),
),
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
}),
);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory);
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true });
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source);
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem.exists(input.filePath);
const currentExists = yield* fileSystem
.exists(input.filePath)
.pipe(Effect.orElseSucceed(() => false));
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
});
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);
const writeBytes = (
chunk: Uint8Array,
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
if (chunk.byteLength === 0) return Effect.void;
return mutex.withPermits(1)(
@@ -247,9 +178,11 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
yield* rotate;
}
}).pipe(
Effect.catchTags({
PlatformError: recoverCurrentSize,
}),
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
),
);
};
@@ -257,7 +190,6 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
yield* pruneOverflowBackups;
return {
filePath: input.filePath,
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
@@ -267,17 +199,10 @@ const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.try({
try: () => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
},
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
}).pipe(
Effect.catchTags({
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
Effect.sync(() => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
}).pipe(Effect.ignore);
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
function* (
@@ -297,47 +222,17 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
annotations: input.annotations,
spans: {},
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
}).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "encode-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
yield* logFile.writeText(`${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "write-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
}).pipe(
Effect.catchTags({
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
});
yield* logFile.writeText(`${encoded}\n`);
}).pipe(Effect.ignore({ log: true }));
},
);
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
const writer = yield* makeRotatingLogFileWriter({
filePath: logFilePath,
}).pipe(
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
Effect.map(Option.some),
Effect.catchTags({
DesktopBackendOutputLogSetupError: (error) =>
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
}),
);
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
const service = Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
+12 -67
View File
@@ -1,8 +1,7 @@
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 { beforeEach, vi } from "vite-plus/test";
import { vi } from "vite-plus/test";
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
createClerkBridgeMock: vi.fn(),
@@ -25,23 +24,7 @@ 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$")}`;
@@ -57,9 +40,19 @@ 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(makeDesktopClerkLayer()));
yield* Effect.scoped(
Layer.build(
DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
),
),
);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
@@ -76,54 +69,6 @@ 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" },
+3 -47
View File
@@ -4,7 +4,6 @@ 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";
@@ -15,32 +14,6 @@ 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,
{
@@ -82,28 +55,11 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
});
}
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
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),
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
(bridge) => Effect.sync(() => bridge.cleanup()),
);
return DesktopClerk.of({
@@ -393,21 +393,7 @@ 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,
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);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
@@ -53,6 +53,8 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-catalog-file",
]);
type DesktopConnectionCatalogStoreWriteOperation =
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"read-legacy-registry",
@@ -60,12 +62,8 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"encode-catalog",
"persist-catalog",
]);
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-catalog",
"decrypt-catalog",
]);
type DesktopConnectionCatalogStoreMigrationOperation =
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
"DesktopConnectionCatalogStoreWriteError",
@@ -80,6 +78,17 @@ 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",
{
@@ -133,18 +142,18 @@ export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedEr
}
}
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}.`;
}
}
const migrationError = (
operation: DesktopConnectionCatalogStoreMigrationOperation,
catalogPath: string,
cause: unknown,
environmentId?: string,
): DesktopConnectionCatalogStoreMigrationError =>
new DesktopConnectionCatalogStoreMigrationError({
operation,
catalogPath,
...(environmentId === undefined ? {} : { environmentId }),
cause,
});
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
@@ -155,13 +164,13 @@ export class DesktopConnectionCatalogStore extends Context.Service<
| DesktopConnectionCatalogStoreDocumentDecodeError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| DesktopConnectionCatalogStoreProtectionError
| ElectronSafeStorage.ElectronSafeStorageError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
>;
readonly clear: Effect.Effect<void>;
}
@@ -227,46 +236,20 @@ 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) =>
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,
}),
),
Effect.mapError((cause) => writeError("encode-document", input.catalogPath, 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) =>
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,
}),
),
);
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)),
);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
@@ -347,17 +330,13 @@ const migrateSavedEnvironmentRecords = Effect.fn(
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-secret",
catalogPath,
environmentId: record.environmentId,
cause,
}),
),
);
const token = yield* savedEnvironments
.getSecret(record.environmentId)
.pipe(
Effect.mapError((cause) =>
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
),
);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
@@ -383,41 +362,13 @@ 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).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "encrypt-catalog",
catalogPath,
cause,
}),
),
),
);
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-temporary-file-name",
path: catalogPath,
cause,
}),
),
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
@@ -429,42 +380,21 @@ export const make = Effect.gen(function* () {
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* encryptionAvailable)) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-registry",
catalogPath,
cause,
}),
),
Effect.mapError((cause) => migrationError("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) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "encode-catalog",
catalogPath,
cause,
}),
),
Effect.mapError((cause) => migrationError("encode-catalog", catalogPath, cause)),
);
yield* writeCatalog(encoded).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "persist-catalog",
catalogPath,
cause,
}),
),
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
);
return Option.some(encoded);
});
@@ -475,27 +405,16 @@ export const make = Effect.gen(function* () {
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* encryptionAvailable)) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
Effect.flatMap((encryptedCatalog) =>
safeStorage.decryptString(encryptedCatalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "decrypt-catalog",
catalogPath,
cause,
}),
),
),
),
Effect.flatMap(safeStorage.decryptString),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* encryptionAvailable)) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
@@ -1,37 +0,0 @@
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.');
});
});
+6 -17
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import type * as Electron from "electron";
@@ -15,18 +15,6 @@ 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
@@ -154,10 +142,11 @@ export const make = DesktopLifecycle.of({
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) => {
const error = new DesktopLifecycleRelaunchError({ reason, cause });
return logLifecycleError(error.message, { error });
}),
Effect.catchCause((cause) =>
logLifecycleError("desktop relaunch failed", {
cause: Cause.pretty(cause),
}),
),
Effect.forkDetach,
Effect.asVoid,
);
@@ -3,8 +3,6 @@ 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";
@@ -23,10 +21,6 @@ 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({
@@ -172,62 +166,6 @@ 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,24 +8,12 @@ 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,
{
@@ -62,34 +50,25 @@ const DESKTOP_BACKEND_ENV_NAMES = [
const backendChildEnvPatch = (): Record<string, string | undefined> =>
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
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 { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
"desktop-backend-configuration",
);
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
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()),
),
}),
);
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);
if (Option.isNone(raw)) {
yield* logBackendConfigurationWarning(
"failed to read persisted backend observability settings",
);
return emptyBackendObservabilitySettings;
}
@@ -3,15 +3,12 @@ import {
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
@@ -31,7 +28,6 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
@@ -59,9 +55,9 @@ const configWithObservability: DesktopBackendBootstrapValue = {
};
function makeProcess(options?: {
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
readonly stdout?: Stream.Stream<Uint8Array>;
readonly stderr?: Stream.Stream<Uint8Array>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
@@ -149,23 +145,6 @@ function makeManagerLayer(input: {
}
describe("DesktopBackendManager", () => {
it("preserves the complete restart cause and schedule context", () => {
const cause = Cause.combine(
Cause.fail(new Error("start failed")),
Cause.die(new Error("restart defect")),
);
const error = new DesktopBackendManager.DesktopBackendRestartError({
reason: "backend exited with code 1",
delayMs: 500,
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.reason, "backend exited with code 1");
assert.equal(error.delayMs, 500);
assert.equal(error.message, "Desktop backend restart failed after a scheduled 500ms delay.");
});
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
@@ -239,243 +218,6 @@ describe("DesktopBackendManager", () => {
}),
);
it.effect("preserves the readiness timeout cause and process context", () =>
Effect.gen(function* () {
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
const layer = Layer.merge(
TestClock.layer(),
httpClientLayer((request) =>
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
),
);
yield* Effect.gen(function* () {
const readiness = yield* DesktopBackendManager.waitForHttpReady({
executablePath: baseConfig.executablePath,
entryPath: baseConfig.entryPath,
cwd: baseConfig.cwd,
httpBaseUrl: baseConfig.httpBaseUrl,
timeout: Duration.millis(50),
}).pipe(Effect.flip, Effect.forkChild);
const request = yield* Deferred.await(requested);
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(readiness);
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
assert.equal(error.timeoutMs, 50);
assert.isTrue(Cause.isTimeoutError(error.cause));
assert.equal(
error.message,
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
);
}).pipe(Effect.provide(layer));
}),
);
it.effect("reports bootstrap encoding failures with stable process context", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
bootstrap: {
...baseConfig.bootstrap,
port: 0,
},
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessBootstrapEncodeError") {
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.isDefined(error.cause);
assert.equal(
error.message,
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves spawn failures without deriving their message from the cause", () =>
Effect.gen(function* () {
const spawnCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcessSpawner",
method: "spawn",
pathOrDescriptor: baseConfig.executablePath,
description: "low-level detail that must not become the public message",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessSpawnError") {
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, spawnCause);
assert.equal(
error.message,
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
);
assert.notInclude(error.message, spawnCause.message);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves exit-status failures without copying their detail into the message", () =>
Effect.gen(function* () {
const exitCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "exitCode",
description: "exit-status-secret-sentinel",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Effect.fail(exitCause),
}),
),
),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessExitStatusError") {
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
}
assert.equal(error.pid, 123);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, exitCause);
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
assert.notInclude(error.message, "exit-status-secret-sentinel");
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("reports output stream failures with process and stream context", () =>
Effect.gen(function* () {
const outputCause = PlatformError.systemError({
_tag: "BadResource",
module: "ChildProcess",
method: "stdout",
description: "output-stream-secret-sentinel",
});
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fail(outputCause),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputReadError") {
return assert.fail(`Expected output read error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.strictEqual(error.cause, outputCause);
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
assert.notInclude(error.message, "output-stream-secret-sentinel");
}),
);
it.effect("reports output handler failures separately from stream read failures", () =>
Effect.gen(function* () {
const chunk = new TextEncoder().encode("backend output");
const outputCause = new Error("output-handler-secret-sentinel");
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.make(chunk),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
onOutput: () => Effect.fail(outputCause),
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputHandlingError") {
return assert.fail(`Expected output handling error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.equal(error.chunkByteLength, chunk.byteLength);
assert.strictEqual(error.cause, outputCause);
assert.equal(
error.message,
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
);
assert.notInclude(error.message, "output-handler-secret-sentinel");
}),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.gen(function* () {
const requestUrls: Array<string> = [];
+65 -218
View File
@@ -9,6 +9,7 @@ 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 Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
@@ -42,145 +43,68 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export interface BackendProcessContext {
export interface DesktopBackendStartConfig {
readonly executablePath: string;
readonly entryPath: string;
readonly cwd: string;
readonly httpBaseUrl: URL;
}
export interface DesktopBackendStartConfig extends BackendProcessContext {
readonly env: Record<string, string | undefined>;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly httpBaseUrl: URL;
readonly captureOutput: boolean;
}
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
const backendProcessContextSchema = {
executablePath: Schema.String,
entryPath: Schema.String,
cwd: Schema.String,
httpBaseUrl: Schema.URL,
};
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
"BackendReadinessTimeoutError",
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
...backendProcessContextSchema,
readinessUrl: Schema.URL,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
url: Schema.URL,
},
) {
override get message(): string {
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
...backendProcessContextSchema,
detail: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
}
}
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
...backendProcessContextSchema,
detail: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
return `Failed to spawn desktop backend process: ${this.detail}`;
}
}
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
"BackendProcessOutputReadError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
}
}
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
"BackendProcessOutputHandlingError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
chunkByteLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
}
}
export type BackendProcessOutputError =
| BackendProcessOutputReadError
| BackendProcessOutputHandlingError;
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
"BackendProcessExitStatusError",
{
...backendProcessContextSchema,
pid: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
}
}
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
"DesktopBackendRestartError",
{
reason: Schema.String,
delayMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
}
}
export const BackendProcessError = Schema.Union([
BackendProcessBootstrapEncodeError,
BackendProcessSpawnError,
BackendProcessExitStatusError,
]);
export type BackendProcessError = typeof BackendProcessError.Type;
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly readinessTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>;
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
@@ -259,10 +183,11 @@ const closeRun = (
).pipe(Effect.ignore);
};
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
options: BackendProcessContext & { readonly timeout: Duration.Duration },
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.filterStatusOk,
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
@@ -271,64 +196,43 @@ export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpRea
yield* client.get(readinessUrl).pipe(
Effect.asVoid,
Effect.timeout(options.timeout),
Effect.mapError(
(cause) =>
new BackendReadinessTimeoutError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
readinessUrl,
timeoutMs: Duration.toMillis(options.timeout),
cause,
}),
),
Effect.timeout(timeout),
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
);
});
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
): BackendProcessExit {
if (Result.isSuccess(result)) {
return {
code: Option.some(result.success),
reason: `code=${result.success}`,
result,
};
}
return {
code: Option.none(),
reason: result.failure.message,
result,
};
}
function drainBackendOutput(
context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>,
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
Stream.mapError(
(cause) =>
new BackendProcessOutputReadError({
...context,
streamName,
cause,
}),
),
Stream.runForEach((chunk) =>
onOutput(streamName, chunk).pipe(
Effect.mapError(
(cause) =>
new BackendProcessOutputHandlingError({
...context,
streamName,
chunkByteLength: chunk.byteLength,
cause,
}),
),
),
),
Effect.catchTags({
BackendProcessOutputReadError: onOutputFailure,
BackendProcessOutputHandlingError: onOutputFailure,
}),
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
Effect.ignore,
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -336,10 +240,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.mapError(
(cause) =>
new BackendProcessBootstrapEncodeError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
detail: cause.message,
cause,
}),
),
@@ -372,10 +273,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
detail: cause.message,
cause,
}),
),
@@ -383,60 +281,19 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
const outputContext = {
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
}
yield* waitForHttpReady({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
yield* waitForHttpReady(
options.httpBaseUrl,
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catchTags({
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.forkScoped,
);
const exitCode = yield* handle.exitCode.pipe(
Effect.mapError(
(cause) =>
new BackendProcessExitStatusError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
cause,
}),
),
);
return {
code: Option.some(exitCode),
reason: `code=${exitCode}`,
} satisfies BackendProcessExit;
return describeProcessExit(yield* Effect.result(handle.exitCode));
});
export const make = Effect.gen(function* () {
@@ -494,7 +351,7 @@ export const make = Effect.gen(function* () {
const config = yield* configuration.resolve.pipe(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error,
cause: error.message,
}),
),
Effect.option,
@@ -632,26 +489,22 @@ export const make = Effect.gen(function* () {
yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", {
cause: error,
message: error.message,
}),
),
);
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error,
error: error.message,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
Scope.provide(runScope),
Effect.matchEffect({
onFailure: (error) =>
logBackendManagerError(error.message, { error }).pipe(
Effect.andThen(finalizeRun(error.message)),
),
onFailure: (error) => finalizeRun(error.message),
onSuccess: (exit) => finalizeRun(exit.reason),
}),
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
@@ -706,17 +559,11 @@ export const make = Effect.gen(function* () {
}),
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopBackendRestartError({
reason,
delayMs: Duration.toMillis(delay),
cause,
});
return logBackendManagerError(error.message, { error });
}),
Effect.catchCause((cause) =>
logBackendManagerError("desktop backend restart fiber failed", {
cause: Cause.pretty(cause),
}),
),
),
parentScope,
);
@@ -1,65 +0,0 @@
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,10 +1,8 @@
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;
@@ -20,18 +18,6 @@ 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,
{
@@ -39,14 +25,9 @@ export class DesktopNetworkInterfaces extends Context.Service<
}
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
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 make = (): DesktopNetworkInterfaces["Service"] =>
DesktopNetworkInterfaces.of({
read: Effect.sync(() => NodeOS.networkInterfaces()),
});
});
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
export const layer = Layer.succeed(DesktopNetworkInterfaces, make());
@@ -91,7 +91,6 @@ 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);
@@ -100,7 +99,7 @@ function makeLayer(input: {
});
return DesktopServerExposure.layer.pipe(
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
@@ -123,7 +122,6 @@ 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;
@@ -137,7 +135,6 @@ const withHarness = <A, E, R>(
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
}),
),
);
@@ -240,67 +237,6 @@ 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,12 +2,11 @@ import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/shared/advertisedEndpoint";
import {
DesktopServerExposureModeSchema,
type AdvertisedEndpoint,
type AdvertisedEndpointProvider,
type DesktopServerExposureMode,
type DesktopServerExposureState,
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
DesktopServerExposureState,
} from "@t3tools/contracts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as Context from "effect/Context";
@@ -214,45 +213,23 @@ export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErr
}
}
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
"DesktopServerExposureModePersistenceError",
export class DesktopServerExposurePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposurePersistenceError>()(
"DesktopServerExposurePersistenceError",
{
mode: DesktopServerExposureModeSchema,
operation: Schema.Literals(["server-exposure-mode", "tailscale-serve"]),
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop server exposure mode ${this.mode}.`;
return `Failed to persist desktop ${this.operation} settings.`;
}
}
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 DesktopServerExposureSetModeError =
| DesktopServerExposureNoNetworkAddressError
| DesktopServerExposurePersistenceError;
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 type DesktopServerExposureError = DesktopServerExposureSetModeError;
export interface DesktopServerExposureBackendConfig {
readonly port: number;
@@ -281,7 +258,7 @@ export class DesktopServerExposure extends Context.Service<
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
@@ -472,8 +449,8 @@ export const make = Effect.gen(function* () {
const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
Effect.mapError(
(cause) =>
new DesktopServerExposureModePersistenceError({
mode,
new DesktopServerExposurePersistenceError({
operation: "server-exposure-mode",
cause,
}),
),
@@ -500,9 +477,8 @@ export const make = Effect.gen(function* () {
.pipe(
Effect.mapError(
(cause) =>
new DesktopTailscaleServePersistenceError({
enabled: input.enabled,
port: input.port ?? null,
new DesktopServerExposurePersistenceError({
operation: "tailscale-serve",
cause,
}),
),
@@ -100,44 +100,6 @@ 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();
+10 -60
View File
@@ -1,7 +1,6 @@
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";
@@ -14,36 +13,12 @@ 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, ElectronAppMetadataReadError>;
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
readonly whenReady: Effect.Effect<void>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
@@ -88,40 +63,15 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
).pipe(Effect.asVoid);
export const make = ElectronApp.of({
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,
};
}),
metadata: Effect.sync(() => ({
appVersion: Electron.app.getVersion(),
appPath: Electron.app.getAppPath(),
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
})),
name: Effect.sync(() => Electron.app.name),
whenReady: Effect.gen(function* () {
const isPackaged = Electron.app.isPackaged;
yield* Effect.tryPromise({
try: () => Electron.app.whenReady(),
catch: (cause) => new ElectronAppWhenReadyError({ isPackaged, cause }),
});
}),
whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
quit: Effect.sync(() => {
Electron.app.quit();
}),
@@ -1,5 +1,4 @@
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";
@@ -91,116 +90,4 @@ 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)),
);
});
+14 -129
View File
@@ -2,80 +2,11 @@ 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>;
@@ -91,24 +22,17 @@ export class ElectronDialog extends Context.Service<
{
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
) => Effect.Effect<Electron.MessageBoxReturnValue>;
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"],
@@ -118,18 +42,10 @@ export const make = ElectronDialog.of({
defaultPath,
}),
});
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,
}),
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
onSome: (owner) =>
Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
});
if (result.canceled) {
@@ -151,48 +67,17 @@ export const make = ElectronDialog.of({
noLink: true,
message: normalizedMessage,
};
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,
}),
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
});
return result.response === CONFIRM_BUTTON_INDEX;
}),
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,
}),
}),
showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
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),
Effect.sync(() => {
Electron.dialog.showErrorBox(title, content);
}),
});
export const layer = Layer.succeed(ElectronDialog, make);
+4 -94
View File
@@ -1,8 +1,5 @@
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";
@@ -27,10 +24,6 @@ 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();
@@ -49,7 +42,7 @@ describe("ElectronMenu", () => {
assert.isTrue(Option.isNone(selectedItemId));
assert.equal(buildFromTemplateMock.mock.calls.length, 0);
}).pipe(Effect.provide(TestLayer)),
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("resolves with the clicked leaf item id", () =>
@@ -76,7 +69,7 @@ describe("ElectronMenu", () => {
});
assert.equal(Option.getOrNull(selectedItemId), "copy");
}).pipe(Effect.provide(TestLayer)),
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("resolves with none when the menu closes without a click", () =>
@@ -100,7 +93,7 @@ describe("ElectronMenu", () => {
enabled: true,
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
});
}).pipe(Effect.provide(TestLayer)),
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("defers popupTemplate side effects until the returned Effect runs", () =>
@@ -121,89 +114,6 @@ describe("ElectronMenu", () => {
assert.equal(buildFromTemplateMock.mock.calls.length, 1);
assert.equal(popupMock.mock.calls.length, 1);
}).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)),
}).pipe(Effect.provide(ElectronMenu.layer)),
);
});
+24 -85
View File
@@ -4,7 +4,6 @@ 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";
@@ -24,28 +23,6 @@ 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,
{
@@ -165,36 +142,16 @@ export const make = Effect.gen(function* () {
return ElectronMenu.of({
setApplicationMenu: (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),
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
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),
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
@@ -212,39 +169,21 @@ export const make = Effect.gen(function* () {
resume(Effect.succeed(selectedItemId));
};
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,
}),
),
);
}
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);
}),
});
});
@@ -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";
@@ -99,60 +98,6 @@ 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",
+4 -21
View File
@@ -31,19 +31,7 @@ export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<E
},
) {
override get message(): string {
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}".`;
return `Failed to register ${this.scheme}: protocol.`;
}
}
@@ -145,14 +133,9 @@ export const make = Effect.gen(function* () {
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
}).pipe(Effect.andThen(Ref.set(registered, true))),
() =>
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),
Effect.sync(() => {
Electron.protocol.unhandle(input.scheme);
}).pipe(Effect.andThen(Ref.set(registered, false))),
);
},
);
@@ -8,7 +8,6 @@ const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
themeState: {
shouldUseDarkColors: true,
themeSource: "system",
setSourceError: null as unknown,
},
}));
@@ -18,9 +17,6 @@ vi.mock("electron", () => ({
return themeState.shouldUseDarkColors;
},
set themeSource(value: string) {
if (themeState.setSourceError !== null) {
throw themeState.setSourceError;
}
themeState.themeSource = value;
},
on: onMock,
@@ -36,7 +32,6 @@ describe("ElectronTheme", () => {
removeListenerMock.mockClear();
themeState.shouldUseDarkColors = true;
themeState.themeSource = "system";
themeState.setSourceError = null;
});
it.effect("scopes native theme update listeners", () =>
@@ -54,21 +49,4 @@ 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)),
);
});
+5 -22
View File
@@ -1,31 +1,16 @@
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";
import 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, ElectronThemeSetSourceError>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronTheme") {}
@@ -33,11 +18,9 @@ export class ElectronTheme extends Context.Service<
export const make = ElectronTheme.of({
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
setSource: (theme) =>
Effect.try({
try: () => {
Electron.nativeTheme.themeSource = theme;
},
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
Effect.suspend(() => {
Electron.nativeTheme.themeSource = theme;
return Effect.void;
}),
onUpdated: (listener) =>
Effect.acquireRelease(
@@ -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";
@@ -64,65 +65,16 @@ describe("ElectronUpdater", () => {
const cause = new Error("network unavailable");
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "beta";
const error = yield* updater.checkForUpdates.pipe(Effect.flip);
const exit = yield* Effect.exit(updater.checkForUpdates);
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]]);
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.");
}
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
});
+21 -37
View File
@@ -10,41 +10,40 @@ type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
const electronUpdaterErrorFields = {
cause: Schema.Defect(),
};
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
"ElectronUpdaterCheckForUpdatesError",
{
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
return "Electron updater failed to check for updates.";
}
}
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
"ElectronUpdaterDownloadUpdateError",
{
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
return "Electron updater failed to download the update.";
}
}
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
"ElectronUpdaterQuitAndInstallError",
{
channel: Schema.NullOr(Schema.String),
isSilent: Schema.Boolean,
isForceRunAfter: Schema.Boolean,
cause: Schema.Defect(),
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
return "Electron updater failed to quit and install the update.";
}
}
@@ -117,33 +116,18 @@ export const make = ElectronUpdater.of({
autoUpdater.disableDifferentialDownload = value;
return Effect.void;
}),
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);
}),
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),
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) =>
new ElectronUpdaterQuitAndInstallError({
channel,
isSilent,
isForceRunAfter,
cause,
}),
});
Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
}),
on: (eventName, listener) => {
const eventTarget = autoUpdater as unknown as {
+10 -194
View File
@@ -1,39 +1,26 @@
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, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
() => ({
appFocusMock: vi.fn(),
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
getAllWindowsMock: vi.fn(),
getFocusedWindowMock: vi.fn(),
}),
);
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
appFocusMock: vi.fn(),
getAllWindowsMock: vi.fn(),
}));
vi.mock("electron", () => ({
app: {
focus: appFocusMock,
},
BrowserWindow: Object.assign(browserWindowMock, {
BrowserWindow: {
getAllWindows: getAllWindowsMock,
getFocusedWindow: getFocusedWindowMock,
}),
},
}));
import * as ElectronWindow from "./ElectronWindow.ts";
const TestLayer = ElectronWindow.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
return {
id: input.id,
isDestroyed: vi.fn(() => input.destroyed),
} as unknown as Electron.BrowserWindow;
}
@@ -41,78 +28,13 @@ function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boo
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({ id: 1, destroyed: false });
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true });
const liveWindow = makeBrowserWindow({ destroyed: false });
const destroyedWindow = makeBrowserWindow({ destroyed: true });
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
const syncedWindows: Electron.BrowserWindow[] = [];
@@ -124,112 +46,6 @@ describe("ElectronWindow", () => {
);
assert.deepEqual(syncedWindows, [liveWindow]);
}).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)),
}).pipe(Effect.provide(ElectronWindow.layer)),
);
});
+44 -191
View File
@@ -8,69 +8,14 @@ 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 {
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}.`;
return "Failed to create Electron BrowserWindow.";
}
}
@@ -98,38 +43,9 @@ export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
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 liveMain = Ref.get(mainWindowRef).pipe(
Effect.map(Option.filter((value) => !value.isDestroyed())),
);
const currentMainOrFirst = Effect.gen(function* () {
const main = yield* liveMain;
@@ -137,60 +53,27 @@ export const make = Effect.gen(function* () {
return main;
}
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
return Option.none<Electron.BrowserWindow>();
}
return first;
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
);
});
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;
});
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,
),
);
return ElectronWindow.of({
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({
create: (options) =>
Effect.try({
try: () => new Electron.BrowserWindow(options),
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
});
},
catch: (cause) => new ElectronWindowCreateError({ cause }),
}),
main: liveMain,
currentMainOrFirst,
focusedMainOrFirst,
@@ -206,75 +89,45 @@ export const make = Effect.gen(function* () {
return Option.none();
}),
reveal: (window) =>
Effect.try({
try: () => {
if (window.isDestroyed()) {
return;
}
Effect.sync(() => {
if (window.isDestroyed()) {
return;
}
if (window.isMinimized()) {
window.restore();
}
if (window.isMinimized()) {
window.restore();
}
if (!window.isVisible()) {
window.show();
}
if (!window.isVisible()) {
window.show();
}
if (platform === "darwin") {
Electron.app.focus({ steal: true });
}
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),
window.focus();
}),
sendAll: (channel, ...args) =>
Effect.gen(function* () {
for (const window of yield* listWindows) {
if (yield* isWindowDestroyed(window)) {
Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
if (window.isDestroyed()) {
continue;
}
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);
window.webContents.send(channel, ...args);
}
}),
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);
destroyAll: Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
window.destroy();
}
}),
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) {
const windows = yield* listWindows;
const windows = Electron.BrowserWindow.getAllWindows();
for (const window of windows) {
if (yield* isWindowDestroyed(window)) {
if (window.isDestroyed()) {
continue;
}
yield* sync(window);
-79
View File
@@ -1,79 +0,0 @@
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 -78
View File
@@ -24,39 +24,6 @@ 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>;
@@ -72,10 +39,10 @@ export class DesktopIpc extends Context.Service<
{
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
) => Effect.Effect<void, never, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
) => Effect.Effect<void, never, R | Scope.Scope>;
}
>()("@t3tools/desktop/ipc/DesktopIpc") {}
@@ -90,27 +57,18 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease(
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);
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),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
}).pipe(Effect.orDie),
() => Effect.sync(() => ipcMain.removeHandler(channel)),
);
}),
@@ -123,30 +81,18 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
const runSync = Effect.runSyncWith(context);
yield* Effect.acquireRelease(
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);
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),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
}).pipe(Effect.orDie),
() => Effect.sync(() => ipcMain.removeAllListeners(channel)),
);
}),
});
+18 -11
View File
@@ -19,30 +19,37 @@ import {
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as NodeURL from "node:url";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(channel, ...args);
}
}
};
export const installPreviewEventForwarding = Effect.fn(
"desktop.ipc.preview.installEventForwarding",
)(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const manager = yield* PreviewManager.PreviewManager;
yield* manager.subscribeStateChanges((tabId, state) =>
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
);
yield* manager.subscribeRecordingFrames((frame) =>
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
);
yield* manager.subscribePointerEvents((event) =>
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
);
yield* manager.subscribeStateChanges((tabId, state) => {
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
});
yield* manager.subscribeRecordingFrames((frame) => {
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
});
yield* manager.subscribePointerEvents((event) => {
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
});
});
export const createTab = DesktopIpc.makeIpcMethod({
@@ -1,9 +1,7 @@
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(() => ({
@@ -61,64 +59,6 @@ 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;
@@ -140,52 +80,4 @@ 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)),
);
});
+18 -91
View File
@@ -5,87 +5,31 @@ 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 BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
"BrowserSessionPartitionDerivationError",
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
"BrowserSessionError",
{
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,
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
return `Desktop preview browser session operation failed: ${this.operation}`;
}
}
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, BrowserSessionPartitionDerivationError>;
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
readonly isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
}
>()("@t3tools/desktop/preview/BrowserSession") {}
@@ -94,15 +38,11 @@ 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 BrowserSessionPartitionDerivationError({
scope,
cause,
}),
),
);
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(scope))
.pipe(
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
);
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
});
@@ -127,12 +67,7 @@ export const make = Effect.gen(function* BrowserSessionMake() {
next.set(partition, browserSession);
return [browserSession, next] as const;
},
catch: (cause) =>
new BrowserSessionCreationError({
scope,
partition,
cause,
}),
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
});
});
});
@@ -144,17 +79,13 @@ export const make = Effect.gen(function* BrowserSessionMake() {
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.entries()].map(([partition, browserSession]) =>
[...sessions.values()].map((browserSession) =>
Effect.tryPromise({
try: () =>
browserSession.clearStorageData({
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
}),
catch: (cause) =>
new BrowserSessionStorageClearError({
partition,
cause,
}),
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
}),
),
{ concurrency: "unbounded", discard: true },
@@ -163,14 +94,10 @@ export const make = Effect.gen(function* BrowserSessionMake() {
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.entries()].map(([partition, browserSession]) =>
[...sessions.values()].map((browserSession) =>
Effect.tryPromise({
try: () => browserSession.clearCache(),
catch: (cause) =>
new BrowserSessionCacheClearError({
partition,
cause,
}),
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
}),
),
{ concurrency: "unbounded", discard: true },
+9 -276
View File
@@ -5,22 +5,19 @@ import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
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, it, vi } from "vite-plus/test";
import { beforeEach, describe, expect, vi } from "vite-plus/test";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts";
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
createFromPath: vi.fn(() => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
@@ -82,7 +79,6 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
const withManager = <A>(
use: (
@@ -132,72 +128,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("isolates failed state listeners and continues delivery", () => {
const loggedErrors: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
for (const value of Array.isArray(message) ? message : [message]) {
if (typeof value === "object" && value !== null && "cause" in value) {
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
}
}
});
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
operation: "send-window-message",
platform: "darwin",
windowId: 42,
channel: "preview:state-change",
cause: new Error("renderer unavailable"),
});
const delivered = vi.fn();
return withManager((manager) =>
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
yield* manager.subscribeStateChanges((tabId, state) =>
Effect.sync(() => {
delivered(tabId, state);
}),
);
const state = yield* manager.createTab("tab_listener_failure");
expect(delivered).toHaveBeenCalledOnce();
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
expect(loggedErrors).toHaveLength(1);
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
expect(loggedErrors[0]).toMatchObject({
operation: "send-window-message",
windowId: 42,
channel: "preview:state-change",
});
}),
).pipe(
Effect.provide(
Logger.layer([logger], {
mergeWithExisting: false,
}),
),
);
});
effectIt.effect("does not swallow state listener interruption", () =>
withManager((manager) =>
Effect.gen(function* () {
const exit = yield* Effect.scoped(
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.interrupt);
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
}),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
}
}),
),
);
effectIt.effect("queues navigation until the webview registers", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -307,20 +237,6 @@ 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,
});
}),
),
);
@@ -386,12 +302,9 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewArtifactPathOutsideDirectoryError",
artifactPath: "/tmp/t3/dev/settings.json",
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
expect(error.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
});
expect("cause" in error).toBe(false);
}),
),
);
@@ -411,20 +324,8 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
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,
expect(error.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
});
}),
),
@@ -479,11 +380,7 @@ describe("PreviewManager", () => {
},
} as never);
yield* manager.subscribePointerEvents((event) =>
Effect.sync(() => {
activity.push(event.phase);
}),
);
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const click = yield* manager
@@ -569,174 +466,10 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
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,
expect(error.cause).toMatchObject({
name: "PreviewAutomationControlInterruptedError",
});
}),
),
);
});
describe("PreviewOperationError", () => {
it("keeps timeline detail separate from its structured message", () => {
const cause = new Error("CDP command failed with an invalid node id");
const error = new PreviewManager.PreviewOperationError({
operation: "click.DOM.resolveNode",
tabId: "tab_1",
webContentsId: 42,
cause,
});
expect(error.message).not.toContain(cause.message);
expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
});
});
describe("Preview automation diagnostics", () => {
it("keeps browser exception detail out of structural diagnostics", () => {
const secret = "unrelated-browser-payload-secret";
const detail = "ReferenceError: missingValue is not defined";
const cause = {
text: "Uncaught Error",
exception: { description: detail },
unsafePayload: secret,
};
const error = new PreviewManager.PreviewAutomationEvaluationError({
tabId: "tab_1",
detailKind: "exception-description",
detailLength: detail.length,
cause,
});
const encoded = encodePreviewManagerError(error);
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
readonly cause?: unknown;
};
expect(error.cause).toBe(cause);
expect(encodedCause).toStrictEqual(cause);
expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
expect(error.message).not.toContain(secret);
expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
expect("detail" in error).toBe(false);
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
secret,
);
});
it("retains bounded selector diagnostics without exposing selector or reason text", () => {
const selector = "role=button[name='selector-secret']";
const reason = "Unexpected token near reason-secret";
const cause = { invalidSelector: true as const, message: reason };
const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
operation: "click",
tabId: "tab_1",
selectorKind: "locator",
selectorLength: selector.length,
reasonLength: reason.length,
cause,
});
const encoded = encodePreviewManagerError(error);
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
readonly cause?: unknown;
};
expect(error.cause).toBe(cause);
expect(encodedCause).toStrictEqual(cause);
expect(error).toMatchObject({
selectorKind: "locator",
selectorLength: selector.length,
reasonLength: reason.length,
});
expect(error.detail).toEqual({
selectorKind: "locator",
selectorLength: selector.length,
});
expect(error.message).not.toContain("secret");
expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
expect("selector" in error).toBe(false);
expect("reason" in error).toBe(false);
expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
reason,
);
});
it("does not retain a missing target locator", () => {
const selector = "[data-token='target-secret']";
const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
operation: "scroll",
tabId: "tab_1",
selectorKind: "selector",
selectorLength: selector.length,
});
expect(error.message).not.toContain(selector);
expect(JSON.stringify(error)).not.toContain(selector);
expect("locator" in error).toBe(false);
});
});
File diff suppressed because it is too large. Load diff
@@ -3,14 +3,10 @@ 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* () {
@@ -27,54 +23,4 @@ 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,180 +4,69 @@ 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 PlaywrightPackageResolveError extends Schema.TaggedErrorClass<PlaywrightPackageResolveError>()(
"PlaywrightPackageResolveError",
{
specifier: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to resolve Playwright package: ${this.specifier}`;
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 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;
});
const fail = (operation: string, cause: unknown) =>
new PlaywrightInjectedRuntimeError({ operation, cause });
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
function* () {
const packageJsonPath = yield* Effect.try({
try: () => require.resolve(PLAYWRIGHT_PACKAGE_SPECIFIER),
catch: (cause) =>
new PlaywrightPackageResolveError({
specifier: PLAYWRIGHT_PACKAGE_SPECIFIER,
cause,
}),
try: () => require.resolve("playwright-core/package.json"),
catch: (cause) => fail("resolvePackage", cause),
});
const bundlePath = NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js");
const coreBundle = yield* Effect.tryPromise({
try: () => NodeFSP.readFile(bundlePath, "utf8"),
catch: (cause) => new PlaywrightCoreBundleReadError({ bundlePath, cause }),
try: () =>
NodeFSP.readFile(
NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js"),
"utf8",
),
catch: (cause) => fail("readCoreBundle", cause),
});
return yield* extractPlaywrightInjectedRuntimeSource(coreBundle, bundlePath);
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;
},
);
@@ -187,23 +76,14 @@ export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
const source = yield* playwrightInjectedRuntimeSource();
const options = yield* encodeUnknownJson({
isUnderTest: false,
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
sdkLanguage: "javascript",
testIdAttributeName: "data-testid",
stableRafCount: 1,
browserName: PLAYWRIGHT_BROWSER_NAME,
browserName: "chromium",
shouldPrependErrorPrefix: false,
isUtilityWorld: false,
customEngines: [],
}).pipe(
Effect.mapError(
(cause) =>
new PlaywrightOptionsEncodeError({
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
browserName: PLAYWRIGHT_BROWSER_NAME,
cause,
}),
),
);
}).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
return `(() => {
if (globalThis.__t3PlaywrightInjected) return true;
const module = { exports: {} };
+20 -47
View File
@@ -83,6 +83,12 @@ export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSe
}
}
const writeError = (
operation: DesktopSettingsWriteOperation,
path: string,
cause: unknown,
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
export class DesktopAppSettings extends Context.Service<
DesktopAppSettings,
{
@@ -238,46 +244,18 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "encode-document",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "replace-settings-file",
path: input.settingsPath,
cause,
}),
),
);
).pipe(Effect.mapError((cause) => writeError("encode-document", 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* () {
@@ -298,13 +276,8 @@ export const make = Effect.gen(function* () {
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-temporary-file-name",
path: environment.desktopSettingsPath,
cause,
}),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
),
Effect.flatMap((suffix) =>
writeSettings({
@@ -1,129 +0,0 @@
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 Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
interface LogRecord {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
const baseDir = "/virtual-home";
function makeLayer(fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopClientSettings.layer.pipe(
Layer.provideMerge(Layer.mergeAll(environmentLayer, NodeServices.layer, fileSystemLayer)),
);
}
const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
const records: Array<LogRecord> = [];
const logger = Logger.make(({ fiber, message }) => {
records.push({
message,
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
});
});
return Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
return {
result: yield* settings.get,
settingsPath: environment.clientSettingsPath,
records,
};
}).pipe(
Effect.provide(
Layer.mergeAll(
makeLayer(fileSystemLayer),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
};
describe("DesktopClientSettings diagnostics", () => {
it.effect("treats a missing settings file as expected without warning", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(FileSystem.layerNoop({}));
assert.isTrue(Option.isNone(result.result));
assert.deepEqual(result.records, []);
}),
);
it.effect("logs non-missing filesystem failures with the settings path", () => {
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
});
return Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
assert.deepEqual(result.records[0]?.message, [
"Could not read desktop client settings.",
permissionError,
]);
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
});
});
it.effect("logs malformed settings documents with the settings path", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.succeed("{not-json"),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
const message = result.records[0]?.message;
if (!Array.isArray(message)) {
return assert.fail("expected structured warning arguments");
}
assert.equal(message[0], "Could not decode desktop client settings.");
const schemaError = message[1];
if (schemaError === null || typeof schemaError !== "object") {
return assert.fail("expected the schema error in the warning");
}
assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError");
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
}),
);
});
@@ -5,7 +5,6 @@ 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";
@@ -118,13 +117,11 @@ describe("DesktopClientSettings", () => {
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsWriteError);
assert.equal(error.operation, "replace-settings-file");
assert.equal(error.path, environment.clientSettingsPath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.isString(error.cause.stack);
assert.exists(error.cause);
assert.equal(
error.message,
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
);
assert.notInclude(error.message, error.cause.message);
}),
),
);
@@ -25,9 +25,7 @@ const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
decodeLegacyClientSettingsDocumentJson(raw).pipe(
Effect.map((document) => document.settings),
Effect.catchTags({
SchemaError: () => decodeClientSettingsJsonValue(raw),
}),
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
);
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
@@ -38,6 +36,7 @@ const DesktopClientSettingsWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-settings-file",
]);
type DesktopClientSettingsWriteOperation = typeof DesktopClientSettingsWriteOperation.Type;
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
"DesktopClientSettingsWriteError",
@@ -52,6 +51,13 @@ 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,
{
@@ -67,29 +73,14 @@ const readClientSettings = (
settingsPath: string,
): Effect.Effect<Option.Option<ClientSettings>> =>
fileSystem.readFileString(settingsPath).pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none<string>())
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<string>()),
),
}),
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<ClientSettings>()),
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.catchTags({
SchemaError: (cause) =>
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<ClientSettings>()),
),
}),
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
),
}),
),
@@ -105,45 +96,19 @@ 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) =>
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,
}),
),
Effect.mapError((cause) => writeError("encode-document", 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* () {
@@ -159,13 +124,8 @@ export const make = Effect.gen(function* () {
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "create-temporary-file-name",
path: environment.clientSettingsPath,
cause,
}),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.clientSettingsPath, cause),
),
Effect.flatMap((suffix) =>
writeClientSettings({
@@ -271,11 +271,10 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("adds saved-environment context to safe storage availability failures", () => {
it.effect("surfaces typed 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]);
@@ -286,22 +285,8 @@ describe("DesktopSavedEnvironments", () => {
})
.pipe(Effect.flip);
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);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
assert.equal(error.cause, cause);
}),
{ availabilityError: cause },
);
@@ -77,12 +77,7 @@ const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-registry-file",
]);
const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-secret",
"decrypt-secret",
]);
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
"DesktopSavedEnvironmentsWriteError",
@@ -97,6 +92,17 @@ 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",
{
@@ -135,20 +141,6 @@ 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;
@@ -160,11 +152,11 @@ export type DesktopSavedEnvironmentsMutationError =
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadRegistryError
| DesktopSavedEnvironmentSecretDecodeError
| DesktopSavedEnvironmentSecretProtectionError;
| ElectronSafeStorage.ElectronSafeStorageError;
export type DesktopSavedEnvironmentsSetSecretError =
| DesktopSavedEnvironmentsMutationError
| DesktopSavedEnvironmentSecretProtectionError;
| ElectronSafeStorage.ElectronSafeStorageError;
export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments,
@@ -284,45 +276,19 @@ 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) =>
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,
}),
),
Effect.mapError((cause) => writeError("encode-registry", 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)),
);
},
);
@@ -375,13 +341,8 @@ export const make = Effect.gen(function* () {
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "create-temporary-file-name",
path: environment.savedEnvironmentRegistryPath,
cause,
}),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
),
Effect.flatMap((suffix) =>
writeRegistryDocument({
@@ -435,21 +396,7 @@ export const make = Effect.gen(function* () {
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
);
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) {
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
@@ -458,19 +405,7 @@ export const make = Effect.gen(function* () {
environment.savedEnvironmentRegistryPath,
encoded.value,
);
return Option.some(
yield* safeStorage.decryptString(secretBytes).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "decrypt-secret",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
),
);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}),
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
const { environmentId, secret } = input;
@@ -480,34 +415,11 @@ export const make = Effect.gen(function* () {
environment.savedEnvironmentRegistryPath,
);
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "check-encryption-availability",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
);
if (!encryptionAvailable) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedBearerToken = Encoding.encodeBase64(
yield* safeStorage.encryptString(secret).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "encrypt-secret",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
),
);
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
let found = false;
const nextDocument: SavedEnvironmentRegistryDocument = {
version: document.version,
@@ -1,23 +1,15 @@
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 * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
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]) => [
@@ -67,7 +59,6 @@ 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,
@@ -77,11 +68,7 @@ function runShellEnvironment(input: {
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
input.failure === undefined
? Effect.succeed(makeProcess(input.handler(command)))
: Effect.fail(input.failure),
),
ChildProcessSpawner.make((command) => Effect.succeed(makeProcess(input.handler(command)))),
);
const program = Effect.gen(function* () {
@@ -242,44 +229,4 @@ 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,7 +3,6 @@ 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";
@@ -21,44 +20,6 @@ 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,
{
@@ -166,18 +127,6 @@ 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) => {
@@ -226,14 +175,13 @@ 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;
const output = yield* spawner
return yield* spawner
.string(
ChildProcess.make(input.command, input.args, {
shell: input.shell ?? false,
@@ -245,33 +193,10 @@ 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 = (
@@ -281,14 +206,12 @@ 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,
@@ -311,7 +234,6 @@ 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,7 +23,6 @@ describe("sshEnvironment", () => {
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
requestId: "prompt-1",
destination: "devbox",
operation: "send-prompt-request",
cause: new Error("renderer send failed"),
});
@@ -17,13 +17,7 @@ interface SentMessage {
readonly args: readonly unknown[];
}
function makeTestWindow(
options: {
readonly isDestroyedError?: unknown;
readonly isMinimizedError?: unknown;
readonly sendError?: unknown;
} = {},
) {
function makeTestWindow() {
const listeners = new Map<string, Set<() => void>>();
const sentMessages: SentMessage[] = [];
let destroyed = false;
@@ -32,18 +26,8 @@ function makeTestWindow(
let focused = false;
const window = {
isDestroyed: () => {
if (options.isDestroyedError !== undefined) {
throw options.isDestroyedError;
}
return destroyed;
},
isMinimized: () => {
if (options.isMinimizedError !== undefined) {
throw options.isMinimizedError;
}
return minimized;
},
isDestroyed: () => destroyed,
isMinimized: () => minimized,
restore: () => {
restored = true;
minimized = false;
@@ -61,11 +45,7 @@ function makeTestWindow(
},
webContents: {
send: (channel: string, ...args: readonly unknown[]) => {
const message = { channel, args };
sentMessages.push(message);
if (options.sendError !== undefined) {
throw options.sendError;
}
sentMessages.push({ channel, args });
},
},
};
@@ -75,7 +55,6 @@ function makeTestWindow(
sentMessages,
isRestored: () => restored,
isFocused: () => focused,
closedListenerCount: () => listeners.get("closed")?.size ?? 0,
close: () => {
destroyed = true;
const closedListeners = [...(listeners.get("closed") ?? [])];
@@ -128,7 +107,6 @@ describe("DesktopSshPasswordPrompts", () => {
})
.pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
assert.equal(testWindow.sentMessages.length, 1);
const sent = testWindow.sentMessages[0];
@@ -165,85 +143,4 @@ 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);
});
});
+35 -123
View File
@@ -20,26 +20,7 @@ const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
type DesktopSshPasswordPromptResolutionInput =
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
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;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
"DesktopSshPromptRequestIdGenerationError",
@@ -57,22 +38,20 @@ export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorCl
"DesktopSshPromptWindowUnavailableError",
{
destination: Schema.String,
requestId: Schema.NullOr(Schema.String),
stage: DesktopSshPromptWindowAvailabilityStage,
},
) {
override get message(): string {
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}).`;
return WINDOW_UNAVAILABLE_MESSAGE;
}
}
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
"DesktopSshPromptPresentationError",
{
requestId: Schema.NullOr(Schema.String),
requestId: Schema.String,
destination: Schema.String,
operation: DesktopSshPromptPresentationOperation,
cause: Schema.Defect(),
},
) {
@@ -284,29 +263,9 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
"desktop.sshPasswordPrompts.request",
)(function* (input) {
const window = yield* electronWindow.main;
if (Option.isNone(window)) {
if (Option.isNone(window) || window.value.isDestroyed()) {
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",
});
}
@@ -360,25 +319,11 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
),
);
};
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", () => {
const cleanup = Effect.sync(() => {
if (!window.value.isDestroyed()) {
window.value.removeListener("closed", cancelOnWindowClosed);
}
}).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid);
}).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
const waitForPassword = Deferred.await(deferred).pipe(
Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
Effect.flatMap(
@@ -394,73 +339,40 @@ 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.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({
return yield* Effect.try({
try: () => {
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "after-send",
});
}
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({
window.value.once("closed", cancelOnWindowClosed);
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "after-restore",
});
}
yield* runPresentationOperation("focus-window", () => window.value.focus());
return yield* waitForPassword;
}).pipe(Effect.catch(preferSubmittedPassword));
}).pipe(Effect.ensuring(cleanup));
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));
});
return DesktopSshPasswordPrompts.of({
+3 -259
View File
@@ -7,10 +7,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
@@ -27,9 +24,6 @@ interface UpdatesHarnessOptions {
void,
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
>;
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
readonly stopBackend?: Effect.Effect<void>;
readonly env?: Record<string, string | undefined>;
}
@@ -73,7 +67,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
Effect.sync(() => {
allowDowngrade = value;
}),
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
setDisableDifferentialDownload: () => Effect.void,
checkForUpdates: Effect.sync(() => {
checkCount += 1;
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
@@ -109,7 +103,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => options.stopBackend ?? Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.none()),
snapshot: Effect.succeed({
desiredRunning: false,
@@ -144,23 +138,12 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
),
);
const setUpdateChannelError = options.setUpdateChannelError;
const settingsLayer = setUpdateChannelError
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
: DesktopAppSettings.layer;
const layer = DesktopUpdates.layer.pipe(
Layer.provideMerge(updaterLayer),
Layer.provideMerge(windowLayer),
Layer.provideMerge(backendLayer),
Layer.provideMerge(DesktopState.layer),
Layer.provideMerge(settingsLayer),
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(
DesktopConfig.layerTest({
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
@@ -192,45 +175,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
}
describe("DesktopUpdates", () => {
it("preserves complete causes for update poller and event failures", () => {
const cause = Cause.combine(
Cause.fail(new Error("updater failed")),
Cause.die(new Error("updater defect")),
);
const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
poller: "startup",
cause,
});
const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
event: "download-progress",
cause,
});
const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
operation: "download",
cause,
});
const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
action: "install",
cause,
});
assert.strictEqual(pollerError.cause, cause);
assert.equal(pollerError.poller, "startup");
assert.equal(pollerError.message, "Desktop update startup poller failed.");
assert.strictEqual(eventError.cause, cause);
assert.equal(eventError.event, "download-progress");
assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
assert.strictEqual(reportedError.cause, cause);
assert.equal(reportedError.operation, "download");
assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
assert.strictEqual(unexpectedActionError.cause, cause);
assert.equal(unexpectedActionError.action, "install");
assert.equal(
unexpectedActionError.message,
"Desktop update install action failed unexpectedly.",
);
});
it.effect("configures the updater and runs startup checks on the test clock", () => {
const harness = makeHarness();
@@ -278,178 +222,6 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("keeps raw updater event failures out of update state", () => {
const harness = makeHarness();
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
);
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("error", cause);
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "error");
assert.equal(state.message, "Desktop updater background operation reported an error.");
assert.notInclude(state.message ?? "", "secret");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("logs bounded updater failure context without exposing the cause", () => {
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
);
const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
channel: null,
cause,
});
const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
const loggedAnnotations: Array<Record<string, unknown>> = [];
const logger = Logger.make(({ fiber }) => {
const annotations = fiber.getRef(References.CurrentLogAnnotations);
if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
loggedAnnotations.push(annotations);
}
});
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
yield* updates.check("manual");
const state = yield* updates.getState;
const loggedAnnotation = loggedAnnotations.at(-1);
assert.isDefined(loggedAnnotation);
assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
assert.isNull(loggedAnnotation.channel);
assert.notProperty(loggedAnnotation, "error");
assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
assert.equal(
state.message,
"Electron updater failed to check for updates on channel default.",
);
assert.notInclude(state.message ?? "", "secret");
}),
).pipe(
Effect.provide(
Layer.mergeAll(
TestClock.layer(),
harness.layer,
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
});
it.effect("recovers download state after an unexpected setup failure", () => {
let disableDifferentialCalls = 0;
const harness = makeHarness({
setDisableDifferentialDownload: Effect.suspend(() => {
disableDifferentialCalls += 1;
return disableDifferentialCalls === 1
? Effect.void
: Effect.die(new Error("download setup failed"));
}),
});
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.download;
assert.isTrue(result.accepted);
assert.isFalse(result.completed);
const failedState = yield* updates.getState;
assert.equal(failedState.status, "available");
assert.equal(failedState.errorContext, "download");
assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
const changedState = yield* updates.setChannel("nightly");
assert.equal(changedState.channel, "nightly");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("restores download state and permits retry after interruption", () =>
Effect.gen(function* () {
const actionStarted = yield* Deferred.make<void>();
let disableDifferentialCalls = 0;
const harness = makeHarness({
setDisableDifferentialDownload: Effect.suspend(() => {
disableDifferentialCalls += 1;
if (disableDifferentialCalls === 1) {
return Effect.void;
}
if (disableDifferentialCalls === 2) {
return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
}
return Effect.void;
}),
});
yield* Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
yield* Deferred.await(actionStarted);
yield* Fiber.interrupt(downloadFiber);
const interruptedState = yield* updates.getState;
assert.equal(interruptedState.status, "available");
assert.isNull(interruptedState.message);
const retry = yield* updates.download;
assert.isTrue(retry.accepted);
assert.isTrue(retry.completed);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("clears quitting state after an unexpected install setup failure", () => {
const harness = makeHarness({
stopBackend: Effect.die(new Error("backend stop failed")),
});
return Effect.scoped(
Effect.gen(function* () {
const desktopState = yield* DesktopState.DesktopState;
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.install;
assert.isTrue(result.accepted);
assert.isFalse(result.completed);
assert.isFalse(yield* Ref.get(desktopState.quitting));
const failedState = yield* updates.getState;
assert.equal(failedState.status, "downloaded");
assert.equal(failedState.errorContext, "install");
assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
const changedState = yield* updates.setChannel("nightly");
assert.equal(changedState.channel, "nightly");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("persists channel changes through the settings service", () => {
const harness = makeHarness();
@@ -512,7 +284,6 @@ describe("DesktopUpdates", () => {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
assert.equal(error.action, "check");
assert.equal(error.requestedChannel, "nightly");
}
yield* Deferred.succeed(releaseCheck, undefined);
@@ -521,31 +292,4 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
operation: "replace-settings-file",
path: "/tmp/settings.json",
cause: diskFailure,
});
const harness = makeHarness({ setUpdateChannelError: settingsFailure });
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
assert.equal(error.channel, "nightly");
assert.strictEqual(error.cause, settingsFailure);
assert.strictEqual(error.cause.cause, diskFailure);
assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
assert.notInclude(error.message, diskFailure.message);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
});
+57 -218
View File
@@ -1,10 +1,9 @@
import {
DesktopUpdateChannelSchema,
type DesktopRuntimeInfo,
type DesktopUpdateActionResult,
type DesktopUpdateChannel,
type DesktopUpdateCheckResult,
type DesktopUpdateState,
import type {
DesktopRuntimeInfo,
DesktopUpdateActionResult,
DesktopUpdateChannel,
DesktopUpdateCheckResult,
DesktopUpdateState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
@@ -64,82 +63,30 @@ export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<
"DesktopUpdateActionInProgressError",
{
action: Schema.Literals(["check", "download", "install"]),
requestedChannel: DesktopUpdateChannelSchema,
},
) {
override get message(): string {
return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
}
}
export class DesktopUpdateChannelPersistenceError extends Schema.TaggedErrorClass<DesktopUpdateChannelPersistenceError>()(
"DesktopUpdateChannelPersistenceError",
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
"DesktopUpdatePersistenceError",
{
channel: DesktopUpdateChannelSchema,
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist the ${this.channel} desktop update channel.`;
}
}
export class DesktopUpdatePollerError extends Schema.TaggedErrorClass<DesktopUpdatePollerError>()(
"DesktopUpdatePollerError",
{
poller: Schema.Literals(["startup", "poll"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop update ${this.poller} poller failed.`;
}
}
export class DesktopUpdateEventHandlingError extends Schema.TaggedErrorClass<DesktopUpdateEventHandlingError>()(
"DesktopUpdateEventHandlingError",
{
event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle desktop update ${this.event} event.`;
}
}
export class DesktopUpdaterReportedError extends Schema.TaggedErrorClass<DesktopUpdaterReportedError>()(
"DesktopUpdaterReportedError",
{
operation: Schema.Literals(["check", "download", "install", "background"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop updater ${this.operation} operation reported an error.`;
}
}
export class DesktopUpdateUnexpectedActionError extends Schema.TaggedErrorClass<DesktopUpdateUnexpectedActionError>()(
"DesktopUpdateUnexpectedActionError",
{
action: Schema.Literals(["download", "install"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop update ${this.action} action failed unexpectedly.`;
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
return `Failed to persist desktop update settings: ${detail}`;
}
}
export type DesktopUpdateConfigureError = never;
export const DesktopUpdateSetChannelError = Schema.Union([
DesktopUpdateActionInProgressError,
DesktopUpdateChannelPersistenceError,
]);
export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
export const isDesktopUpdateSetChannelError = Schema.is(DesktopUpdateSetChannelError);
export type DesktopUpdateSetChannelError =
| DesktopUpdateActionInProgressError
| DesktopUpdatePersistenceError;
export class DesktopUpdates extends Context.Service<
DesktopUpdates,
@@ -361,21 +308,16 @@ export const make = Effect.gen(function* () {
return yield* electronUpdater.checkForUpdates.pipe(
Effect.as(true),
Effect.catchTags({
ElectronUpdaterCheckForUpdatesError: Effect.fn(
"desktop.updates.handleCheckForUpdatesFailure",
)(function* (error) {
Effect.catch(
Effect.fn("desktop.updates.handleCheckForUpdatesFailure")(function* (error) {
const failedAt = yield* currentIsoTimestamp;
yield* updateState((current) =>
reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
yield* logUpdaterError("failed to check for updates", { message: error.message });
return true;
}),
}),
),
Effect.ensuring(Ref.set(updateCheckInFlightRef, false)),
);
});
@@ -400,50 +342,19 @@ export const make = Effect.gen(function* () {
yield* electronUpdater.downloadUpdate;
return { accepted: true, completed: true };
}).pipe(
Effect.catchTags({
ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
function* (error) {
yield* updateState((current) =>
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
return { accepted: true, completed: false };
},
),
}),
Effect.onInterrupt(() =>
updateState((current) => (current.status === "downloading" ? state : current)).pipe(
Effect.asVoid,
),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
return Effect.gen(function* () {
Effect.catch(
Effect.fn("desktop.updates.handleDownloadFailure")(function* (error) {
yield* updateState((current) =>
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
action: error.action,
});
yield* logUpdaterError("failed to download update", { message: error.message });
return { accepted: true, completed: false };
});
}),
}),
),
Effect.ensuring(Ref.set(updateDownloadInFlightRef, false)),
);
}).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
const resetInstallAction = Effect.all(
[Ref.set(updateInstallInFlightRef, false), Ref.set(desktopState.quitting, false)],
{ discard: true },
);
const installDownloadedUpdate = Effect.gen(function* () {
const state = yield* Ref.get(updateStateRef);
if (
@@ -466,38 +377,14 @@ export const make = Effect.gen(function* () {
});
return { accepted: true, completed: false };
}).pipe(
Effect.catchTags({
ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
function* (error) {
yield* resetInstallAction;
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
isSilent: error.isSilent,
isForceRunAfter: error.isForceRunAfter,
});
return { accepted: true, completed: false };
},
),
}),
Effect.onInterrupt(() => resetInstallAction),
Effect.catchCause((cause) =>
Effect.gen(function* () {
if (Cause.hasInterruptsOnly(cause)) {
return yield* Effect.failCause(cause);
}
yield* resetInstallAction;
const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
Effect.catch(
Effect.fn("desktop.updates.handleInstallFailure")(function* (error) {
yield* Ref.set(updateInstallInFlightRef, false);
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
action: error.action,
});
yield* Ref.set(desktopState.quitting, false);
yield* logUpdaterError("failed to install update", { message: error.message });
return { accepted: true, completed: false };
}),
),
@@ -507,31 +394,17 @@ export const make = Effect.gen(function* () {
const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
Effect.andThen(checkForUpdates("startup")),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdatePollerError({ poller: "startup", cause });
return logUpdaterError(error.message, {
errorTag: error._tag,
poller: error.poller,
});
}),
Effect.catchCause((cause) =>
logUpdaterError("startup update check failed", { cause: Cause.pretty(cause) }),
),
Effect.forkScoped,
);
yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
Effect.andThen(checkForUpdates("poll")),
Effect.forever,
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdatePollerError({ poller: "poll", cause });
return logUpdaterError(error.message, {
errorTag: error._tag,
poller: error.poller,
});
}),
Effect.catchCause((cause) =>
logUpdaterError("poll update check failed", { cause: Cause.pretty(cause) }),
),
Effect.forkScoped,
);
}).pipe(Effect.withSpan("desktop.updates.startPollers"));
@@ -562,16 +435,11 @@ export const make = Effect.gen(function* () {
yield* logUpdaterInfo("update available", { version: info.version });
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed update-available event", {
cause: Cause.pretty(cause),
}),
),
);
});
@@ -584,23 +452,14 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
cause: unknown,
error: unknown,
) {
const activeAction = yield* activeUpdateAction;
const error = new DesktopUpdaterReportedError({
operation: Option.getOrElse(activeAction, () => "background" as const),
cause,
});
const message = error instanceof Error ? error.message : String(error);
if (yield* Ref.get(updateInstallInFlightRef)) {
yield* Ref.set(updateInstallInFlightRef, false);
yield* Ref.set(desktopState.quitting, false);
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
operation: error.operation,
});
yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
yield* logUpdaterError("updater error", { message });
return;
}
@@ -610,7 +469,7 @@ export const make = Effect.gen(function* () {
yield* updateState((current) => ({
...current,
status: "error",
message: error.message,
message,
checkedAt,
downloadPercent: null,
errorContext,
@@ -618,10 +477,7 @@ export const make = Effect.gen(function* () {
}));
}
yield* logUpdaterError(error.message, {
errorTag: error._tag,
operation: error.operation,
});
yield* logUpdaterError("updater error", { message });
});
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
@@ -643,16 +499,11 @@ export const make = Effect.gen(function* () {
}
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed download-progress event", {
cause: Cause.pretty(cause),
}),
),
);
});
@@ -667,16 +518,11 @@ export const make = Effect.gen(function* () {
yield* logUpdaterInfo("update downloaded", { version: info.version });
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed update-downloaded event", {
cause: Cause.pretty(cause),
}),
),
);
});
@@ -752,10 +598,7 @@ export const make = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
const activeAction = yield* activeUpdateAction;
if (Option.isSome(activeAction)) {
return yield* new DesktopUpdateActionInProgressError({
action: activeAction.value,
requestedChannel: nextChannel,
});
return yield* new DesktopUpdateActionInProgressError({ action: activeAction.value });
}
const state = yield* Ref.get(updateStateRef);
@@ -765,11 +608,7 @@ export const make = Effect.gen(function* () {
yield* desktopSettings
.setUpdateChannel(nextChannel)
.pipe(
Effect.mapError(
(cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
),
);
.pipe(Effect.mapError((cause) => new DesktopUpdatePersistenceError({ cause })));
const enabled = yield* shouldEnableAutoUpdates;
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
@@ -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,18 +14,6 @@ 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,
{
@@ -112,10 +100,12 @@ export const make = Effect.gen(function* () {
effect.pipe(
Effect.annotateLogs({ action }),
Effect.withSpan("desktop.menu.action"),
Effect.catchCause((cause) => {
const error = new DesktopApplicationMenuActionError({ action, cause });
return logMenuError(error.message, { error });
}),
Effect.catchCause((cause) =>
logMenuError("desktop menu action failed", {
action,
cause: Cause.pretty(cause),
}),
),
),
);
};
@@ -397,7 +397,7 @@ function CloudEnvironmentRowShell(props: {
className={cn("text-xs leading-[16px] underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
copyTextWithHaptic(errorTraceId);
}}
onPress={(event) => {
event.stopPropagation();
@@ -441,7 +441,7 @@ function CopyTraceIdButton(props: { readonly traceId: string }) {
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
copyTextWithHaptic(props.traceId);
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
+1 -2
View File
@@ -18,8 +18,7 @@ export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog.`,
cause,
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
+49 -58
View File
@@ -58,8 +58,23 @@ const LegacyStoredShellSnapshot = Schema.Struct({
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog.`,
cause,
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
@@ -85,7 +100,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
}
return directory;
},
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
catch: (cause) => shellPersistenceError(operation, cause),
});
},
);
@@ -102,6 +117,16 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
operation,
message: error.message,
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
@@ -138,7 +163,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
catch: (cause) => shellPersistenceError(operation, cause),
});
});
@@ -159,29 +184,18 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({ operation: "register-connection", cause }),
),
),
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
),
),
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -269,19 +283,15 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
);
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -293,19 +303,15 @@ export const connectionStorageLayer = Layer.effectContext(
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
);
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
@@ -320,11 +326,7 @@ export const connectionStorageLayer = Layer.effectContext(
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
),
);
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -332,7 +334,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadThread: (environmentId, threadId) =>
@@ -343,19 +345,15 @@ export const connectionStorageLayer = Layer.effectContext(
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
),
);
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -370,11 +368,7 @@ export const connectionStorageLayer = Layer.effectContext(
threadId: thread.id,
thread,
}),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
),
);
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -382,7 +376,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
removeThread: (environmentId, threadId) =>
@@ -395,7 +389,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: new ConnectionPersistenceError({ operation: "remove-thread", cause }),
: shellPersistenceError("remove-thread", cause),
),
),
clear: (environmentId) =>
@@ -404,16 +398,14 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
@@ -423,8 +415,7 @@ export const connectionStorageLayer = Layer.effectContext(
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
@@ -1,5 +1,4 @@
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";
@@ -8,18 +7,6 @@ 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;
@@ -28,7 +15,7 @@ export function setLiveActivityUpdatesEnabled(input: {
return Effect.gen(function* () {
yield* Effect.tryPromise({
try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }),
catch: (cause) => new LiveActivityPreferenceSaveError({ enabled: input.enabled, cause }),
catch: (error) => error,
});
yield* refreshAgentAwarenessRegistration();
@@ -1,7 +1,4 @@
import type { NotificationResponse } from "expo-notifications";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
import { describe, expect, it } from "vite-plus/test";
import {
extractAgentNotificationDeepLink,
@@ -21,76 +18,6 @@ function responseWithData(data: Record<string, unknown>, identifier = "notificat
};
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("consumeLastAgentNotificationResponse", () => {
it("reports which initial-response operation failed", async () => {
const cause = new Error("notification lookup unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.reject(cause),
clearLastResponse: () => Promise.resolve(),
handleResponse: vi.fn(),
});
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "read",
}),
);
});
it("routes a response before reporting a clear failure", async () => {
const cause = new Error("notification clear unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const response = responseWithData({}, "notification-clear") as NotificationResponse;
const handleResponse = vi.fn();
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.resolve(response),
clearLastResponse: () => Promise.reject(cause),
handleResponse,
});
expect(handleResponse).toHaveBeenCalledWith(response);
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "clear",
notificationId: "notification-clear",
}),
);
});
it("reports routing failures before clearing the response", async () => {
const cause = new Error("notification routing unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const response = responseWithData({}, "notification-route") as NotificationResponse;
const clearLastResponse = vi.fn(() => Promise.resolve());
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.resolve(response),
clearLastResponse,
handleResponse: () => {
throw cause;
},
});
expect(clearLastResponse).not.toHaveBeenCalled();
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "route",
notificationId: "notification-route",
}),
);
});
});
describe("extractAgentNotificationDeepLink", () => {
it("uses explicit deep links from APNs payload data", () => {
expect(
@@ -3,7 +3,6 @@ import * as Notifications from "expo-notifications";
import { useRouter } from "expo-router";
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
export function useAgentNotificationNavigation(): void {
const router = useRouter();
@@ -19,11 +18,15 @@ export function useAgentNotificationNavigation(): void {
};
const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
void consumeLastAgentNotificationResponse({
getLastResponse: () => Notifications.getLastNotificationResponseAsync(),
clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(),
handleResponse,
});
void Notifications.getLastNotificationResponseAsync()
.then((response) => {
if (response) {
handleResponse(response);
return Notifications.clearLastNotificationResponseAsync();
}
return undefined;
})
.catch(() => undefined);
return () => {
subscription.remove();
@@ -1,6 +1,5 @@
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 =
@@ -8,31 +7,9 @@ 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,
NotificationPermissionReadError | NotificationPermissionRequestError
unknown
> = Effect.gen(function* () {
if (Platform.OS !== "ios") {
return { type: "unsupported" };
@@ -40,7 +17,7 @@ export const requestAgentNotificationPermission: Effect.Effect<
const existing = yield* Effect.tryPromise({
try: () => Notifications.getPermissionsAsync(),
catch: (cause) => new NotificationPermissionReadError({ cause }),
catch: (error) => error,
});
if (existing.granted) {
return { type: "granted" };
@@ -59,7 +36,7 @@ export const requestAgentNotificationPermission: Effect.Effect<
allowSound: true,
},
}),
catch: (cause) => new NotificationPermissionRequestError({ cause }),
catch: (error) => error,
});
return requested.granted
? { type: "granted" }
@@ -1,58 +0,0 @@
import type { NotificationResponse } from "expo-notifications";
import * as Schema from "effect/Schema";
export class NotificationNavigationError extends Schema.TaggedErrorClass<NotificationNavigationError>()(
"NotificationNavigationError",
{
operation: Schema.Literals(["read", "route", "clear"]),
notificationId: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} the last notification response.`;
}
}
export async function consumeLastAgentNotificationResponse(input: {
readonly getLastResponse: () => Promise<NotificationResponse | null>;
readonly clearLastResponse: () => Promise<void>;
readonly handleResponse: (response: NotificationResponse) => void;
}): Promise<void> {
let response: NotificationResponse | null;
try {
response = await input.getLastResponse();
} catch (cause) {
console.error(new NotificationNavigationError({ operation: "read", cause }));
return;
}
if (!response) {
return;
}
try {
input.handleResponse(response);
} catch (cause) {
console.error(
new NotificationNavigationError({
operation: "route",
notificationId: response.notification.request.identifier,
cause,
}),
);
return;
}
try {
await input.clearLastResponse();
} catch (cause) {
console.error(
new NotificationNavigationError({
operation: "clear",
notificationId: response.notification.request.identifier,
cause,
}),
);
}
}
@@ -18,7 +18,6 @@ import { cryptoLayer } from "../cloud/dpop";
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
AgentAwarenessOperationError,
__resetAgentAwarenessRemoteRegistrationForTest,
refreshActiveLiveActivityRemoteRegistration,
refreshAgentAwarenessRegistration,
@@ -268,28 +267,6 @@ describe("makeRelayDeviceRegistrationRequest", () => {
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("preserves Live Activity push-token lookup failures", () => {
const cause = new Error("native token lookup failed");
const activity = {
getPushToken: vi.fn(() => Promise.reject(cause)),
addPushTokenListener: vi.fn(),
};
return Effect.gen(function* () {
const error = yield* Effect.flip(
registerLiveActivityPushToken({ activity: activity as never }),
);
expect(error).toBeInstanceOf(AgentAwarenessOperationError);
expect(error).toMatchObject({
_tag: "AgentAwarenessOperationError",
operation: "read-live-activity-push-token",
cause,
message: "Agent awareness operation read-live-activity-push-token failed.",
});
}).pipe(Effect.provide(relayTestLayer));
});
it.effect(
"reports Live Activity token registration as skipped when relay auth is unavailable",
() => {
@@ -2,7 +2,6 @@ import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Platform } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import {
@@ -29,33 +28,6 @@ import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
const AgentAwarenessOperation = Schema.Literals([
"read-notification-permissions",
"read-native-push-token",
"read-device-registration-relay-token",
"read-device-unregistration-relay-token",
"read-live-activity-registration-relay-token",
"load-device-registration-identifier",
"load-device-registration-preferences",
"load-device-unregistration-identifier",
"read-live-activity-push-token",
"load-live-activity-registration-identifier",
"list-active-live-activities",
]);
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
"AgentAwarenessOperationError",
{
operation: AgentAwarenessOperation,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Agent awareness operation ${this.operation} failed.`;
}
}
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
let pushToStartSubscription: { remove: () => void } | null = null;
@@ -165,22 +137,14 @@ function nativePushTokenRegistration(observedPushToken?: string) {
}
const permissions = yield* Effect.tryPromise({
try: () => Notifications.getPermissionsAsync(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-notification-permissions",
cause,
}),
catch: (error) => error,
});
if (!permissions.granted) {
return { notificationsEnabled: false, pushToken: null };
}
const token = yield* Effect.tryPromise({
try: () => Notifications.getDevicePushTokenAsync(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-native-push-token",
cause,
}),
catch: (error) => error,
}).pipe(
Effect.tapError((error) =>
Effect.sync(() => {
@@ -197,19 +161,16 @@ function nativePushTokenRegistration(observedPushToken?: string) {
});
}
const relayToken = (
operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
) =>
Effect.gen(function* () {
const provider = relayTokenProvider;
if (!provider) {
return null;
}
return yield* Effect.tryPromise({
try: provider,
catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
});
const relayToken = Effect.gen(function* () {
const provider = relayTokenProvider;
if (!provider) {
return null;
}
return yield* Effect.tryPromise({
try: provider,
catch: (error) => error,
});
});
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
@@ -224,7 +185,7 @@ function registerDeviceWithRelay(
return;
}
if (!readRelayConfig()) return;
const token = yield* relayToken("read-device-registration-relay-token");
const token = yield* relayToken;
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled after auth lookup", {
expectedGeneration,
@@ -259,11 +220,7 @@ function unregisterDeviceWithRelay(input: {
if (!readRelayConfig()) return;
const token = yield* Effect.tryPromise({
try: input.tokenProvider,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-device-unregistration-relay-token",
cause,
}),
catch: (error) => error,
});
if (!token) {
logRegistrationDebug("relay device unregistration skipped; user is not signed in");
@@ -283,7 +240,7 @@ function registerLiveActivityWithRelay(
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
if (!readRelayConfig()) return false;
const token = yield* relayToken("read-live-activity-registration-relay-token");
const token = yield* relayToken;
if (!token) {
logRegistrationDebug("relay live activity registration skipped; user is not signed in");
return false;
@@ -424,19 +381,11 @@ function registerDevice(
const [deviceId, preferences] = yield* Effect.all([
Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-registration-identifier",
cause,
}),
catch: (error) => error,
}),
Effect.tryPromise({
try: () => loadPreferences(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-registration-preferences",
cause,
}),
catch: (error) => error,
}),
]);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
@@ -570,11 +519,7 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadAgentAwarenessDeviceId(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-unregistration-identifier",
cause,
}),
catch: (error) => error,
});
if (!deviceId) {
return;
@@ -599,11 +544,7 @@ export function registerLiveActivityPushToken(input: {
const activityPushToken = yield* Effect.tryPromise({
try: () => input.activity.getPushToken(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-live-activity-push-token",
cause,
}),
catch: (error) => error,
});
if (!activityPushToken) {
if (activityPushTokenListeners.has(input.activity)) {
@@ -651,11 +592,7 @@ function registerLiveActivityPushTokenValue(input: {
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-live-activity-registration-identifier",
cause,
}),
catch: (error) => error,
});
const registered = yield* registerLiveActivityWithRelay({
deviceId,
@@ -696,11 +633,7 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
const activities = yield* Effect.try({
try: () => AgentActivity.getInstances(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "list-active-live-activities",
cause,
}),
catch: (error) => error,
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
@@ -4,7 +4,6 @@ import { useState } from "react";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
const { errors, fetchStatus, waitlist } = useWaitlist();
@@ -22,14 +21,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
setRequestError(null);
try {
await joinCloudWaitlist(waitlist, normalizedEmailAddress);
} catch (error) {
console.error(error);
setRequestError(
error instanceof CloudWaitlistJoinRejectedError
? "Could not join the waitlist. Check your email address and try again."
: "Could not join the waitlist. Check your connection and try again.",
);
const { error } = await waitlist.join({ emailAddress: normalizedEmailAddress });
if (error) {
setRequestError("Could not join the waitlist. Check your email address and try again.");
}
} catch {
setRequestError("Could not join the waitlist. Check your connection and try again.");
}
};
@@ -1,48 +0,0 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
CloudWaitlistJoinRejectedError,
CloudWaitlistJoinRequestError,
joinCloudWaitlist,
} from "./cloudWaitlistJoin";
describe("joinCloudWaitlist", () => {
it("submits the provided email address", async () => {
const join = vi.fn().mockResolvedValue({ error: null });
await joinCloudWaitlist({ join }, "[email protected]");
expect(join).toHaveBeenCalledExactlyOnceWith({ emailAddress: "[email protected]" });
});
it("preserves Clerk rejection details without exposing the email address", async () => {
const cause = Object.assign(new Error("The enrollment was rejected."), {
code: "form_identifier_invalid",
});
const join = vi.fn().mockResolvedValue({ error: cause });
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(CloudWaitlistJoinRejectedError);
expect(failure).toMatchObject({
code: "form_identifier_invalid",
cause,
});
expect(String(failure)).not.toContain("[email protected]");
});
it("distinguishes request failures from rejected enrollments", async () => {
const cause = new Error("network unavailable");
const join = vi.fn().mockRejectedValue(cause);
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(CloudWaitlistJoinRequestError);
expect(failure).toMatchObject({ cause });
expect(failure).not.toBeInstanceOf(CloudWaitlistJoinRejectedError);
});
});
@@ -1,46 +0,0 @@
import * as Schema from "effect/Schema";
interface CloudWaitlistJoiner {
readonly join: (input: { emailAddress: string }) => Promise<{
readonly error: { readonly code: string } | null;
}>;
}
export class CloudWaitlistJoinRejectedError extends Schema.TaggedErrorClass<CloudWaitlistJoinRejectedError>()(
"CloudWaitlistJoinRejectedError",
{
code: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Cloud waitlist enrollment was rejected with code "${this.code}".`;
}
}
export class CloudWaitlistJoinRequestError extends Schema.TaggedErrorClass<CloudWaitlistJoinRequestError>()(
"CloudWaitlistJoinRequestError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Cloud waitlist enrollment request failed.";
}
}
export async function joinCloudWaitlist(
waitlist: CloudWaitlistJoiner,
emailAddress: string,
): Promise<void> {
const result = await waitlist.join({ emailAddress }).catch((cause) => {
throw new CloudWaitlistJoinRequestError({ cause });
});
if (result.error) {
throw new CloudWaitlistJoinRejectedError({
code: result.error.code,
cause: result.error,
});
}
}
@@ -1,7 +1,5 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Logger from "effect/Logger";
import * as SecureStore from "expo-secure-store";
import { vi } from "vite-plus/test";
const secureStore = vi.hoisted(() => new Map<string, string>());
@@ -18,10 +16,7 @@ vi.mock("expo-secure-store", () => ({
}),
}));
import {
ManagedRelayTokenStoreError,
managedRelayAccessTokenStore,
} from "./managedRelayTokenStore";
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
it.effect("round-trips and clears persisted managed relay access tokens", () =>
Effect.gen(function* () {
@@ -54,32 +49,3 @@ it.effect("falls back to an empty cache when persisted data is invalid", () =>
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
}),
);
it.effect("logs structured storage failures before falling back to an empty cache", () => {
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
const cause = new Error("secure store unavailable");
vi.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(cause);
return Effect.gen(function* () {
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
const message = messages.find(
(candidate) =>
Array.isArray(candidate) && candidate[0] === "Managed relay token store operation failed.",
);
expect(message).toBeDefined();
const context = (message as ReadonlyArray<unknown>)[1] as {
readonly cause: ManagedRelayTokenStoreError;
};
expect(context.cause).toBeInstanceOf(ManagedRelayTokenStoreError);
expect(context.cause).toMatchObject({
operation: "read",
storageKey: "t3code.cloud.relay-access-tokens",
cause,
});
expect(context.cause.message).not.toContain(cause.message);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
@@ -1,4 +1,5 @@
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
@@ -30,50 +31,36 @@ const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(
);
const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);
export class ManagedRelayTokenStoreError extends Schema.TaggedErrorClass<ManagedRelayTokenStoreError>()(
"ManagedRelayTokenStoreError",
{
operation: Schema.Literals(["read", "decode", "encode", "write", "clear"]),
storageKey: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Managed relay token store operation "${this.operation}" failed for key "${this.storageKey}".`;
}
}
export class ManagedRelayTokenStoreError extends Data.TaggedError("ManagedRelayTokenStoreError")<{
readonly message: string;
readonly cause: unknown;
}> {}
function logStoreFailure(error: ManagedRelayTokenStoreError) {
return Effect.logWarning("Managed relay token store operation failed.", {
errorTag: error._tag,
operation: error.operation,
storageKey: error.storageKey,
cause: error,
});
const storeError =
(message: string) =>
(cause: unknown): ManagedRelayTokenStoreError =>
new ManagedRelayTokenStoreError({ message, cause });
function logStoreFailure(operation: string) {
return (error: ManagedRelayTokenStoreError) =>
Effect.logWarning(`Managed relay token store ${operation} failed.`).pipe(
Effect.annotateLogs({
errorTag: error._tag,
message: error.message,
}),
);
}
const loadManagedRelayAccessTokens = Effect.tryPromise({
try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "read",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
catch: storeError("Could not read persisted relay access tokens."),
}).pipe(
Effect.flatMap((encoded) =>
encoded === null
? Effect.succeed<ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>>([])
: decodeManagedRelayAccessTokenCache(encoded).pipe(
Effect.map((cache) => cache.entries),
Effect.mapError(
(cause) =>
new ManagedRelayTokenStoreError({
operation: "decode",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
),
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
),
),
);
@@ -85,48 +72,34 @@ const saveManagedRelayAccessTokens = (
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
entries,
}).pipe(
Effect.mapError(
(cause) =>
new ManagedRelayTokenStoreError({
operation: "encode",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
),
Effect.mapError(storeError("Could not encode relay access tokens.")),
Effect.flatMap((encoded) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "write",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
catch: storeError("Could not persist relay access tokens."),
}),
),
);
const clearManagedRelayAccessTokens = Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "clear",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
catch: storeError("Could not clear persisted relay access tokens."),
});
export const managedRelayAccessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {
load: loadManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure),
Effect.tapError(logStoreFailure("load")),
Effect.orElseSucceed(() => []),
Effect.withSpan("mobile.managedRelayTokenStore.load"),
),
save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>
saveManagedRelayAccessTokens(entries).pipe(Effect.tapError(logStoreFailure), Effect.ignore),
saveManagedRelayAccessTokens(entries).pipe(
Effect.tapError(logStoreFailure("save")),
Effect.ignore,
),
),
clear: clearManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure),
Effect.tapError(logStoreFailure("clear")),
Effect.ignore,
Effect.withSpan("mobile.managedRelayTokenStore.clear"),
),
@@ -1,11 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
CloudPublicConfigMissingError,
hasTracingPublicConfig,
resolveCloudPublicConfig,
resolveRelayClerkTokenOptions,
} from "./publicConfig";
import { hasTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
@@ -16,12 +11,6 @@ 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 -13
View File
@@ -1,18 +1,6 @@
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: {
@@ -99,7 +87,7 @@ export function hasTracingPublicConfig(
export function resolveRelayClerkTokenOptions() {
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
if (!jwtTemplate) {
throw new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" });
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
}
return relayClerkTokenOptions(jwtTemplate);
}
@@ -101,7 +101,7 @@ export function ConnectionEnvironmentRow(props: {
className="underline"
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(statusTraceId, { target: "connection-trace-id" });
copyTextWithHaptic(statusTraceId);
}}
onPress={(event) => {
event.stopPropagation();
@@ -85,11 +85,7 @@ export function EnvironmentConnectionNotice(props: {
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className="underline decoration-dotted"
onPress={() =>
copyTextWithHaptic(props.connection.traceId!, {
target: "connection-trace-id",
})
}
onPress={() => copyTextWithHaptic(props.connection.traceId!)}
>
{props.connection.traceId}
</Text>
@@ -1,10 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
extractPairingUrlFromQrPayload,
PairingQrPayloadEmptyError,
parsePairingUrl,
} from "./pairing";
import { extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
describe("extractPairingUrlFromQrPayload", () => {
it("trims raw pairing urls from qr payloads", () => {
@@ -22,8 +18,7 @@ describe("extractPairingUrlFromQrPayload", () => {
});
it("rejects empty qr payloads", () => {
expect(() => extractPairingUrlFromQrPayload(" ")).toThrowError(PairingQrPayloadEmptyError);
expect(() => extractPairingUrlFromQrPayload(" ")).toThrowError(
expect(() => extractPairingUrlFromQrPayload(" ")).toThrow(
"Scanned QR code did not contain a pairing URL.",
);
});
+1 -11
View File
@@ -1,17 +1,7 @@
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();
@@ -58,7 +48,7 @@ export function parsePairingUrl(url: string): { host: string; code: string } {
export function extractPairingUrlFromQrPayload(payload: string): string {
const trimmed = payload.trim();
if (!trimmed) {
throw new PairingQrPayloadEmptyError({});
throw new Error("Scanned QR code did not contain a pairing URL.");
}
try {
@@ -8,7 +8,6 @@ import jsxLanguage from "@shikijs/langs/jsx";
import tsxLanguage from "@shikijs/langs/tsx";
import typescriptLanguage from "@shikijs/langs/typescript";
import yamlLanguage from "@shikijs/langs/yaml";
import * as Schema from "effect/Schema";
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffTypes";
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
@@ -16,32 +15,6 @@ import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewD
export type NativeReviewDiffHighlightScheme = "light" | "dark";
export type NativeReviewDiffHighlightEngine = "native" | "javascript";
export class NativeReviewDiffHighlighterUnavailableError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterUnavailableError>()(
"NativeReviewDiffHighlighterUnavailableError",
{},
) {
override get message(): string {
return "The native review diff highlighter is unavailable in this build.";
}
}
export const isNativeReviewDiffHighlighterUnavailableError = Schema.is(
NativeReviewDiffHighlighterUnavailableError,
);
export class NativeReviewDiffHighlighterInitializationError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterInitializationError>()(
"NativeReviewDiffHighlighterInitializationError",
{
requestedEngine: Schema.Literals(["native", "javascript"]),
attemptedEngine: Schema.Literals(["native", "javascript"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the ${this.attemptedEngine} review diff highlighter requested as ${this.requestedEngine}.`;
}
}
export interface NativeReviewDiffHighlighterHandle {
readonly engine: NativeReviewDiffHighlightEngine;
readonly tokenize: (
@@ -224,7 +197,7 @@ function normalizeTokens(
async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
const nativeEngineModule = await import("react-native-shiki-engine");
if (!nativeEngineModule.isNativeEngineAvailable()) {
throw new NativeReviewDiffHighlighterUnavailableError();
throw new Error("Native Shiki engine is not available in this build.");
}
const highlighter = await createHighlighterCore({
@@ -256,52 +229,18 @@ export async function getNativeReviewDiffHighlighter(
engine: NativeReviewDiffHighlightEngine = "native",
): Promise<NativeReviewDiffHighlighterHandle> {
if (engine === "javascript") {
try {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return await javascriptHighlighterPromise;
} catch (cause) {
javascriptHighlighterPromise = null;
throw new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "javascript",
cause,
});
}
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return javascriptHighlighterPromise;
}
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter()
.catch(async (cause: unknown) => {
const nativeError = isNativeReviewDiffHighlighterUnavailableError(cause)
? cause
: new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "native",
cause,
});
console.warn("[debug-native-diff] native highlighter unavailable", {
error: nativeError,
});
try {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return await javascriptHighlighterPromise;
} catch (fallbackCause) {
javascriptHighlighterPromise = null;
throw new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "javascript",
cause: new AggregateError(
[nativeError, fallbackCause],
"Native and JavaScript review diff highlighter initialization failed.",
{ cause: nativeError },
),
});
}
})
.catch((error) => {
nativeHighlighterPromise = null;
throw error;
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter().catch((error: unknown) => {
console.warn("[debug-native-diff] native highlighter unavailable", {
error: error instanceof Error ? error.message : String(error),
});
return await nativeHighlighterPromise;
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return javascriptHighlighterPromise;
});
return nativeHighlighterPromise;
}
function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
@@ -58,23 +58,10 @@ describe("resolveNativeReviewDiffView", () => {
it("returns null when the view manager cannot be required", async () => {
setExpoViewConfigAvailable();
const cause = new Error("boom");
expoMocks.requireNativeView.mockImplementation(() => {
throw cause;
throw new Error("boom");
});
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,8 +2,6 @@ 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 {
@@ -130,7 +128,6 @@ 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?.(
@@ -143,10 +140,6 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
return cachedNativeReviewDiffView;
}
if (nativeReviewDiffViewResolutionFailed) {
return null;
}
if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
return null;
}
@@ -155,14 +148,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
NATIVE_REVIEW_DIFF_MODULE_NAME,
);
} catch (cause) {
nativeReviewDiffViewResolutionFailed = true;
console.error(
new NativeViewResolutionError({
nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
cause,
}),
);
} catch {
return null;
}
@@ -1,13 +1,12 @@
import { useCallback, useMemo } from "react";
import { useMemo } from "react";
import {
Markdown,
type CustomRenderers,
type NodeStyleOverrides,
type PartialMarkdownTheme,
} from "react-native-nitro-markdown";
import { ScrollView, Text as NativeText, View } from "react-native";
import { Linking, 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 {
@@ -39,7 +38,7 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
<NativeText
onPress={() => {
if (href) {
void tryOpenExternalUrl(href, "markdown-link");
void Linking.openURL(href);
}
}}
style={{
@@ -144,19 +143,12 @@ 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}
onLinkPress={onLinkPress}
textStyle={styles.nativeTextStyle}
/>
<SelectableMarkdownText markdown={props.markdown} textStyle={styles.nativeTextStyle} />
) : (
<Markdown
options={{ gfm: true }}
@@ -2,7 +2,14 @@ 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, Pressable, ScrollView, Text as RNText, View } from "react-native";
import {
ActivityIndicator,
Linking,
Pressable,
ScrollView,
Text as RNText,
View,
} from "react-native";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import {
EnvironmentId,
@@ -16,7 +23,6 @@ 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";
@@ -249,7 +255,7 @@ function FilePreviewHeader(props: {
)}
onPress={() => {
if (typeof props.externalPreviewUri === "string") {
void tryOpenExternalUrl(props.externalPreviewUri, "file-preview");
void Linking.openURL(props.externalPreviewUri);
}
}}
>
@@ -53,12 +53,11 @@ it("initializes review highlighter state once", async () => {
});
it("stores initialization failures in atom state", async () => {
const cause = new Error("load failed");
const manager = createReviewHighlighterManager({
getRegistry: () => registry,
loader: {
prepare: async () => {
throw cause;
throw new Error("load failed");
},
prepareLanguages: async () => undefined,
getEngine: async () => "javascript",
@@ -68,23 +67,9 @@ it("stores initialization failures in atom state", async () => {
void manager.initialize();
await flushAsyncWork();
const snapshot = manager.getSnapshot();
assert.strictEqual(snapshot.engine, null);
assert.strictEqual(snapshot.status, "error");
assert.strictEqual(snapshot.error?._tag, "ReviewHighlighterManagerError");
assert.strictEqual(snapshot.error?.operation, "prepare");
assert.deepStrictEqual(snapshot.error?.languages, [
"typescript",
"tsx",
"javascript",
"jsx",
"json",
"yaml",
"bash",
]);
assert.strictEqual(snapshot.error?.cause, cause);
assert.strictEqual(
snapshot.error?.message,
"Review highlighter operation prepare failed for languages typescript, tsx, javascript, jsx, json, yaml, bash.",
);
assert.deepStrictEqual(manager.getSnapshot(), {
engine: null,
error: "load failed",
status: "error",
});
});
@@ -1,5 +1,4 @@
import { useAtomValue } from "@effect/atom-react";
import * as Schema from "effect/Schema";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import { useEffect } from "react";
@@ -13,22 +12,9 @@ import {
export type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
export class ReviewHighlighterManagerError extends Schema.TaggedErrorClass<ReviewHighlighterManagerError>()(
"ReviewHighlighterManagerError",
{
operation: Schema.Literals(["prepare", "prepare-languages", "resolve-engine"]),
languages: Schema.Array(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Review highlighter operation ${this.operation} failed for languages ${this.languages.join(", ")}.`;
}
}
export interface ReviewHighlighterState {
readonly engine: ReviewHighlighterEngine | null;
readonly error: ReviewHighlighterManagerError | null;
readonly error: string | null;
readonly status: ReviewHighlighterStatus;
}
@@ -115,35 +101,24 @@ export function createReviewHighlighterManager(config: {
inFlight = (async () => {
const startedAt = performance.now();
const languages = config.languages ?? REVIEW_INITIAL_LANGUAGES;
let operation: ReviewHighlighterManagerError["operation"] = "prepare";
let engine: ReviewHighlighterEngine;
try {
await config.loader.prepare();
operation = "prepare-languages";
await config.loader.prepareLanguages(languages);
operation = "resolve-engine";
engine = await config.loader.getEngine();
} catch (cause) {
const error = new ReviewHighlighterManagerError({
operation,
languages,
cause,
await config.loader.prepareLanguages(config.languages ?? REVIEW_INITIAL_LANGUAGES);
const engine = await config.loader.getEngine();
const durationMs = Math.round(performance.now() - startedAt);
logReviewHighlighterProviderDiagnostic("initialized", {
durationMs,
engine,
});
logReviewHighlighterProviderDiagnostic("initialization failed", { error });
setState({ engine: null, error, status: "error" });
return;
setState({ engine, error: null, status: "ready" });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
setState({ engine: null, error: message, status: "error" });
} finally {
inFlight = null;
}
const durationMs = Math.round(performance.now() - startedAt);
logReviewHighlighterProviderDiagnostic("initialized", {
durationMs,
engine,
});
setState({ engine, error: null, status: "ready" });
})().finally(() => {
inFlight = null;
});
})();
return inFlight;
}
@@ -10,7 +10,6 @@ import yamlLanguage from "@shikijs/langs/yaml";
import githubDarkDefault from "@shikijs/themes/github-dark-default";
import githubLightDefault from "@shikijs/themes/github-light-default";
import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
import * as Schema from "effect/Schema";
import {
resolveReviewHighlighterEngine,
@@ -23,19 +22,6 @@ import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordD
export type ReviewDiffTheme = "light" | "dark";
export type { ReviewHighlighterEngine };
export class ReviewHighlighterEngineInitializationError extends Schema.TaggedErrorClass<ReviewHighlighterEngineInitializationError>()(
"ReviewHighlighterEngineInitializationError",
{
preferredEngine: Schema.Literals(["native", "javascript"]),
attemptedEngine: Schema.Literals(["native", "javascript"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the ${this.attemptedEngine} review highlighter with ${this.preferredEngine} preferred.`;
}
}
export interface ReviewHighlightedToken {
content: string;
readonly color: string | null;
@@ -241,6 +227,16 @@ function logReviewHighlighterDiagnosticError(message: string, error: unknown): v
if (!isReviewHighlighterDebugLoggingEnabled()) {
return;
}
if (error instanceof Error) {
console.error(`[review-highlighter] ${message}`, {
name: error.name,
message: error.message,
stack: error.stack,
});
return;
}
console.error(`[review-highlighter] ${message}`, error);
}
@@ -262,7 +258,6 @@ async function getHighlighter(): Promise<HighlighterCore> {
if (!highlighterPromise) {
const configuredHighlighterPromise = (async () => {
let nativeEngineAvailable = false;
let nativeInitializationError: ReviewHighlighterEngineInitializationError | undefined;
logReviewHighlighterDiagnostic("initializing", {
configuredPreference: REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
@@ -294,14 +289,9 @@ async function getHighlighter(): Promise<HighlighterCore> {
};
}
} catch (error) {
nativeInitializationError = new ReviewHighlighterEngineInitializationError({
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
attemptedEngine: "native",
cause: error,
});
logReviewHighlighterDiagnosticError(
"native engine initialization failed; falling back to javascript",
nativeInitializationError,
error,
);
nativeEngineAvailable = false;
}
@@ -315,30 +305,11 @@ async function getHighlighter(): Promise<HighlighterCore> {
REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
nativeEngineAvailable,
);
let highlighter: HighlighterCore;
try {
highlighter = await createHighlighterCore({
themes,
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
engine: createJavaScriptRegexEngine(),
});
} catch (cause) {
const javascriptError = new ReviewHighlighterEngineInitializationError({
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
attemptedEngine: "javascript",
cause,
});
if (!nativeInitializationError) throw javascriptError;
throw new ReviewHighlighterEngineInitializationError({
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
attemptedEngine: "javascript",
cause: new AggregateError(
[nativeInitializationError, javascriptError],
"Native and JavaScript review highlighter initialization failed.",
{ cause: nativeInitializationError },
),
});
}
const highlighter = await createHighlighterCore({
themes,
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
engine: createJavaScriptRegexEngine(),
});
logReviewHighlighterDiagnostic("using javascript engine", {
resolvedEngine: engine,
});
@@ -108,11 +108,7 @@ export function useNativeReviewDiffHighlighting(input: {
} catch (error) {
if (!abortController.signal.aborted) {
logReviewDiffDiagnostic("native visible highlight failed", {
error,
resetKey,
scheme,
firstRowIndex: requestRange.firstRowIndex,
lastRowIndex: requestRange.lastRowIndex,
error: error instanceof Error ? error.message : String(error),
});
}
}
@@ -43,23 +43,10 @@ describe("resolveNativeTerminalSurfaceView", () => {
it("returns null when the view manager cannot be required", async () => {
setExpoViewConfigAvailable();
const cause = new Error("boom");
expoMocks.requireNativeView.mockImplementation(() => {
throw cause;
throw new Error("boom");
});
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,8 +2,6 @@ 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 {
@@ -35,7 +33,6 @@ 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?.(
@@ -48,10 +45,6 @@ export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminal
return cachedNativeTerminalSurfaceView;
}
if (nativeTerminalSurfaceViewResolutionFailed) {
return null;
}
if (getExpoViewConfig(NATIVE_TERMINAL_MODULE_NAME) == null) {
return null;
}
@@ -60,14 +53,7 @@ export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminal
cachedNativeTerminalSurfaceView = requireNativeView<NativeTerminalSurfaceProps>(
NATIVE_TERMINAL_MODULE_NAME,
);
} catch (cause) {
nativeTerminalSurfaceViewResolutionFailed = true;
console.error(
new NativeViewResolutionError({
nativeModuleName: NATIVE_TERMINAL_MODULE_NAME,
cause,
}),
);
} catch {
return null;
}
@@ -1,12 +1,11 @@
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useRef } from "react";
import { ActivityIndicator, Pressable, View } from "react-native";
import { ActivityIndicator, Linking, 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";
@@ -31,7 +30,7 @@ export function GitActionProgressOverlay(props: {
const handlePress = useCallback(() => {
if (progress.prUrl) {
void tryOpenExternalUrl(progress.prUrl, "pull-request");
void Linking.openURL(progress.prUrl);
return;
}
if (progress.phase === "success" || progress.phase === "error") {
@@ -1,3 +1,4 @@
import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
@@ -30,7 +31,6 @@ import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import {
hasNativeSelectableMarkdownText,
SelectableMarkdownText,
@@ -1321,10 +1321,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}, []);
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
copyTextWithHaptic(value, {
target: "thread-work-row",
feedback: "selection",
});
void Clipboard.setStringAsync(value);
void Haptics.selectionAsync();
setInteractionState((current) => ({ ...current, copiedRowId: rowId }));
if (copyFeedbackTimeoutRef.current) {
clearTimeout(copyFeedbackTimeoutRef.current);
@@ -13,9 +13,8 @@ import {
import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback, useMemo } from "react";
import { Alert } from "react-native";
import { Alert, Linking } from "react-native";
import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import {
basename,
getTerminalStatusLabel,
@@ -126,8 +125,13 @@ export function ThreadGitControls(props: {
Alert.alert("No open PR", "This branch does not have an open pull request.");
return;
}
if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
Alert.alert("Unable to open PR", "The pull request could not be opened.");
try {
await Linking.openURL(prUrl);
} catch (error) {
Alert.alert(
"Unable to open PR",
error instanceof Error ? error.message : "An error occurred.",
);
}
}, [gitStatus]);
@@ -8,12 +8,11 @@ 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, Pressable, ScrollView, View } from "react-native";
import { Alert, Linking, 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";
@@ -84,8 +83,13 @@ export function GitOverviewSheet() {
Alert.alert("No open PR", "This branch does not have an open pull request.");
return;
}
if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
Alert.alert("Unable to open PR", "The pull request could not be opened.");
try {
await Linking.openURL(prUrl);
} catch (error) {
Alert.alert(
"Unable to open PR",
error instanceof Error ? error.message : "An error occurred.",
);
}
}, [gitStatus.data]);
@@ -1,56 +0,0 @@
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,7 +21,6 @@ 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();
@@ -53,16 +52,15 @@ export function useCreateProjectThread() {
const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
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));
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 isWorktree = input.envMode === "worktree";
+2 -58
View File
@@ -1,8 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({
impactAsync: vi.fn(),
selectionAsync: vi.fn(),
setStringAsync: vi.fn(),
}));
@@ -15,25 +14,15 @@ vi.mock("expo-haptics", () => ({
Light: "light",
},
impactAsync: mocks.impactAsync,
selectionAsync: mocks.selectionAsync,
}));
import {
CopyTextClipboardWriteError,
CopyTextHapticFeedbackError,
copyTextWithHaptic,
} from "./copyTextWithHaptic";
import { copyTextWithHaptic } from "./copyTextWithHaptic";
describe("copyTextWithHaptic", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.setStringAsync.mockReturnValue(new Promise<void>(() => undefined));
mocks.impactAsync.mockResolvedValue(undefined);
mocks.selectionAsync.mockResolvedValue(undefined);
});
afterEach(() => {
vi.restoreAllMocks();
});
it("triggers haptic feedback without waiting for the clipboard promise", () => {
@@ -42,49 +31,4 @@ describe("copyTextWithHaptic", () => {
expect(mocks.setStringAsync).toHaveBeenCalledWith("trace-123");
expect(mocks.impactAsync).toHaveBeenCalledWith("light");
});
it("preserves selection feedback for thread work rows", () => {
copyTextWithHaptic("work output", {
target: "thread-work-row",
feedback: "selection",
});
expect(mocks.setStringAsync).toHaveBeenCalledWith("work output");
expect(mocks.selectionAsync).toHaveBeenCalledOnce();
expect(mocks.impactAsync).not.toHaveBeenCalled();
});
it("reports structured failures without including clipboard contents", async () => {
const clipboardCause = new Error("native clipboard failure");
const hapticCause = new Error("native haptic failure");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
mocks.setStringAsync.mockRejectedValueOnce(clipboardCause);
mocks.impactAsync.mockRejectedValueOnce(hapticCause);
copyTextWithHaptic("secret clipboard contents", { target: "connection-trace-id" });
await vi.waitFor(() => {
expect(consoleError).toHaveBeenCalledTimes(2);
});
const failures = consoleError.mock.calls.map(([failure]) => failure);
const clipboardError = failures.find(
(failure) => failure instanceof CopyTextClipboardWriteError,
);
expect(clipboardError).toBeInstanceOf(CopyTextClipboardWriteError);
expect(clipboardError).toMatchObject({
target: "connection-trace-id",
cause: clipboardCause,
});
expect((clipboardError as Error).message).not.toContain("secret clipboard contents");
const hapticError = failures.find((failure) => failure instanceof CopyTextHapticFeedbackError);
expect(hapticError).toBeInstanceOf(CopyTextHapticFeedbackError);
expect(hapticError).toMatchObject({
target: "connection-trace-id",
feedback: "light-impact",
cause: hapticCause,
});
expect((hapticError as Error).message).not.toContain("secret clipboard contents");
});
});
+3 -66
View File
@@ -1,70 +1,7 @@
import * as Schema from "effect/Schema";
import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
export class CopyTextClipboardWriteError extends Schema.TaggedErrorClass<CopyTextClipboardWriteError>()(
"CopyTextClipboardWriteError",
{
target: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to copy ${this.target} to the clipboard.`;
}
}
export class CopyTextHapticFeedbackError extends Schema.TaggedErrorClass<CopyTextHapticFeedbackError>()(
"CopyTextHapticFeedbackError",
{
target: Schema.String,
feedback: Schema.Literals(["light-impact", "selection"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to trigger ${this.feedback} haptic feedback after copying ${this.target}.`;
}
}
export function copyTextWithHaptic(
value: string,
options: {
readonly target?: string;
readonly feedback?: "light-impact" | "selection";
} = {},
): void {
const target = options.target ?? "text";
const feedback = options.feedback ?? "light-impact";
void (async () => {
try {
await Clipboard.setStringAsync(value);
} catch (cause) {
console.error(
new CopyTextClipboardWriteError({
target,
cause,
}),
);
}
})();
void (async () => {
try {
if (feedback === "selection") {
await Haptics.selectionAsync();
} else {
await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
}
} catch (cause) {
console.error(
new CopyTextHapticFeedbackError({
target,
feedback,
cause,
}),
);
}
})();
export function copyTextWithHaptic(value: string): void {
void Clipboard.setStringAsync(value);
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
}
@@ -1,58 +0,0 @@
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");
});
});
Loaded 100 of 432 files, more files were not shown because too many files have changed in this diff. Show more