Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95144d8d18 | ||
|
|
31078cb4e0 |
No files matched your search
@@ -2,12 +2,10 @@ name: Mobile EAS Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, labeled, unlabeled]
|
||||
|
||||
jobs:
|
||||
preview:
|
||||
name: EAS Preview
|
||||
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/**/*.ts"
|
||||
- "apps/**/*.tsx"
|
||||
- "packages/**/*.ts"
|
||||
- "packages/**/*.tsx"
|
||||
- "infra/**/*.ts"
|
||||
- "infra/**/*.tsx"
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# Effect service review
|
||||
|
||||
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
|
||||
|
||||
## Imports and module namespaces
|
||||
|
||||
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
|
||||
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
|
||||
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
|
||||
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
|
||||
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
|
||||
|
||||
## Service definition
|
||||
|
||||
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
|
||||
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
|
||||
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
|
||||
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
|
||||
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
|
||||
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
|
||||
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
|
||||
## Errors and predicates
|
||||
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
|
||||
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
|
||||
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
|
||||
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Preserve useful comments, invariants, and specification documentation while moving code.
|
||||
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
|
||||
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
|
||||
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
@@ -1,23 +1,23 @@
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeModule from "node:module";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { compile } from "tailwindcss";
|
||||
|
||||
const directory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const appRoot = NodePath.join(directory, "..");
|
||||
const sourcePath = NodePath.join(appRoot, "src", "preview", "Annotation.css");
|
||||
const preloadPath = NodePath.join(appRoot, "src", "preview", "PickPreload.ts");
|
||||
const outputPath = NodePath.join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const tailwindRoot = NodePath.dirname(require.resolve("tailwindcss/package.json"));
|
||||
const directory = dirname(fileURLToPath(import.meta.url));
|
||||
const appRoot = join(directory, "..");
|
||||
const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
|
||||
const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
|
||||
const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
|
||||
const require = createRequire(import.meta.url);
|
||||
const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
|
||||
|
||||
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
|
||||
NodeFSP.readFile(sourcePath, "utf8"),
|
||||
NodeFSP.readFile(preloadPath, "utf8"),
|
||||
NodeFSP.readFile(NodePath.join(tailwindRoot, "theme.css"), "utf8"),
|
||||
NodeFSP.readFile(NodePath.join(tailwindRoot, "preflight.css"), "utf8"),
|
||||
readFile(sourcePath, "utf8"),
|
||||
readFile(preloadPath, "utf8"),
|
||||
readFile(join(tailwindRoot, "theme.css"), "utf8"),
|
||||
readFile(join(tailwindRoot, "preflight.css"), "utf8"),
|
||||
]);
|
||||
|
||||
const candidates = new Set(
|
||||
@@ -37,4 +37,4 @@ const encodedCss = `'${css
|
||||
.replaceAll("\n", "\\n")}'`;
|
||||
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
|
||||
|
||||
await NodeFSP.writeFile(outputPath, moduleSource);
|
||||
await writeFile(outputPath, moduleSource);
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
desktopDir,
|
||||
@@ -64,7 +64,7 @@ function killChildTreeByPid(pid, signal) {
|
||||
return;
|
||||
}
|
||||
|
||||
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
@@ -72,9 +72,7 @@ function cleanupStaleDevApps() {
|
||||
return;
|
||||
}
|
||||
|
||||
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
@@ -89,7 +87,7 @@ function startApp() {
|
||||
? electronArgs
|
||||
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
|
||||
const electronCommand = resolveElectronLaunchCommand(launchArgs);
|
||||
const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
const app = spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
@@ -182,8 +180,8 @@ function scheduleRestart() {
|
||||
|
||||
function startWatchers() {
|
||||
for (const { directory, files } of watchedDirectories) {
|
||||
const watcher = NodeFS.watch(
|
||||
NodePath.join(desktopDir, directory),
|
||||
const watcher = watch(
|
||||
join(desktopDir, directory),
|
||||
{ persistent: true },
|
||||
(_eventType, filename) => {
|
||||
if (typeof filename !== "string" || !files.has(filename)) {
|
||||
@@ -204,9 +202,7 @@ function killChildTree(signal) {
|
||||
}
|
||||
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
async function shutdown(exitCode) {
|
||||
|
||||
@@ -1,18 +1,29 @@
|
||||
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
|
||||
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeModule from "node:module";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
chmodSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
export const desktopDir = NodePath.resolve(__dirname, "..");
|
||||
const repoRoot = NodePath.resolve(desktopDir, "..", "..");
|
||||
const devBundleIdSuffix = NodePath.basename(repoRoot)
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
const repoRoot = resolve(desktopDir, "..", "..");
|
||||
const devBundleIdSuffix = basename(repoRoot)
|
||||
.toLowerCase()
|
||||
.replaceAll(/[^a-z0-9]+/g, "");
|
||||
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
@@ -21,35 +32,22 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 12;
|
||||
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = NodePath.join(
|
||||
repoRoot,
|
||||
"assets",
|
||||
"dev",
|
||||
"blueprint-macos-1024.png",
|
||||
);
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-replace", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-insert", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -60,24 +58,16 @@ function setPlistString(plistPath, key, value) {
|
||||
|
||||
function setPlistJson(plistPath, key, value) {
|
||||
const serialized = JSON.stringify(value);
|
||||
const replaceResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-replace", key, "-json", serialized, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-insert", key, "-json", serialized, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -87,7 +77,7 @@ function setPlistJson(plistPath, key, value) {
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
|
||||
const result = spawnSync(command, args, { encoding: "utf8" });
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -101,7 +91,7 @@ function shellSingleQuote(value) {
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
@@ -111,7 +101,7 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
NodeFS.writeFileSync(
|
||||
writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
@@ -120,7 +110,7 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
|
||||
function registerMacLauncherBundle(appBundlePath) {
|
||||
@@ -150,24 +140,21 @@ function registerMacLauncherBundle(appBundlePath) {
|
||||
}
|
||||
|
||||
function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
|
||||
NodeFS.mkdirSync(runtimeDir, { recursive: true });
|
||||
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
|
||||
if (!existsSync(developmentMacIconPngPath)) {
|
||||
return defaultIconPath;
|
||||
}
|
||||
|
||||
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (
|
||||
NodeFS.existsSync(generatedIconPath) &&
|
||||
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
|
||||
) {
|
||||
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
|
||||
return generatedIconPath;
|
||||
}
|
||||
|
||||
const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
|
||||
NodeFS.mkdirSync(iconsetDir, { recursive: true });
|
||||
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = join(iconsetRoot, "icon.iconset");
|
||||
mkdirSync(iconsetDir, { recursive: true });
|
||||
|
||||
try {
|
||||
for (const size of [16, 32, 128, 256, 512]) {
|
||||
@@ -177,7 +164,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
String(size),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
]);
|
||||
|
||||
const retinaSize = size * 2;
|
||||
@@ -187,7 +174,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
String(retinaSize),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -200,12 +187,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
);
|
||||
return defaultIconPath;
|
||||
} finally {
|
||||
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
@@ -217,9 +204,9 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
},
|
||||
]);
|
||||
|
||||
const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
|
||||
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
|
||||
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
|
||||
const resourcesDir = join(appBundlePath, "Contents", "Resources");
|
||||
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
@@ -231,7 +218,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
];
|
||||
|
||||
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
|
||||
const infoPlistPath = NodePath.join(
|
||||
const infoPlistPath = join(
|
||||
appBundlePath,
|
||||
"Contents",
|
||||
"Frameworks",
|
||||
@@ -239,7 +226,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
"Contents",
|
||||
"Info.plist",
|
||||
);
|
||||
if (!NodeFS.existsSync(infoPlistPath)) {
|
||||
if (!existsSync(infoPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -255,34 +242,34 @@ function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(NodeFS.readFileSync(path, "utf8"));
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
|
||||
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
NodeFS.mkdirSync(runtimeDir, { recursive: true });
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
const expectedMetadata = {
|
||||
launcherVersion: LAUNCHER_VERSION,
|
||||
sourceAppBundlePath,
|
||||
sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
|
||||
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: statSync(iconPath).mtimeMs,
|
||||
appBundleId: APP_BUNDLE_ID,
|
||||
appProtocolSchemes: APP_PROTOCOL_SCHEMES,
|
||||
};
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
NodeFS.existsSync(targetBinaryPath) &&
|
||||
existsSync(targetBinaryPath) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
@@ -290,21 +277,18 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
// verbatimSymlinks keeps the framework's relative symlinks intact
|
||||
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
|
||||
// rewrites them to absolute paths into node_modules, which escape the
|
||||
// bundle and crash sandboxed helper processes (icudtl.dat not found).
|
||||
NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
});
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
|
||||
return targetBinaryPath;
|
||||
@@ -315,9 +299,9 @@ function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
|
||||
const sandboxPath = join(dirname(electronBinaryPath), "chrome-sandbox");
|
||||
try {
|
||||
const sandboxStat = NodeFS.statSync(sandboxPath);
|
||||
const sandboxStat = statSync(sandboxPath);
|
||||
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
|
||||
} catch {
|
||||
return false;
|
||||
@@ -338,7 +322,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
|
||||
export function resolveElectronPath() {
|
||||
ensureElectronRuntime();
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (hostPlatform !== "darwin") {
|
||||
@@ -361,11 +345,11 @@ export function resolveDevProtocolClient() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
|
||||
return {
|
||||
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
appBundleId: APP_BUNDLE_ID,
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeModule from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { arch, platform, tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const require = createRequire(import.meta.url);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
const hostPlatform = platform();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostArch = NodeOS.arch();
|
||||
const hostArch = arch();
|
||||
|
||||
function getPlatformPath() {
|
||||
switch (hostPlatform) {
|
||||
@@ -27,28 +27,26 @@ function getPlatformPath() {
|
||||
|
||||
function ensureExecutable(filePath) {
|
||||
if (hostPlatform !== "win32") {
|
||||
NodeFS.chmodSync(filePath, 0o755);
|
||||
chmodSync(filePath, 0o755);
|
||||
}
|
||||
}
|
||||
|
||||
function repairPathFile(electronDir, platformPath) {
|
||||
const pathFile = NodePath.join(electronDir, "path.txt");
|
||||
const currentPath = NodeFS.existsSync(pathFile)
|
||||
? NodeFS.readFileSync(pathFile, "utf8")
|
||||
: undefined;
|
||||
const pathFile = join(electronDir, "path.txt");
|
||||
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
|
||||
|
||||
if (currentPath !== platformPath) {
|
||||
NodeFS.writeFileSync(pathFile, platformPath);
|
||||
writeFileSync(pathFile, platformPath);
|
||||
}
|
||||
}
|
||||
|
||||
function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
const paths = [NodePath.join(electronDir, "dist", platformPath)];
|
||||
const paths = [join(electronDir, "dist", platformPath)];
|
||||
|
||||
if (hostPlatform === "darwin") {
|
||||
paths.push(
|
||||
NodePath.join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
NodePath.join(
|
||||
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
join(
|
||||
electronDir,
|
||||
"dist",
|
||||
"Electron.app",
|
||||
@@ -68,7 +66,7 @@ function isMachO(filePath) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const result = NodeChildProcess.spawnSync("file", ["-b", filePath], {
|
||||
const result = spawnSync("file", ["-b", filePath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
@@ -77,7 +75,7 @@ function isMachO(filePath) {
|
||||
|
||||
function missingRuntimePaths(electronDir, platformPath) {
|
||||
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
|
||||
return !NodeFS.existsSync(runtimePath);
|
||||
return !existsSync(runtimePath);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -87,8 +85,8 @@ function invalidRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
return [
|
||||
NodePath.join(electronDir, "dist", platformPath),
|
||||
NodePath.join(
|
||||
join(electronDir, "dist", platformPath),
|
||||
join(
|
||||
electronDir,
|
||||
"dist",
|
||||
"Electron.app",
|
||||
@@ -97,11 +95,11 @@ function invalidRuntimePaths(electronDir, platformPath) {
|
||||
"Electron Framework.framework",
|
||||
"Electron Framework",
|
||||
),
|
||||
].filter((runtimePath) => NodeFS.existsSync(runtimePath) && !isMachO(runtimePath));
|
||||
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = NodeChildProcess.spawnSync(command, args, {
|
||||
const result = spawnSync(command, args, {
|
||||
encoding: "utf8",
|
||||
stdio: "inherit",
|
||||
});
|
||||
@@ -116,8 +114,8 @@ function runChecked(command, args) {
|
||||
}
|
||||
|
||||
function installElectronRuntime(electronDir, version) {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-"));
|
||||
const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
|
||||
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
|
||||
|
||||
try {
|
||||
runChecked("curl", [
|
||||
@@ -127,34 +125,34 @@ function installElectronRuntime(electronDir, version) {
|
||||
zipPath,
|
||||
]);
|
||||
if (hostPlatform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, NodePath.join(electronDir, "dist")]);
|
||||
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
|
||||
} else {
|
||||
runChecked("python3", [
|
||||
"-c",
|
||||
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
|
||||
zipPath,
|
||||
NodePath.join(electronDir, "dist"),
|
||||
join(electronDir, "dist"),
|
||||
]);
|
||||
}
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureElectronRuntime() {
|
||||
const electronPackageJsonPath = require.resolve("electron/package.json");
|
||||
const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8"));
|
||||
const electronDir = NodePath.dirname(electronPackageJsonPath);
|
||||
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
|
||||
const electronDir = dirname(electronPackageJsonPath);
|
||||
const platformPath = getPlatformPath();
|
||||
const electronPath = NodePath.join(electronDir, "dist", platformPath);
|
||||
const electronPath = join(electronDir, "dist", platformPath);
|
||||
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
|
||||
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
|
||||
|
||||
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
|
||||
if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) {
|
||||
NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true });
|
||||
if (existsSync(join(electronDir, "dist"))) {
|
||||
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
|
||||
}
|
||||
NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true });
|
||||
rmSync(join(electronDir, "path.txt"), { force: true });
|
||||
installElectronRuntime(electronDir, electronPackageJson.version);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import { spawn } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const desktopDir = NodePath.resolve(__dirname, "..");
|
||||
const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
const electronCommand = resolveElectronLaunchCommand([mainJs]);
|
||||
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
const child = spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
@@ -6,7 +6,7 @@ const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
|
||||
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
const child = spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeNet from "node:net";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
import * as FileSystem from "node:fs/promises";
|
||||
import * as Net from "node:net";
|
||||
import * as Path from "node:path";
|
||||
import * as Timers from "node:timers/promises";
|
||||
|
||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
||||
|
||||
async function fileExists(filePath) {
|
||||
try {
|
||||
await NodeFSP.access(filePath);
|
||||
await FileSystem.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
@@ -16,7 +16,7 @@ async function fileExists(filePath) {
|
||||
|
||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
||||
return new Promise((resolveReady) => {
|
||||
const socket = NodeNet.createConnection({ host, port });
|
||||
const socket = Net.createConnection({ host, port });
|
||||
let settled = false;
|
||||
|
||||
const finish = (ready) => {
|
||||
@@ -47,7 +47,7 @@ async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, conn
|
||||
const pendingFiles = [];
|
||||
|
||||
for (const relativeFilePath of files) {
|
||||
const ready = await fileExists(NodePath.resolve(baseDir, relativeFilePath));
|
||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
||||
if (!ready) {
|
||||
pendingFiles.push(relativeFilePath);
|
||||
}
|
||||
@@ -114,6 +114,6 @@ export async function waitForResources({
|
||||
);
|
||||
}
|
||||
|
||||
await NodeTimersPromises.setTimeout(intervalMs);
|
||||
await Timers.setTimeout(intervalMs);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
@@ -101,12 +100,12 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
| DesktopLifecycle.DesktopShutdown
|
||||
| DesktopState.DesktopState
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronDialog.ElectronDialog
|
||||
> {
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
@@ -238,7 +237,7 @@ const scopedProgram = Effect.scoped(
|
||||
yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
|
||||
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
|
||||
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
|
||||
@@ -63,7 +63,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
} satisfies ElectronApp.ElectronAppShape);
|
||||
|
||||
const makeAssetsLayer = (png: Option.Option<string>) =>
|
||||
Layer.succeed(DesktopAssets.DesktopAssets, {
|
||||
@@ -73,7 +73,7 @@ const makeAssetsLayer = (png: Option.Option<string>) =>
|
||||
png,
|
||||
}),
|
||||
resolveResourcePath: () => Effect.succeed(Option.none()),
|
||||
} satisfies DesktopAssets.DesktopAssets["Service"]);
|
||||
} satisfies DesktopAssets.DesktopAssetsShape);
|
||||
|
||||
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
|
||||
const { env, ...environmentOverrides } = overrides;
|
||||
|
||||
@@ -18,12 +18,14 @@ const AppPackageMetadata = Schema.Struct({
|
||||
});
|
||||
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
|
||||
|
||||
export interface DesktopAppIdentityShape {
|
||||
readonly resolveUserDataPath: Effect.Effect<string>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopAppIdentity extends Context.Service<
|
||||
DesktopAppIdentity,
|
||||
{
|
||||
readonly resolveUserDataPath: Effect.Effect<string>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
DesktopAppIdentityShape
|
||||
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
|
||||
|
||||
const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
|
||||
@@ -12,13 +12,14 @@ export interface DesktopIconPaths {
|
||||
readonly png: Option.Option<string>;
|
||||
}
|
||||
|
||||
export class DesktopAssets extends Context.Service<
|
||||
DesktopAssets,
|
||||
{
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAssets") {}
|
||||
export interface DesktopAssetsShape {
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
|
||||
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
|
||||
"@t3tools/desktop/app/DesktopAssets",
|
||||
) {}
|
||||
|
||||
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
|
||||
fileName: string,
|
||||
|
||||
@@ -1,280 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
{
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@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;
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
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 }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
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).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
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> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLog.of(service);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendOutputLog, make);
|
||||
@@ -21,6 +21,10 @@ vi.mock("@clerk/electron/storage", () => ({
|
||||
storage: storageMock,
|
||||
}));
|
||||
|
||||
import {
|
||||
createDesktopClerkBridge,
|
||||
resolveDesktopClerkFrontendApiHostname,
|
||||
} from "./DesktopClerk.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
@@ -28,12 +32,9 @@ describe("DesktopClerk", () => {
|
||||
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
|
||||
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
|
||||
|
||||
assert.equal(
|
||||
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
|
||||
"clerk.t3.codes",
|
||||
);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
|
||||
assert.equal(resolveDesktopClerkFrontendApiHostname(publishableKey), "clerk.t3.codes");
|
||||
assert.equal(resolveDesktopClerkFrontendApiHostname(""), undefined);
|
||||
assert.equal(resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
|
||||
});
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
@@ -43,7 +44,7 @@ describe("DesktopClerk", () => {
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment: true,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironmentShape);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(
|
||||
@@ -77,7 +78,7 @@ describe("DesktopClerk", () => {
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
|
||||
assert.equal(createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
|
||||
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
|
||||
@@ -14,16 +14,17 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export class DesktopClerk extends Context.Service<
|
||||
DesktopClerk,
|
||||
{
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopClerk") {}
|
||||
export interface DesktopClerkShape {
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopClerk extends Context.Service<DesktopClerk, DesktopClerkShape>()(
|
||||
"@t3tools/desktop/app/DesktopClerk",
|
||||
) {}
|
||||
|
||||
export function resolveDesktopClerkFrontendApiHostname(
|
||||
publishableKey: string | undefined,
|
||||
|
||||
@@ -21,6 +21,7 @@ const textEncoder = new TextEncoder();
|
||||
const decodeConnectionCatalog = Schema.decodeEffect(
|
||||
Schema.fromJsonString(ConnectionCatalogDocument),
|
||||
);
|
||||
|
||||
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(available),
|
||||
@@ -39,7 +40,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
@@ -235,10 +236,8 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.catalogPath, catalogPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
|
||||
}),
|
||||
),
|
||||
@@ -254,7 +253,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
|
||||
pathOrDescriptor: `${baseDir}/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -271,113 +270,10 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
assert.equal(error.cause, permissionError);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the failed catalog write operation and path", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
makeDirectory: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* store.set("{}").pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
|
||||
);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the legacy migration stage", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError,
|
||||
);
|
||||
assert.equal(error.operation, "read-legacy-registry");
|
||||
assert.equal(error.catalogPath, `${environment.stateDir}/connection-catalog.json`);
|
||||
assert.instanceOf(
|
||||
error.cause,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
const registryError =
|
||||
error.cause as DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
assert.exists(registryError.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${environment.stateDir}/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, registryError.message);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports invalid encrypted catalog data without exposing it", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n');
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError,
|
||||
);
|
||||
assert.equal(error.resource, "encryptedCatalog");
|
||||
assert.equal(error.catalogPath, catalogPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to decode encryptedCatalog for the desktop connection catalog at ${catalogPath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "%%%");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -14,12 +14,14 @@ import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
@@ -46,149 +48,76 @@ const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
RuntimeConnectionCatalogDocumentJson,
|
||||
);
|
||||
|
||||
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-catalog-file",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreWriteOperation =
|
||||
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"read-legacy-registry",
|
||||
"read-legacy-secret",
|
||||
"encode-catalog",
|
||||
"persist-catalog",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreMigrationOperation =
|
||||
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop connection catalog: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopConnectionCatalogStoreWriteError =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
{
|
||||
resource: Schema.Literal("encryptedCatalog"),
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode the desktop connection catalog.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
|
||||
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreReadError",
|
||||
{
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to read desktop connection catalog: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDocumentDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDocumentDecodeError",
|
||||
{
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreMigrationError>()(
|
||||
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreMigrationError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: Schema.String,
|
||||
environmentId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const environment =
|
||||
this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
|
||||
return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to migrate legacy desktop saved environments.";
|
||||
}
|
||||
}
|
||||
|
||||
const migrationError = (
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: string,
|
||||
cause: unknown,
|
||||
environmentId?: string,
|
||||
): DesktopConnectionCatalogStoreMigrationError =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation,
|
||||
catalogPath,
|
||||
...(environmentId === undefined ? {} : { environmentId }),
|
||||
cause,
|
||||
});
|
||||
export interface DesktopConnectionCatalogStoreShape {
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopConnectionCatalogStoreReadError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopConnectionCatalogStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
DesktopConnectionCatalogStore,
|
||||
{
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopConnectionCatalogStoreReadError
|
||||
| DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
DesktopConnectionCatalogStoreShape
|
||||
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
catalogPath: string,
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreDecodeError({
|
||||
resource: "encryptedCatalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -197,32 +126,16 @@ const readDocument = (
|
||||
catalogPath: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<EncryptedConnectionCatalogDocument>,
|
||||
DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
PlatformError.PlatformError | Schema.SchemaError
|
||||
> =>
|
||||
fileSystem.readFileString(catalogPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound"
|
||||
? Effect.succeed<string | null>(null)
|
||||
: Effect.fail(
|
||||
new DesktopConnectionCatalogStoreReadError({
|
||||
catalogPath,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
|
||||
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreDocumentDecodeError({
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -232,24 +145,14 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
|
||||
readonly catalogPath: string;
|
||||
readonly document: EncryptedConnectionCatalogDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-document", input.catalogPath, cause)),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.catalogPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-catalog-file", input.catalogPath, cause)),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
input.fileSystem.remove(tempPath, { force: true }).pipe(
|
||||
@@ -272,11 +175,10 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
|
||||
)(function* (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
|
||||
catalogPath: string,
|
||||
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironmentsShape,
|
||||
): Effect.fn.Return<
|
||||
RuntimeConnectionCatalogDocumentType,
|
||||
DesktopConnectionCatalogStoreMigrationError
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
|
||||
> {
|
||||
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
|
||||
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
|
||||
@@ -330,13 +232,7 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments
|
||||
.getSecret(record.environmentId)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
|
||||
),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId);
|
||||
if (Option.isSome(token)) {
|
||||
credentials.push({
|
||||
connectionId: id,
|
||||
@@ -354,82 +250,79 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
};
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
export const layer = Layer.effect(
|
||||
DesktopConnectionCatalogStore,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
catalogPath,
|
||||
document: { version: 1, encryptedCatalog },
|
||||
suffix,
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
catalogPath,
|
||||
document: { version: 1, encryptedCatalog },
|
||||
suffix,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
|
||||
});
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry.pipe(
|
||||
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) => migrationError("encode-catalog", catalogPath, cause)),
|
||||
);
|
||||
yield* writeCatalog(encoded).pipe(
|
||||
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
|
||||
);
|
||||
return Option.some(encoded);
|
||||
});
|
||||
|
||||
return DesktopConnectionCatalogStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, catalogPath);
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
const records = yield* savedEnvironments.getRegistry;
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear the desktop connection catalog.", {
|
||||
catalogPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.connectionCatalogStore.clear"),
|
||||
),
|
||||
});
|
||||
});
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
|
||||
yield* writeCatalog(encoded);
|
||||
return Option.some(encoded);
|
||||
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
|
||||
|
||||
export const layer = Layer.effect(DesktopConnectionCatalogStore, make);
|
||||
return DesktopConnectionCatalogStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, catalogPath).pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
|
||||
);
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear the desktop connection catalog.", {
|
||||
catalogPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.connectionCatalogStore.clear"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -11,7 +11,10 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import {
|
||||
type DesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
} from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
|
||||
|
||||
@@ -27,53 +30,55 @@ export interface MakeDesktopEnvironmentInput {
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopEnvironmentShape {
|
||||
readonly path: Path.Path;
|
||||
readonly dirname: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly processArch: string;
|
||||
readonly isPackaged: boolean;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
readonly appPath: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly homeDirectory: string;
|
||||
readonly appDataDirectory: string;
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: string;
|
||||
readonly desktopSettingsPath: string;
|
||||
readonly clientSettingsPath: string;
|
||||
readonly savedEnvironmentRegistryPath: string;
|
||||
readonly serverSettingsPath: string;
|
||||
readonly logDir: string;
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
readonly appUpdateYmlPath: string;
|
||||
readonly devServerUrl: Option.Option<URL>;
|
||||
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
|
||||
readonly configuredBackendPort: Option.Option<number>;
|
||||
readonly commitHashOverride: Option.Option<string>;
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
readonly branding: DesktopAppBranding;
|
||||
readonly displayName: string;
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopSettings;
|
||||
readonly runtimeInfo: DesktopRuntimeInfo;
|
||||
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
|
||||
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
|
||||
readonly developmentDockIconPath: string;
|
||||
}
|
||||
|
||||
export class DesktopEnvironment extends Context.Service<
|
||||
DesktopEnvironment,
|
||||
{
|
||||
readonly path: Path.Path;
|
||||
readonly dirname: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly processArch: string;
|
||||
readonly isPackaged: boolean;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
readonly appPath: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly homeDirectory: string;
|
||||
readonly appDataDirectory: string;
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: string;
|
||||
readonly desktopSettingsPath: string;
|
||||
readonly clientSettingsPath: string;
|
||||
readonly savedEnvironmentRegistryPath: string;
|
||||
readonly serverSettingsPath: string;
|
||||
readonly logDir: string;
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
readonly appUpdateYmlPath: string;
|
||||
readonly devServerUrl: Option.Option<URL>;
|
||||
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
|
||||
readonly configuredBackendPort: Option.Option<number>;
|
||||
readonly commitHashOverride: Option.Option<string>;
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
readonly branding: DesktopAppBranding;
|
||||
readonly displayName: string;
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
readonly runtimeInfo: DesktopRuntimeInfo;
|
||||
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
|
||||
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
|
||||
readonly developmentDockIconPath: string;
|
||||
}
|
||||
DesktopEnvironmentShape
|
||||
>()("@t3tools/desktop/app/DesktopEnvironment") {}
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
@@ -131,9 +136,9 @@ function resolveDesktopRuntimeInfo(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const make = Effect.fn("desktop.environment.make")(function* (
|
||||
const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
input: MakeDesktopEnvironmentInput,
|
||||
): Effect.fn.Return<DesktopEnvironment["Service"], Config.ConfigError, Path.Path> {
|
||||
): Effect.fn.Return<DesktopEnvironmentShape, Config.ConfigError, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const homeDirectory = input.homeDirectory;
|
||||
@@ -203,7 +208,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
|
||||
runtimeInfo: resolveDesktopRuntimeInfo({
|
||||
platform: input.platform,
|
||||
processArch: input.processArch,
|
||||
@@ -245,4 +250,4 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
});
|
||||
|
||||
export const layer = (input: MakeDesktopEnvironmentInput) =>
|
||||
Layer.effect(DesktopEnvironment, make(input));
|
||||
Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -8,36 +9,67 @@ import * as Scope from "effect/Scope";
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
export interface DesktopShutdownShape {
|
||||
readonly request: Effect.Effect<void>;
|
||||
readonly awaitRequest: Effect.Effect<void>;
|
||||
readonly markComplete: Effect.Effect<void>;
|
||||
readonly awaitComplete: Effect.Effect<void>;
|
||||
readonly isComplete: Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
|
||||
) {}
|
||||
|
||||
const makeShutdown = Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<void>();
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const completedRef = yield* Ref.make(false);
|
||||
|
||||
return DesktopShutdown.of({
|
||||
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
|
||||
awaitRequest: Deferred.await(requested),
|
||||
markComplete: Ref.set(completedRef, true).pipe(
|
||||
Effect.andThen(Deferred.succeed(completed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
awaitComplete: Deferred.await(completed),
|
||||
isComplete: Ref.get(completedRef),
|
||||
});
|
||||
});
|
||||
|
||||
export const layerShutdown = Layer.effect(DesktopShutdown, makeShutdown);
|
||||
|
||||
export type DesktopLifecycleRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
| DesktopShutdown
|
||||
| DesktopState.DesktopState
|
||||
| DesktopWindow.DesktopWindow
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronTheme.ElectronTheme;
|
||||
|
||||
export interface DesktopLifecycleShape {
|
||||
readonly relaunch: (
|
||||
reason: string,
|
||||
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
|
||||
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
|
||||
*/
|
||||
export class DesktopLifecycle extends Context.Service<
|
||||
DesktopLifecycle,
|
||||
{
|
||||
readonly relaunch: (
|
||||
reason: string,
|
||||
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
|
||||
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLifecycle") {}
|
||||
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle",
|
||||
) {}
|
||||
|
||||
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
|
||||
makeComponentLogger("desktop-lifecycle");
|
||||
DesktopObservability.makeComponentLogger("desktop-lifecycle");
|
||||
|
||||
function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
target: unknown,
|
||||
@@ -61,8 +93,8 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
}
|
||||
|
||||
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdown;
|
||||
yield* shutdown.request;
|
||||
yield* shutdown.awaitComplete;
|
||||
},
|
||||
@@ -122,82 +154,83 @@ function quitFromSignal(
|
||||
);
|
||||
}
|
||||
|
||||
export const make = DesktopLifecycle.of({
|
||||
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
yield* logLifecycleInfo("desktop relaunch requested", { reason });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(state.quitting, true);
|
||||
yield* requestDesktopShutdownAndWait();
|
||||
if (environment.isDevelopment) {
|
||||
yield* electronApp.exit(75);
|
||||
return;
|
||||
export const layer = Layer.succeed(
|
||||
DesktopLifecycle,
|
||||
DesktopLifecycle.of({
|
||||
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
yield* logLifecycleInfo("desktop relaunch requested", { reason });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(state.quitting, true);
|
||||
yield* requestDesktopShutdownAndWait();
|
||||
if (environment.isDevelopment) {
|
||||
yield* electronApp.exit(75);
|
||||
return;
|
||||
}
|
||||
yield* electronApp.relaunch({
|
||||
execPath: process.execPath,
|
||||
args: process.argv.slice(1),
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logLifecycleError("desktop relaunch failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
register: Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
|
||||
const runEffect = Effect.runPromiseWith(context);
|
||||
let quitAllowed = false;
|
||||
yield* electronTheme.onUpdated(() => {
|
||||
void runEffect(
|
||||
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("before-quit", (event: Electron.Event) => {
|
||||
handleBeforeQuit(
|
||||
event,
|
||||
runEffect,
|
||||
() => quitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("activate", () => {
|
||||
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
|
||||
});
|
||||
yield* electronApp.on("window-all-closed", () => {
|
||||
void runEffect(
|
||||
Effect.gen(function* () {
|
||||
const app = yield* ElectronApp.ElectronApp;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
|
||||
yield* app.quit;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
|
||||
);
|
||||
});
|
||||
|
||||
if (environment.platform !== "win32") {
|
||||
yield* addScopedListener(process, "SIGINT", () => {
|
||||
quitFromSignal("SIGINT", runEffect);
|
||||
});
|
||||
yield* addScopedListener(process, "SIGTERM", () => {
|
||||
quitFromSignal("SIGTERM", runEffect);
|
||||
});
|
||||
}
|
||||
yield* electronApp.relaunch({
|
||||
execPath: process.execPath,
|
||||
args: process.argv.slice(1),
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logLifecycleError("desktop relaunch failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
|
||||
}),
|
||||
register: Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
|
||||
const runEffect = Effect.runPromiseWith(context);
|
||||
let quitAllowed = false;
|
||||
yield* electronTheme.onUpdated(() => {
|
||||
void runEffect(
|
||||
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("before-quit", (event: Electron.Event) => {
|
||||
handleBeforeQuit(
|
||||
event,
|
||||
runEffect,
|
||||
() => quitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("activate", () => {
|
||||
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
|
||||
});
|
||||
yield* electronApp.on("window-all-closed", () => {
|
||||
void runEffect(
|
||||
Effect.gen(function* () {
|
||||
const app = yield* ElectronApp.ElectronApp;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
|
||||
yield* app.quit;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
|
||||
);
|
||||
});
|
||||
|
||||
if (environment.platform !== "win32") {
|
||||
yield* addScopedListener(process, "SIGINT", () => {
|
||||
quitFromSignal("SIGINT", runEffect);
|
||||
});
|
||||
yield* addScopedListener(process, "SIGTERM", () => {
|
||||
quitFromSignal("SIGTERM", runEffect);
|
||||
});
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(DesktopLifecycle, make);
|
||||
);
|
||||
@@ -1,20 +1,52 @@
|
||||
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
|
||||
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
DesktopBackendOutputLogShape
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
export type DesktopLogAnnotations = Record<string, unknown>;
|
||||
|
||||
@@ -50,7 +82,165 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
|
||||
};
|
||||
}
|
||||
|
||||
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
|
||||
class DesktopLogFileWriterConfigurationError extends Data.TaggedError(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
)<{
|
||||
readonly option: "maxBytes" | "maxFiles";
|
||||
readonly value: number;
|
||||
}> {
|
||||
override get message() {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
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 }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
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).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
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> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const readPersistedOtlpTracesUrl: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
|
||||
@@ -70,6 +260,90 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
|
||||
return yield* readPersistedOtlpTracesUrl;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
const backendOutputLogLayer = Layer.effect(
|
||||
DesktopBackendOutputLog,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
return Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn(
|
||||
"desktop.observability.backendOutput.writeSessionBoundary",
|
||||
)(function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
}),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const desktopLoggerLayer = Layer.mergeAll(
|
||||
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
|
||||
Layer.succeed(References.MinimumLogLevel, "Info"),
|
||||
@@ -82,8 +356,8 @@ const tracerLayer = Layer.unwrap(
|
||||
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
const sink = yield* makeTraceSink({
|
||||
filePath: tracePath,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
});
|
||||
const delegate = Option.isNone(otlpTracesUrl)
|
||||
@@ -101,8 +375,8 @@ const tracerLayer = Layer.unwrap(
|
||||
});
|
||||
const tracer = yield* makeLocalFileTracer({
|
||||
filePath: tracePath,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
sink,
|
||||
...(delegate ? { delegate } : {}),
|
||||
@@ -113,7 +387,7 @@ const tracerLayer = Layer.unwrap(
|
||||
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
|
||||
|
||||
export const layer = Layer.mergeAll(
|
||||
DesktopBackendOutputLogModule.layer,
|
||||
backendOutputLogLayer,
|
||||
desktopLoggerLayer,
|
||||
tracerLayer,
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
export class DesktopShutdown extends Context.Service<
|
||||
DesktopShutdown,
|
||||
{
|
||||
readonly request: Effect.Effect<void>;
|
||||
readonly awaitRequest: Effect.Effect<void>;
|
||||
readonly markComplete: Effect.Effect<void>;
|
||||
readonly awaitComplete: Effect.Effect<void>;
|
||||
readonly isComplete: Effect.Effect<boolean>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopShutdown") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<void>();
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const completedRef = yield* Ref.make(false);
|
||||
|
||||
return DesktopShutdown.of({
|
||||
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
|
||||
awaitRequest: Deferred.await(requested),
|
||||
markComplete: Ref.set(completedRef, true).pipe(
|
||||
Effect.andThen(Deferred.succeed(completed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
awaitComplete: Deferred.await(completed),
|
||||
isComplete: Ref.get(completedRef),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopShutdown, make);
|
||||
@@ -3,17 +3,19 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
export class DesktopState extends Context.Service<
|
||||
export interface DesktopStateShape {
|
||||
readonly backendReady: Ref.Ref<boolean>;
|
||||
readonly quitting: Ref.Ref<boolean>;
|
||||
}
|
||||
|
||||
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
|
||||
"@t3tools/desktop/app/DesktopState",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopState,
|
||||
{
|
||||
readonly backendReady: Ref.Ref<boolean>;
|
||||
readonly quitting: Ref.Ref<boolean>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopState") {}
|
||||
|
||||
const make = Effect.all({
|
||||
backendReady: Ref.make(false),
|
||||
quitting: Ref.make(false),
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopState, make);
|
||||
Effect.all({
|
||||
backendReady: Ref.make(false),
|
||||
quitting: Ref.make(false),
|
||||
}),
|
||||
);
|
||||
@@ -34,7 +34,7 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.succeed([]),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
} satisfies DesktopServerExposure.DesktopServerExposureShape);
|
||||
|
||||
function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
|
||||
@@ -14,14 +14,16 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
|
||||
export interface DesktopBackendConfigurationShape {
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
{
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
}
|
||||
DesktopBackendConfigurationShape
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
interface BackendObservabilitySettings {
|
||||
@@ -54,7 +56,11 @@ const { logWarning: logBackendConfigurationWarning } = DesktopObservability.make
|
||||
"desktop-backend-configuration",
|
||||
);
|
||||
|
||||
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
const readPersistedBackendObservabilitySettings: Effect.Effect<
|
||||
BackendObservabilitySettings,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const exists = yield* fileSystem
|
||||
@@ -124,39 +130,40 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
},
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value;
|
||||
}
|
||||
export const layer = Layer.effect(
|
||||
DesktopBackendConfiguration,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value;
|
||||
}
|
||||
|
||||
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
|
||||
yield* Ref.set(tokenRef, Option.some(token));
|
||||
return token;
|
||||
});
|
||||
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
|
||||
yield* Ref.set(tokenRef, Option.some(token));
|
||||
return token;
|
||||
});
|
||||
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolve: Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendConfiguration, make);
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolve: Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -104,9 +104,9 @@ function decodeBootstrap(raw: string) {
|
||||
function makeManagerLayer(input: {
|
||||
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
|
||||
readonly desktopState?: DesktopState.DesktopState["Service"];
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
|
||||
readonly desktopState?: DesktopState.DesktopStateShape;
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
@@ -127,7 +127,7 @@ function makeManagerLayer(input: {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
...input.backendOutputLog,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected createMain"),
|
||||
ensureMain: Effect.die("unexpected ensureMain"),
|
||||
@@ -138,7 +138,7 @@ function makeManagerLayer(input: {
|
||||
dispatchMenuAction: () => Effect.void,
|
||||
syncAppearance: Effect.void,
|
||||
...input.desktopWindow,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
} satisfies DesktopWindow.DesktopWindowShape),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -15,9 +16,8 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
@@ -59,38 +59,29 @@ interface BackendProcessExit {
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
url: Schema.URL,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
|
||||
readonly url: URL;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
class BackendProcessBootstrapEncodeError extends Data.TaggedError(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
|
||||
)<{
|
||||
readonly cause: Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend process: ${this.detail}`;
|
||||
class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
|
||||
readonly cause: PlatformError.PlatformError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to spawn desktop backend process: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,14 +106,16 @@ export interface DesktopBackendSnapshot {
|
||||
readonly restartScheduled: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopBackendManagerShape {
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
}
|
||||
|
||||
export class DesktopBackendManager extends Context.Service<
|
||||
DesktopBackendManager,
|
||||
{
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
}
|
||||
DesktopBackendManagerShape
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
@@ -237,13 +230,7 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const command = ChildProcess.make(
|
||||
@@ -269,15 +256,9 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
@@ -296,7 +277,7 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
@@ -622,4 +603,4 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendManager, make);
|
||||
export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());
|
||||
@@ -3,8 +3,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
@@ -1,88 +1,77 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
|
||||
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
|
||||
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Local backend is not configured.";
|
||||
}
|
||||
export interface DesktopLocalEnvironmentAuthShape {
|
||||
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
|
||||
}
|
||||
|
||||
export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
|
||||
"DesktopLocalEnvironmentAuthSessionBootstrapError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to create the local desktop bearer session.";
|
||||
}
|
||||
}
|
||||
|
||||
export const DesktopLocalEnvironmentAuthError = Schema.Union([
|
||||
DesktopLocalEnvironmentAuthBackendNotConfiguredError,
|
||||
DesktopLocalEnvironmentAuthSessionBootstrapError,
|
||||
]);
|
||||
export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;
|
||||
export class DesktopLocalEnvironmentAuthError extends Data.TaggedError(
|
||||
"DesktopLocalEnvironmentAuthError",
|
||||
)<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
DesktopLocalEnvironmentAuth,
|
||||
{
|
||||
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
|
||||
}
|
||||
DesktopLocalEnvironmentAuthShape
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
export const layer = Layer.effect(
|
||||
DesktopLocalEnvironmentAuth,
|
||||
Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const getBearerToken = mutex
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
const getBearerToken = mutex
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const config = configOption.value;
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLocalEnvironmentAuthSessionBootstrapError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(tokenRef, Option.some(session.access_token));
|
||||
return session.access_token;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthError({
|
||||
message: "Local backend is not configured.",
|
||||
});
|
||||
}
|
||||
const config = configOption.value;
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLocalEnvironmentAuthError({
|
||||
message: "Failed to create the local desktop bearer session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(tokenRef, Option.some(session.access_token));
|
||||
return session.access_token;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
|
||||
|
||||
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);
|
||||
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
|
||||
}),
|
||||
);
|
||||
@@ -1,33 +0,0 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export interface DesktopNetworkInterfaceInfo {
|
||||
readonly address: string;
|
||||
readonly family: string | number;
|
||||
readonly internal: boolean;
|
||||
readonly netmask?: string;
|
||||
readonly mac?: string;
|
||||
readonly cidr?: string | null;
|
||||
readonly scopeid?: number;
|
||||
}
|
||||
|
||||
export type NetworkInterfaces = Readonly<
|
||||
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
|
||||
>;
|
||||
|
||||
export class DesktopNetworkInterfaces extends Context.Service<
|
||||
DesktopNetworkInterfaces,
|
||||
{
|
||||
readonly read: Effect.Effect<NetworkInterfaces>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
|
||||
|
||||
export const make = (): DesktopNetworkInterfaces["Service"] =>
|
||||
DesktopNetworkInterfaces.of({
|
||||
read: Effect.sync(() => NodeOS.networkInterfaces()),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(DesktopNetworkInterfaces, make());
|
||||
@@ -7,18 +7,21 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import {
|
||||
DesktopEnvironment,
|
||||
layer as makeDesktopEnvironmentLayer,
|
||||
} from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {};
|
||||
const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
const emptyNetworkInterfaces: DesktopNetworkInterfaces = {};
|
||||
const lanNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.20",
|
||||
@@ -28,7 +31,7 @@ const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
],
|
||||
};
|
||||
|
||||
const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
tailscale0: [
|
||||
{
|
||||
address: "100.90.1.2",
|
||||
@@ -69,7 +72,7 @@ function dieOnSpawnLayer() {
|
||||
}
|
||||
|
||||
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
|
||||
return DesktopEnvironment.layer({
|
||||
return makeDesktopEnvironmentLayer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
@@ -88,13 +91,13 @@ function makeEnvironmentLayer(baseDir: string, env: Record<string, string | unde
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly baseDir: string;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
}) {
|
||||
const env = { T3CODE_HOME: input.baseDir, ...input.env };
|
||||
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
|
||||
const networkLayer = Layer.succeed(DesktopNetworkInterfaces.DesktopNetworkInterfaces, {
|
||||
const networkLayer = Layer.succeed(DesktopServerExposure.DesktopNetworkInterfacesService, {
|
||||
read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
|
||||
});
|
||||
|
||||
@@ -110,12 +113,12 @@ function makeLayer(input: {
|
||||
}
|
||||
|
||||
const withHarness = <A, E, R>(
|
||||
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
|
||||
networkInterfaces: DesktopNetworkInterfaces,
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
| R
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopEnvironment
|
||||
| FileSystem.FileSystem
|
||||
| DesktopServerExposure.DesktopServerExposure
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
@@ -8,27 +10,41 @@ import type {
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
} from "@t3tools/contracts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
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 Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
|
||||
|
||||
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
|
||||
export interface DesktopNetworkInterfaceInfo {
|
||||
readonly address: string;
|
||||
readonly family: string | number;
|
||||
readonly internal: boolean;
|
||||
readonly netmask?: string;
|
||||
readonly mac?: string;
|
||||
readonly cidr?: string | null;
|
||||
readonly scopeid?: number;
|
||||
}
|
||||
|
||||
export type DesktopNetworkInterfaces = Readonly<
|
||||
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
|
||||
>;
|
||||
|
||||
interface ResolvedDesktopServerExposure {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly bindHost: string;
|
||||
@@ -75,7 +91,7 @@ const isHttpsEndpointUrl = (value: string): boolean => {
|
||||
};
|
||||
|
||||
const resolveLanAdvertisedHost = (
|
||||
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
|
||||
networkInterfaces: DesktopNetworkInterfaces,
|
||||
explicitHost: string | undefined,
|
||||
): string | null => {
|
||||
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
|
||||
@@ -100,7 +116,7 @@ const resolveLanAdvertisedHost = (
|
||||
const resolveDesktopServerExposure = (input: {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly advertisedHostOverride?: string;
|
||||
}): ResolvedDesktopServerExposure => {
|
||||
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
||||
@@ -202,25 +218,25 @@ const resolveDesktopCoreAdvertisedEndpoints = (
|
||||
return endpoints;
|
||||
};
|
||||
|
||||
export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErrorClass<DesktopServerExposureNoNetworkAddressError>()(
|
||||
type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
|
||||
|
||||
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
|
||||
"DesktopServerExposureNoNetworkAddressError",
|
||||
{
|
||||
port: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly port: number;
|
||||
}> {
|
||||
override get message() {
|
||||
return `No reachable network address is available for desktop network access on port ${this.port}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopServerExposurePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposurePersistenceError>()(
|
||||
export class DesktopServerExposurePersistenceError extends Data.TaggedError(
|
||||
"DesktopServerExposurePersistenceError",
|
||||
{
|
||||
operation: Schema.Literals(["server-exposure-mode", "tailscale-serve"]),
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly operation: DesktopServerExposurePersistenceOperation;
|
||||
readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to persist desktop ${this.operation} settings.`;
|
||||
}
|
||||
}
|
||||
@@ -244,25 +260,36 @@ export interface DesktopServerExposureChange {
|
||||
readonly requiresRelaunch: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopServerExposureShape {
|
||||
readonly getState: Effect.Effect<DesktopServerExposureState>;
|
||||
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
|
||||
readonly configureFromSettings: (input: {
|
||||
readonly port: number;
|
||||
}) => Effect.Effect<DesktopServerExposureState>;
|
||||
readonly setMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
|
||||
export class DesktopServerExposure extends Context.Service<
|
||||
DesktopServerExposure,
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopServerExposureState>;
|
||||
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
|
||||
readonly configureFromSettings: (input: {
|
||||
readonly port: number;
|
||||
}) => Effect.Effect<DesktopServerExposureState>;
|
||||
readonly setMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
DesktopServerExposureShape
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
|
||||
|
||||
export interface DesktopNetworkInterfacesServiceShape {
|
||||
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
|
||||
}
|
||||
|
||||
export class DesktopNetworkInterfacesService extends Context.Service<
|
||||
DesktopNetworkInterfacesService,
|
||||
DesktopNetworkInterfacesServiceShape
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
|
||||
|
||||
interface RuntimeState {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
@@ -284,10 +311,10 @@ interface ResolvedRuntimeState {
|
||||
|
||||
const initialRuntimeState = (): RuntimeState =>
|
||||
runtimeStateFromResolvedExposure({
|
||||
requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
settings: DEFAULT_DESKTOP_SETTINGS,
|
||||
exposure: resolveDesktopServerExposure({
|
||||
mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
port: 0,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
@@ -321,7 +348,7 @@ const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure
|
||||
|
||||
function runtimeStateFromResolvedExposure(input: {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly settings: DesktopAppSettings.DesktopSettings;
|
||||
readonly settings: DesktopSettings;
|
||||
readonly exposure: ResolvedDesktopServerExposure;
|
||||
readonly port: number;
|
||||
}): RuntimeState {
|
||||
@@ -342,9 +369,9 @@ function runtimeStateFromResolvedExposure(input: {
|
||||
|
||||
function resolveRuntimeState(input: {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly settings: DesktopAppSettings.DesktopSettings;
|
||||
readonly settings: DesktopSettings;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly advertisedHostOverride: Option.Option<string>;
|
||||
}): ResolvedRuntimeState {
|
||||
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
|
||||
@@ -381,12 +408,12 @@ const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): bo
|
||||
previous.bindHost !== next.bindHost ||
|
||||
previous.localHttpUrl !== next.localHttpUrl;
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
const networkInterfaces = yield* DesktopNetworkInterfacesService;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
|
||||
const stateRef = yield* Ref.make(initialRuntimeState());
|
||||
|
||||
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
|
||||
@@ -537,3 +564,10 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopServerExposure, make);
|
||||
|
||||
export const networkInterfacesLayer = Layer.succeed(
|
||||
DesktopNetworkInterfacesService,
|
||||
DesktopNetworkInterfacesService.of({
|
||||
read: Effect.sync(() => NodeOS.networkInterfaces()),
|
||||
}),
|
||||
);
|
||||
@@ -9,10 +9,10 @@ import {
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts";
|
||||
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
|
||||
|
||||
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
|
||||
|
||||
@@ -25,7 +25,7 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
|
||||
function resolveTailscaleIpAdvertisedEndpoints(input: {
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: NetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
}): readonly AdvertisedEndpoint[] {
|
||||
const seen = new Set<string>();
|
||||
const endpoints: AdvertisedEndpoint[] = [];
|
||||
@@ -103,7 +103,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
readonly port: number;
|
||||
readonly serveEnabled?: boolean;
|
||||
readonly servePort?: number;
|
||||
readonly networkInterfaces: NetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly statusJson?: string | null;
|
||||
readonly readMagicDnsName?: Effect.Effect<
|
||||
string | null,
|
||||
|
||||
@@ -13,40 +13,41 @@ export interface ElectronAppMetadata {
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<
|
||||
ElectronApp,
|
||||
{
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata>;
|
||||
readonly name: Effect.Effect<string>;
|
||||
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>;
|
||||
readonly setPath: (
|
||||
name: Parameters<Electron.App["setPath"]>[0],
|
||||
path: string,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setName: (name: string) => Effect.Effect<void>;
|
||||
readonly setAboutPanelOptions: (
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
path?: string,
|
||||
args?: readonly string[],
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
|
||||
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
|
||||
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronApp") {}
|
||||
export interface ElectronAppShape {
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata>;
|
||||
readonly name: Effect.Effect<string>;
|
||||
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>;
|
||||
readonly setPath: (
|
||||
name: Parameters<Electron.App["setPath"]>[0],
|
||||
path: string,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setName: (name: string) => Effect.Effect<void>;
|
||||
readonly setAboutPanelOptions: (
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
path?: string,
|
||||
args?: readonly string[],
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
|
||||
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
|
||||
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
|
||||
"@t3tools/desktop/electron/ElectronApp",
|
||||
) {}
|
||||
|
||||
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
@@ -62,7 +63,7 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
export const make = ElectronApp.of({
|
||||
const make = ElectronApp.of({
|
||||
metadata: Effect.sync(() => ({
|
||||
appVersion: Electron.app.getVersion(),
|
||||
appPath: Electron.app.getAppPath(),
|
||||
|
||||
@@ -17,21 +17,22 @@ export interface ElectronDialogConfirmInput {
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export class ElectronDialog extends Context.Service<
|
||||
ElectronDialog,
|
||||
{
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue>;
|
||||
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronDialog") {}
|
||||
export interface ElectronDialogShape {
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue>;
|
||||
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export const make = ElectronDialog.of({
|
||||
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
|
||||
"@t3tools/desktop/electron/ElectronDialog",
|
||||
) {}
|
||||
|
||||
const make = ElectronDialog.of({
|
||||
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
|
||||
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
|
||||
onNone: () => ({
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
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 Option from "effect/Option";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export interface ElectronMenuPosition {
|
||||
readonly x: number;
|
||||
@@ -23,18 +23,19 @@ export interface ElectronMenuTemplateInput {
|
||||
readonly template: readonly Electron.MenuItemConstructorOptions[];
|
||||
}
|
||||
|
||||
export class ElectronMenu extends Context.Service<
|
||||
ElectronMenu,
|
||||
{
|
||||
readonly setApplicationMenu: (
|
||||
template: readonly Electron.MenuItemConstructorOptions[],
|
||||
) => Effect.Effect<void>;
|
||||
readonly showContextMenu: (
|
||||
input: ElectronMenuContextInput,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronMenu") {}
|
||||
export interface ElectronMenuShape {
|
||||
readonly setApplicationMenu: (
|
||||
template: readonly Electron.MenuItemConstructorOptions[],
|
||||
) => Effect.Effect<void>;
|
||||
readonly showContextMenu: (
|
||||
input: ElectronMenuContextInput,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
|
||||
"@t3tools/desktop/electron/ElectronMenu",
|
||||
) {}
|
||||
|
||||
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
|
||||
const normalizedItems: ContextMenuItem[] = [];
|
||||
@@ -79,113 +80,114 @@ const normalizePosition = (
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
export const layer = Layer.effect(
|
||||
ElectronMenu,
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
icon.setTemplateImage(true);
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
icon.setTemplateImage(true);
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
return destructiveMenuIconCache;
|
||||
};
|
||||
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
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);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
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);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
});
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
export const layer = Layer.effect(ElectronMenu, make);
|
||||
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,8 +1,8 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
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 * as Electron from "electron";
|
||||
@@ -23,14 +23,13 @@ export function getDesktopUrl(isDevelopment: boolean): string {
|
||||
return `${getDesktopOrigin(isDevelopment)}/`;
|
||||
}
|
||||
|
||||
export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<ElectronProtocolRegistrationError>()(
|
||||
export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
"ElectronProtocolRegistrationError",
|
||||
{
|
||||
scheme: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly scheme: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to register ${this.scheme}: protocol.`;
|
||||
}
|
||||
}
|
||||
@@ -42,14 +41,15 @@ export interface DesktopProtocolRegistrationInput {
|
||||
readonly clerkFrontendApiHostname: string | undefined;
|
||||
}
|
||||
|
||||
export class ElectronProtocol extends Context.Service<
|
||||
ElectronProtocol,
|
||||
{
|
||||
readonly registerDesktopProtocol: (
|
||||
input: DesktopProtocolRegistrationInput,
|
||||
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronProtocol") {}
|
||||
export interface ElectronProtocolShape {
|
||||
readonly registerDesktopProtocol: (
|
||||
input: DesktopProtocolRegistrationInput,
|
||||
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
|
||||
"@t3tools/desktop/electron/ElectronProtocol",
|
||||
) {}
|
||||
|
||||
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
|
||||
const clerkOrigin = input.clerkFrontendApiHostname
|
||||
@@ -114,7 +114,7 @@ async function proxyRequest(
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
|
||||
|
||||
@@ -1,69 +1,56 @@
|
||||
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 Electron from "electron";
|
||||
|
||||
const electronSafeStorageErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
|
||||
export class ElectronSafeStorageAvailabilityError extends Schema.TaggedErrorClass<ElectronSafeStorageAvailabilityError>()(
|
||||
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
|
||||
"ElectronSafeStorageAvailabilityError",
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron safe storage failed to check encryption availability.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronSafeStorageEncryptError extends Schema.TaggedErrorClass<ElectronSafeStorageEncryptError>()(
|
||||
export class ElectronSafeStorageEncryptError extends Data.TaggedError(
|
||||
"ElectronSafeStorageEncryptError",
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron safe storage failed to encrypt a string.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronSafeStorageDecryptError extends Schema.TaggedErrorClass<ElectronSafeStorageDecryptError>()(
|
||||
export class ElectronSafeStorageDecryptError extends Data.TaggedError(
|
||||
"ElectronSafeStorageDecryptError",
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron safe storage failed to decrypt a string.";
|
||||
}
|
||||
}
|
||||
|
||||
export const ElectronSafeStorageError = Schema.Union([
|
||||
ElectronSafeStorageAvailabilityError,
|
||||
ElectronSafeStorageEncryptError,
|
||||
ElectronSafeStorageDecryptError,
|
||||
]);
|
||||
export type ElectronSafeStorageError = typeof ElectronSafeStorageError.Type;
|
||||
export const isElectronSafeStorageError = Schema.is(ElectronSafeStorageError);
|
||||
export interface ElectronSafeStorageShape {
|
||||
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
|
||||
readonly encryptString: (
|
||||
value: string,
|
||||
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
}
|
||||
|
||||
export class ElectronSafeStorage extends Context.Service<
|
||||
ElectronSafeStorage,
|
||||
{
|
||||
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
|
||||
readonly encryptString: (
|
||||
value: string,
|
||||
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
}
|
||||
ElectronSafeStorageShape
|
||||
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
|
||||
|
||||
export const make = ElectronSafeStorage.of({
|
||||
const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
|
||||
@@ -20,15 +20,16 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronShell extends Context.Service<
|
||||
ElectronShell,
|
||||
{
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronShell") {}
|
||||
export interface ElectronShellShape {
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export const make = ElectronShell.of({
|
||||
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
|
||||
"@t3tools/desktop/electron/ElectronShell",
|
||||
) {}
|
||||
|
||||
const make = ElectronShell.of({
|
||||
openExternal: (rawUrl) =>
|
||||
Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
onNone: () => Effect.succeed(false),
|
||||
|
||||
@@ -6,16 +6,17 @@ import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export class ElectronTheme extends Context.Service<
|
||||
ElectronTheme,
|
||||
{
|
||||
readonly shouldUseDarkColors: Effect.Effect<boolean>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
|
||||
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronTheme") {}
|
||||
export interface ElectronThemeShape {
|
||||
readonly shouldUseDarkColors: Effect.Effect<boolean>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
|
||||
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export const make = ElectronTheme.of({
|
||||
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
|
||||
"@t3tools/desktop/electron/ElectronTheme",
|
||||
) {}
|
||||
|
||||
const make = ElectronTheme.of({
|
||||
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
|
||||
setSource: (theme) =>
|
||||
Effect.suspend(() => {
|
||||
|
||||
@@ -73,7 +73,6 @@ describe("ElectronUpdater", () => {
|
||||
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)),
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
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 { autoUpdater } from "electron-updater";
|
||||
@@ -10,76 +10,67 @@ type AutoUpdater = typeof autoUpdater;
|
||||
|
||||
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
|
||||
|
||||
const electronUpdaterErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
|
||||
export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
|
||||
"ElectronUpdaterCheckForUpdatesError",
|
||||
{
|
||||
...electronUpdaterErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to check for updates.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
|
||||
export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
|
||||
"ElectronUpdaterDownloadUpdateError",
|
||||
{
|
||||
...electronUpdaterErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to download the update.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
|
||||
export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
|
||||
"ElectronUpdaterQuitAndInstallError",
|
||||
{
|
||||
...electronUpdaterErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to quit and install the update.";
|
||||
}
|
||||
}
|
||||
|
||||
export const ElectronUpdaterError = Schema.Union([
|
||||
ElectronUpdaterCheckForUpdatesError,
|
||||
ElectronUpdaterDownloadUpdateError,
|
||||
ElectronUpdaterQuitAndInstallError,
|
||||
]);
|
||||
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
|
||||
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
|
||||
export type ElectronUpdaterError =
|
||||
| ElectronUpdaterCheckForUpdatesError
|
||||
| ElectronUpdaterDownloadUpdateError
|
||||
| ElectronUpdaterQuitAndInstallError;
|
||||
|
||||
export class ElectronUpdater extends Context.Service<
|
||||
ElectronUpdater,
|
||||
{
|
||||
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
|
||||
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setChannel: (channel: string) => Effect.Effect<void>;
|
||||
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
|
||||
readonly allowDowngrade: Effect.Effect<boolean>;
|
||||
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
|
||||
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
|
||||
readonly quitAndInstall: (options: {
|
||||
readonly isSilent: boolean;
|
||||
readonly isForceRunAfter: boolean;
|
||||
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronUpdater") {}
|
||||
export interface ElectronUpdaterShape {
|
||||
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
|
||||
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setChannel: (channel: string) => Effect.Effect<void>;
|
||||
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
|
||||
readonly allowDowngrade: Effect.Effect<boolean>;
|
||||
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
|
||||
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
|
||||
readonly quitAndInstall: (options: {
|
||||
readonly isSilent: boolean;
|
||||
readonly isForceRunAfter: boolean;
|
||||
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export const make = ElectronUpdater.of({
|
||||
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
|
||||
"@t3tools/desktop/electron/ElectronUpdater",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.succeed(ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.setFeedURL(options);
|
||||
@@ -145,6 +136,4 @@ export const make = ElectronUpdater.of({
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
},
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronUpdater, make);
|
||||
} satisfies ElectronUpdaterShape);
|
||||
@@ -1,45 +1,43 @@
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
|
||||
"ElectronWindowCreateError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to create Electron BrowserWindow.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronWindow extends Context.Service<
|
||||
ElectronWindow,
|
||||
{
|
||||
readonly create: (
|
||||
options: Electron.BrowserWindowConstructorOptions,
|
||||
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
|
||||
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
|
||||
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
|
||||
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
|
||||
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
|
||||
readonly destroyAll: Effect.Effect<void>;
|
||||
readonly syncAllAppearance: <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) => Effect.Effect<void, E, R>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronWindow") {}
|
||||
export interface ElectronWindowShape {
|
||||
readonly create: (
|
||||
options: Electron.BrowserWindowConstructorOptions,
|
||||
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
|
||||
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
|
||||
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
|
||||
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
|
||||
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
|
||||
readonly destroyAll: Effect.Effect<void>;
|
||||
readonly syncAllAppearance: <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) => Effect.Effect<void, E, R>;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
|
||||
"@t3tools/desktop/electron/ElectronWindow",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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";
|
||||
|
||||
@@ -34,19 +33,20 @@ export interface DesktopSyncIpcMethod<E, R> {
|
||||
readonly handler: () => Effect.Effect<unknown, E, R>;
|
||||
}
|
||||
|
||||
export class DesktopIpc extends Context.Service<
|
||||
DesktopIpc,
|
||||
{
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/ipc/DesktopIpc") {}
|
||||
export interface DesktopIpcShape {
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
}
|
||||
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
|
||||
"@t3tools/desktop/ipc/DesktopIpc",
|
||||
) {}
|
||||
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
DesktopIpc.of({
|
||||
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
|
||||
channel,
|
||||
@@ -97,8 +97,6 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
}),
|
||||
});
|
||||
|
||||
export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
|
||||
|
||||
/**
|
||||
* Convenience helpers for creating IPC methods
|
||||
*/
|
||||
|
||||
@@ -5,9 +5,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
export const getClientSettings = DesktopIpc.makeIpcMethod({
|
||||
export const getClientSettings = makeIpcMethod({
|
||||
channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(ClientSettingsSchema),
|
||||
@@ -17,7 +17,7 @@ export const getClientSettings = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setClientSettings = DesktopIpc.makeIpcMethod({
|
||||
export const setClientSettings = makeIpcMethod({
|
||||
channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
|
||||
payload: ClientSettingsSchema,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -4,9 +4,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
export const getConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
@@ -16,7 +16,7 @@ export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
export const setConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
@@ -26,7 +26,7 @@ export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
export const clearConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -22,12 +22,12 @@ import {
|
||||
import { BrowserWindow } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as NodeURL from "node:url";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
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";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
@@ -52,7 +52,7 @@ export const installPreviewEventForwarding = Effect.fn(
|
||||
});
|
||||
});
|
||||
|
||||
export const createTab = DesktopIpc.makeIpcMethod({
|
||||
export const createTab = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -62,7 +62,7 @@ export const createTab = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const closeTab = DesktopIpc.makeIpcMethod({
|
||||
export const closeTab = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -72,7 +72,7 @@ export const closeTab = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const registerWebview = DesktopIpc.makeIpcMethod({
|
||||
export const registerWebview = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
|
||||
payload: DesktopPreviewRegisterWebviewInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -82,7 +82,7 @@ export const registerWebview = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const navigate = DesktopIpc.makeIpcMethod({
|
||||
export const navigate = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
|
||||
payload: DesktopPreviewNavigateInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -96,11 +96,11 @@ const tabMethod = (
|
||||
channel: string,
|
||||
name: string,
|
||||
invoke: (
|
||||
manager: PreviewManager.PreviewManager["Service"],
|
||||
manager: PreviewManager.PreviewManagerShape,
|
||||
tabId: string,
|
||||
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
|
||||
) =>
|
||||
DesktopIpc.makeIpcMethod({
|
||||
makeIpcMethod({
|
||||
channel,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -166,7 +166,7 @@ export const stopRecording = tabMethod(
|
||||
(manager, tabId) => manager.stopRecording(tabId),
|
||||
);
|
||||
|
||||
export const clearCookies = DesktopIpc.makeIpcMethod({
|
||||
export const clearCookies = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
@@ -176,7 +176,7 @@ export const clearCookies = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCache = DesktopIpc.makeIpcMethod({
|
||||
export const clearCache = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
@@ -186,7 +186,7 @@ export const clearCache = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getPreviewConfig = DesktopIpc.makeIpcMethod({
|
||||
export const getPreviewConfig = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
|
||||
payload: DesktopPreviewConfigInputSchema,
|
||||
result: DesktopPreviewWebviewConfigSchema,
|
||||
@@ -196,12 +196,12 @@ export const getPreviewConfig = DesktopIpc.makeIpcMethod({
|
||||
return {
|
||||
partition: yield* manager.getBrowserPartition(environmentId),
|
||||
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
|
||||
preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
|
||||
preloadUrl: pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
export const setAnnotationTheme = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
|
||||
payload: DesktopPreviewAnnotationThemeInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -211,7 +211,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
export const pickElement = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
@@ -221,7 +221,7 @@ export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const captureScreenshot = DesktopIpc.makeIpcMethod({
|
||||
export const captureScreenshot = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: DesktopPreviewScreenshotArtifactSchema,
|
||||
@@ -231,7 +231,7 @@ export const captureScreenshot = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const revealArtifact = DesktopIpc.makeIpcMethod({
|
||||
export const revealArtifact = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -241,7 +241,7 @@ export const revealArtifact = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
|
||||
export const copyArtifactToClipboard = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -251,7 +251,7 @@ export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationStatus = DesktopIpc.makeIpcMethod({
|
||||
export const automationStatus = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationStatus,
|
||||
@@ -261,7 +261,7 @@ export const automationStatus = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationSnapshot = DesktopIpc.makeIpcMethod({
|
||||
export const automationSnapshot = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationSnapshot,
|
||||
@@ -271,7 +271,7 @@ export const automationSnapshot = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationClick = DesktopIpc.makeIpcMethod({
|
||||
export const automationClick = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
|
||||
payload: DesktopPreviewAutomationClickInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -281,7 +281,7 @@ export const automationClick = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationType = DesktopIpc.makeIpcMethod({
|
||||
export const automationType = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationTypeInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -291,7 +291,7 @@ export const automationType = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationPress = DesktopIpc.makeIpcMethod({
|
||||
export const automationPress = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
|
||||
payload: DesktopPreviewAutomationPressInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -301,7 +301,7 @@ export const automationPress = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationScroll = DesktopIpc.makeIpcMethod({
|
||||
export const automationScroll = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
|
||||
payload: DesktopPreviewAutomationScrollInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -311,7 +311,7 @@ export const automationScroll = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationEvaluate = DesktopIpc.makeIpcMethod({
|
||||
export const automationEvaluate = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationEvaluateInputSchema,
|
||||
result: Schema.Unknown,
|
||||
@@ -321,7 +321,7 @@ export const automationEvaluate = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationWaitFor = DesktopIpc.makeIpcMethod({
|
||||
export const automationWaitFor = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
|
||||
payload: DesktopPreviewAutomationWaitForInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -331,7 +331,7 @@ export const automationWaitFor = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const saveRecording = DesktopIpc.makeIpcMethod({
|
||||
export const saveRecording = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
|
||||
payload: DesktopPreviewRecordingSaveInputSchema,
|
||||
result: DesktopPreviewRecordingArtifactSchema,
|
||||
|
||||
@@ -9,14 +9,14 @@ import * as Schema from "effect/Schema";
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const SetTailscaleServeEnabledInput = Schema.Struct({
|
||||
enabled: Schema.Boolean,
|
||||
port: Schema.optionalKey(Schema.Number),
|
||||
});
|
||||
|
||||
export const getServerExposureState = DesktopIpc.makeIpcMethod({
|
||||
export const getServerExposureState = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -26,7 +26,7 @@ export const getServerExposureState = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setServerExposureMode = DesktopIpc.makeIpcMethod({
|
||||
export const setServerExposureMode = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SERVER_EXPOSURE_MODE_CHANNEL,
|
||||
payload: DesktopServerExposureModeSchema,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -41,7 +41,7 @@ export const setServerExposureMode = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({
|
||||
export const setTailscaleServeEnabled = makeIpcMethod({
|
||||
channel: IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL,
|
||||
payload: SetTailscaleServeEnabledInput,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -58,7 +58,7 @@ export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getAdvertisedEndpoints = DesktopIpc.makeIpcMethod({
|
||||
export const getAdvertisedEndpoints = makeIpcMethod({
|
||||
channel: IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Array(AdvertisedEndpoint),
|
||||
|
||||
@@ -33,7 +33,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
|
||||
|
||||
@@ -107,7 +107,7 @@ const withLoopbackSshApi =
|
||||
),
|
||||
);
|
||||
|
||||
export const discoverSshHosts = DesktopIpc.makeIpcMethod({
|
||||
export const discoverSshHosts = makeIpcMethod({
|
||||
channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Array(DesktopDiscoveredSshHostSchema),
|
||||
@@ -117,7 +117,7 @@ export const discoverSshHosts = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
export const ensureSshEnvironment = makeIpcMethod({
|
||||
channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
|
||||
payload: DesktopSshEnvironmentEnsureInputSchema,
|
||||
result: DesktopSshEnvironmentEnsureResultSchema,
|
||||
@@ -139,7 +139,7 @@ export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
export const disconnectSshEnvironment = makeIpcMethod({
|
||||
channel: IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL,
|
||||
payload: DesktopSshEnvironmentTargetSchema,
|
||||
result: Schema.Void,
|
||||
@@ -149,7 +149,7 @@ export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
|
||||
export const fetchSshEnvironmentDescriptor = makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
|
||||
payload: DesktopSshHttpBaseUrlInputSchema,
|
||||
result: ExecutionEnvironmentDescriptor,
|
||||
@@ -160,7 +160,7 @@ export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
|
||||
export const bootstrapSshBearerSession = makeIpcMethod({
|
||||
channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
|
||||
payload: DesktopSshBearerBootstrapInputSchema,
|
||||
result: AuthAccessTokenResult,
|
||||
@@ -177,7 +177,7 @@ export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
|
||||
export const fetchSshSessionState = makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL,
|
||||
payload: DesktopSshBearerRequestInputSchema,
|
||||
result: AuthSessionState,
|
||||
@@ -194,7 +194,7 @@ export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const issueSshWebSocketTicket = DesktopIpc.makeIpcMethod({
|
||||
export const issueSshWebSocketTicket = makeIpcMethod({
|
||||
channel: IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
|
||||
payload: DesktopSshBearerRequestInputSchema,
|
||||
result: AuthWebSocketTicketResult,
|
||||
@@ -211,7 +211,7 @@ export const issueSshWebSocketTicket = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const resolveSshPasswordPrompt = DesktopIpc.makeIpcMethod({
|
||||
export const resolveSshPasswordPrompt = makeIpcMethod({
|
||||
channel: IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
|
||||
payload: DesktopSshPasswordPromptResolutionInputSchema,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -9,9 +9,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopUpdates from "../../updates/DesktopUpdates.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
export const getUpdateState = DesktopIpc.makeIpcMethod({
|
||||
export const getUpdateState = makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_GET_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateStateSchema,
|
||||
@@ -21,7 +21,7 @@ export const getUpdateState = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setUpdateChannel = DesktopIpc.makeIpcMethod({
|
||||
export const setUpdateChannel = makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
|
||||
payload: DesktopUpdateChannelSchema,
|
||||
result: DesktopUpdateStateSchema,
|
||||
@@ -31,7 +31,7 @@ export const setUpdateChannel = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const downloadUpdate = DesktopIpc.makeIpcMethod({
|
||||
export const downloadUpdate = makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_DOWNLOAD_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateActionResultSchema,
|
||||
@@ -41,7 +41,7 @@ export const downloadUpdate = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const installUpdate = DesktopIpc.makeIpcMethod({
|
||||
export const installUpdate = makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateActionResultSchema,
|
||||
@@ -51,7 +51,7 @@ export const installUpdate = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const checkForUpdate = DesktopIpc.makeIpcMethod({
|
||||
export const checkForUpdate = makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_CHECK_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateCheckResultSchema,
|
||||
|
||||
@@ -18,7 +18,7 @@ import * as ElectronShell from "../../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const ContextMenuPosition = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
@@ -36,7 +36,7 @@ function toWebSocketBaseUrl(httpBaseUrl: URL): string {
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
export const getAppBranding = makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
|
||||
result: Schema.NullOr(DesktopAppBrandingSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
|
||||
@@ -45,7 +45,7 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
|
||||
export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
|
||||
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
|
||||
@@ -65,7 +65,7 @@ export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
|
||||
export const getLocalEnvironmentBearerToken = makeIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.String,
|
||||
@@ -75,7 +75,7 @@ export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
export const pickFolder = makeIpcMethod({
|
||||
channel: IpcChannels.PICK_FOLDER_CHANNEL,
|
||||
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
|
||||
result: Schema.NullOr(Schema.String),
|
||||
@@ -91,7 +91,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const confirm = DesktopIpc.makeIpcMethod({
|
||||
export const confirm = makeIpcMethod({
|
||||
channel: IpcChannels.CONFIRM_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
@@ -104,7 +104,7 @@ export const confirm = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTheme = DesktopIpc.makeIpcMethod({
|
||||
export const setTheme = makeIpcMethod({
|
||||
channel: IpcChannels.SET_THEME_CHANNEL,
|
||||
payload: DesktopThemeSchema,
|
||||
result: Schema.Void,
|
||||
@@ -114,7 +114,7 @@ export const setTheme = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const showContextMenu = DesktopIpc.makeIpcMethod({
|
||||
export const showContextMenu = makeIpcMethod({
|
||||
channel: IpcChannels.CONTEXT_MENU_CHANNEL,
|
||||
payload: ContextMenuInput,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
@@ -135,7 +135,7 @@ export const showContextMenu = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const openExternal = DesktopIpc.makeIpcMethod({
|
||||
export const openExternal = makeIpcMethod({
|
||||
channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
|
||||
+10
-11
@@ -14,12 +14,13 @@ import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import serverPackageJson from "../../server/package.json" with { type: "json" };
|
||||
|
||||
import type { DesktopSettings as DesktopSettingsValue } from "./settings/DesktopAppSettings.ts";
|
||||
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
|
||||
import * as ElectronApp from "./electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "./electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "./electron/ElectronMenu.ts";
|
||||
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSecretStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as ElectronShell from "./electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "./electron/ElectronTheme.ts";
|
||||
import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
|
||||
@@ -33,10 +34,8 @@ import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
|
||||
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
|
||||
@@ -47,7 +46,7 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
|
||||
@@ -69,8 +68,8 @@ const desktopEnvironmentLayer = Layer.unwrap(
|
||||
);
|
||||
|
||||
const resolveDesktopSshCliRunner = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
settings: DesktopAppSettings.DesktopSettings,
|
||||
environment: DesktopEnvironment.DesktopEnvironmentShape,
|
||||
settings: DesktopSettingsValue,
|
||||
): RemoteT3RunnerOptions => {
|
||||
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
|
||||
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
|
||||
@@ -106,17 +105,17 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronProtocol.layer,
|
||||
ElectronSafeStorage.layer,
|
||||
DesktopSecretStorage.layer,
|
||||
ElectronShell.layer,
|
||||
ElectronTheme.layer,
|
||||
ElectronUpdater.layer,
|
||||
ElectronWindow.layer,
|
||||
DesktopIpc.layer(Electron.ipcMain),
|
||||
Layer.succeed(DesktopIpc.DesktopIpc, DesktopIpc.make(Electron.ipcMain)),
|
||||
);
|
||||
|
||||
const desktopFoundationLayer = Layer.mergeAll(
|
||||
DesktopState.layer,
|
||||
DesktopShutdown.layer,
|
||||
DesktopLifecycle.layerShutdown,
|
||||
DesktopAppSettings.layer,
|
||||
DesktopClientSettings.layer,
|
||||
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
|
||||
@@ -129,12 +128,12 @@ const desktopSshLayer = desktopSshEnvironmentLayer.pipe(
|
||||
);
|
||||
|
||||
const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(DesktopNetworkInterfaces.layer),
|
||||
Layer.provideMerge(DesktopServerExposure.networkInterfacesLayer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
const desktopPreviewLayer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(BrowserSession.layer),
|
||||
Layer.provideMerge(PreviewBrowserSession.layer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -2,38 +2,36 @@ import type { Session } from "electron";
|
||||
import { session } from "electron";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
|
||||
"BrowserSessionError",
|
||||
{
|
||||
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Desktop preview browser session operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSession extends Context.Service<
|
||||
BrowserSession,
|
||||
{
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserSession") {}
|
||||
export interface BrowserSessionShape {
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
|
||||
"@t3tools/desktop/preview/BrowserSession",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ const environmentLayer = Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
|
||||
} as DesktopEnvironment.DesktopEnvironment["Service"]),
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape),
|
||||
);
|
||||
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
@@ -82,7 +82,7 @@ const layer = PreviewManager.layer.pipe(
|
||||
|
||||
const withManager = <A>(
|
||||
use: (
|
||||
manager: PreviewManager.PreviewManager["Service"],
|
||||
manager: PreviewManager.PreviewManagerShape,
|
||||
) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
+116
-119
@@ -37,6 +37,7 @@ import {
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -431,17 +432,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
) {
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
const tab = tabs.get(tabId);
|
||||
if (!tab) {
|
||||
return yield* fail("requireWebContents", new PreviewTabNotFoundError({ tabId }));
|
||||
}
|
||||
if (!tab) return yield* fail("requireWebContents", new PreviewTabNotFoundError(tabId));
|
||||
if (tab.webContentsId == null) {
|
||||
return yield* fail("requireWebContents", new PreviewWebviewNotInitializedError({ tabId }));
|
||||
return yield* fail("requireWebContents", new PreviewWebviewNotInitializedError(tabId));
|
||||
}
|
||||
const wc = webContents.fromId(tab.webContentsId);
|
||||
if (!wc) {
|
||||
return yield* fail(
|
||||
"requireWebContents",
|
||||
new PreviewWebContentsNotFoundError({ tabId, webContentsId: tab.webContentsId }),
|
||||
new PreviewWebContentsNotFoundError(tabId, tab.webContentsId),
|
||||
);
|
||||
}
|
||||
return wc;
|
||||
@@ -846,7 +845,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
} else {
|
||||
const error = Option.getOrNull(Cause.findErrorOption(exit.cause));
|
||||
const underlying = isPreviewManagerError(error) ? error.cause : error;
|
||||
const underlying = error instanceof PreviewManagerError ? error.cause : error;
|
||||
const interrupted =
|
||||
underlying instanceof Error &&
|
||||
underlying.name === "PreviewAutomationControlInterruptedError";
|
||||
@@ -1162,7 +1161,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
) {
|
||||
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (!tab) {
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError({ tabId }));
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
|
||||
}
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
const mainWindow = yield* Ref.get(mainWindowRef);
|
||||
@@ -1173,7 +1172,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
) {
|
||||
return yield* fail(
|
||||
"registerWebview",
|
||||
new PreviewWebContentsNotFoundError({ tabId, webContentsId }),
|
||||
new PreviewWebContentsNotFoundError(tabId, webContentsId),
|
||||
);
|
||||
}
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
@@ -1225,7 +1224,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
] as const;
|
||||
});
|
||||
if (Option.isNone(registration)) {
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError({ tabId }));
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
@@ -2201,131 +2200,129 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
};
|
||||
});
|
||||
|
||||
export class PreviewTabNotFoundError extends Schema.TaggedErrorClass<PreviewTabNotFoundError>()(
|
||||
"PreviewTabNotFoundError",
|
||||
{ tabId: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Preview tab not found: ${this.tabId}`;
|
||||
export class PreviewTabNotFoundError extends Error {
|
||||
readonly tabId: string;
|
||||
constructor(tabId: string) {
|
||||
super(`Preview tab not found: ${tabId}`);
|
||||
this.name = "PreviewTabNotFoundError";
|
||||
this.tabId = tabId;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewWebContentsNotFoundError extends Schema.TaggedErrorClass<PreviewWebContentsNotFoundError>()(
|
||||
"PreviewWebContentsNotFoundError",
|
||||
{ tabId: Schema.String, webContentsId: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `WebContents ${this.webContentsId} not found for preview tab ${this.tabId}`;
|
||||
export class PreviewWebContentsNotFoundError extends Error {
|
||||
readonly tabId: string;
|
||||
readonly webContentsId: number;
|
||||
constructor(tabId: string, webContentsId: number) {
|
||||
super(`WebContents ${webContentsId} not found for preview tab ${tabId}`);
|
||||
this.name = "PreviewWebContentsNotFoundError";
|
||||
this.tabId = tabId;
|
||||
this.webContentsId = webContentsId;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewWebviewNotInitializedError extends Schema.TaggedErrorClass<PreviewWebviewNotInitializedError>()(
|
||||
"PreviewWebviewNotInitializedError",
|
||||
{ tabId: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Preview tab "${this.tabId}" has no webview registered`;
|
||||
export class PreviewWebviewNotInitializedError extends Error {
|
||||
readonly tabId: string;
|
||||
constructor(tabId: string) {
|
||||
super(`Preview tab "${tabId}" has no webview registered`);
|
||||
this.name = "PreviewWebviewNotInitializedError";
|
||||
this.tabId = tabId;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewManagerError extends Schema.TaggedErrorClass<PreviewManagerError>()(
|
||||
"PreviewManagerError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
export class PreviewManagerError extends Data.TaggedError("PreviewManagerError")<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Desktop preview operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
const isPreviewManagerError = Schema.is(PreviewManagerError);
|
||||
export interface PreviewManagerShape {
|
||||
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
|
||||
readonly isBrowserPartition: (partition: string) => boolean;
|
||||
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
|
||||
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly registerWebview: (
|
||||
tabId: string,
|
||||
webContentsId: number,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly navigate: (tabId: string, url: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goBack: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goForward: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly refresh: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserPartition: (scope?: string) => Effect.Effect<string, PreviewManagerError>;
|
||||
readonly setAnnotationTheme: (
|
||||
theme: DesktopPreviewAnnotationTheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<DesktopPreviewScreenshotArtifact, PreviewManagerError>;
|
||||
readonly revealArtifact: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly saveRecording: (
|
||||
tabId: string,
|
||||
mimeType: string,
|
||||
data: Uint8Array,
|
||||
) => Effect.Effect<DesktopPreviewRecordingArtifact, PreviewManagerError>;
|
||||
readonly automationStatus: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationStatus, PreviewManagerError>;
|
||||
readonly automationSnapshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationSnapshot, PreviewManagerError>;
|
||||
readonly automationClick: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationClickInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationType: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationTypeInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationPress: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationPressInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationScroll: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationScrollInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationEvaluate: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationEvaluateInput,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
readonly automationWaitFor: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationWaitForInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly subscribeStateChanges: (listener: Listener) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribePointerEvents: (
|
||||
listener: PointerEventListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribeRecordingFrames: (
|
||||
listener: RecordingFrameListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class PreviewManager extends Context.Service<
|
||||
PreviewManager,
|
||||
{
|
||||
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
|
||||
readonly isBrowserPartition: (partition: string) => boolean;
|
||||
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
|
||||
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly registerWebview: (
|
||||
tabId: string,
|
||||
webContentsId: number,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly navigate: (tabId: string, url: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goBack: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goForward: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly refresh: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserPartition: (scope?: string) => Effect.Effect<string, PreviewManagerError>;
|
||||
readonly setAnnotationTheme: (
|
||||
theme: DesktopPreviewAnnotationTheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<DesktopPreviewScreenshotArtifact, PreviewManagerError>;
|
||||
readonly revealArtifact: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly saveRecording: (
|
||||
tabId: string,
|
||||
mimeType: string,
|
||||
data: Uint8Array,
|
||||
) => Effect.Effect<DesktopPreviewRecordingArtifact, PreviewManagerError>;
|
||||
readonly automationStatus: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationStatus, PreviewManagerError>;
|
||||
readonly automationSnapshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationSnapshot, PreviewManagerError>;
|
||||
readonly automationClick: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationClickInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationType: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationTypeInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationPress: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationPressInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationScroll: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationScrollInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationEvaluate: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationEvaluateInput,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
readonly automationWaitFor: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationWaitForInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly subscribeStateChanges: (listener: Listener) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribePointerEvents: (
|
||||
listener: PointerEventListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribeRecordingFrames: (
|
||||
listener: RecordingFrameListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/Manager/PreviewManager") {}
|
||||
export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
|
||||
"@t3tools/desktop/preview/Manager/PreviewManager",
|
||||
) {}
|
||||
|
||||
export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
const make = Effect.gen(function* PreviewManagerMake() {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const browserSession = yield* BrowserSession.BrowserSession;
|
||||
const operations = yield* makeNativeOperations(environment.browserArtifactsDir);
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection.
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeModule from "node:module";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeVM from "node:vm";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { runInNewContext } 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 require = createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
|
||||
@@ -32,11 +32,7 @@ export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRunt
|
||||
catch: (cause) => fail("resolvePackage", cause),
|
||||
});
|
||||
const coreBundle = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
NodeFSP.readFile(
|
||||
NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js"),
|
||||
"utf8",
|
||||
),
|
||||
try: () => readFile(join(dirname(packageJsonPath), "lib/coreBundle.js"), "utf8"),
|
||||
catch: (cause) => fail("readCoreBundle", cause),
|
||||
});
|
||||
const marker = "source3 = ";
|
||||
@@ -57,7 +53,7 @@ export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRunt
|
||||
}
|
||||
const literal = coreBundle.slice(literalStart, literalEnd);
|
||||
const source = yield* Effect.try({
|
||||
try: () => NodeVM.runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
|
||||
try: () => runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
|
||||
catch: (cause) => fail("evaluateSourceLiteral", cause),
|
||||
});
|
||||
if (typeof source !== "string" || source.length < 100_000) {
|
||||
|
||||
@@ -8,6 +8,11 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
resolveDefaultDesktopSettings,
|
||||
type DesktopSettings as DesktopSettingsValue,
|
||||
} from "./DesktopAppSettings.ts";
|
||||
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
|
||||
|
||||
const DesktopSettingsPatch = Schema.Struct({
|
||||
@@ -77,23 +82,20 @@ describe("DesktopSettings", () => {
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
assert.deepEqual(yield* settings.load, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
|
||||
assert.deepEqual(yield* settings.get, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
|
||||
assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
|
||||
assert.deepEqual(yield* settings.get, DEFAULT_DESKTOP_SETTINGS);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it("defaults packaged nightly builds to the nightly update channel", () => {
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopAppSettings.DesktopSettings,
|
||||
);
|
||||
assert.deepEqual(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"), {
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopSettingsValue);
|
||||
});
|
||||
|
||||
it.effect("loads persisted settings and applies semantic updates", () =>
|
||||
@@ -114,7 +116,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
} satisfies DesktopSettingsValue);
|
||||
|
||||
const exposure = yield* settings.setServerExposureMode("local-only");
|
||||
assert.isTrue(exposure.changed);
|
||||
@@ -135,27 +137,6 @@ describe("DesktopSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports the failed desktop settings write operation and path", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* fileSystem.makeDirectory(environment.desktopSettingsPath, { recursive: true });
|
||||
|
||||
const error = yield* settings.setServerExposureMode("network-accessible").pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopAppSettings.DesktopSettingsWriteError);
|
||||
assert.equal(error.operation, "replace-settings-file");
|
||||
assert.equal(error.path, environment.desktopSettingsPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop settings write failed during replace-settings-file at ${environment.desktopSettingsPath}.`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist no-op semantic updates", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -186,7 +167,7 @@ describe("DesktopSettings", () => {
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.desktopSettingsPath, "{not-json");
|
||||
|
||||
assert.deepEqual(yield* settings.load, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
|
||||
assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -214,7 +195,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
} satisfies DesktopSettingsValue);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -253,7 +234,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
} satisfies DesktopSettingsValue);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
),
|
||||
@@ -275,7 +256,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
} satisfies DesktopSettingsValue);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
),
|
||||
@@ -296,7 +277,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
} satisfies DesktopSettingsValue);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -7,11 +7,13 @@ import {
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
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 Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
@@ -61,50 +63,32 @@ const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSet
|
||||
changed,
|
||||
});
|
||||
|
||||
const DesktopSettingsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-settings-file",
|
||||
]);
|
||||
type DesktopSettingsWriteOperation = typeof DesktopSettingsWriteOperation.Type;
|
||||
|
||||
export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSettingsWriteError>()(
|
||||
"DesktopSettingsWriteError",
|
||||
{
|
||||
operation: DesktopSettingsWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop settings write failed during ${this.operation} at ${this.path}.`;
|
||||
export class DesktopSettingsWriteError extends Data.TaggedError("DesktopSettingsWriteError")<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop settings: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
|
||||
export interface DesktopAppSettingsShape {
|
||||
readonly load: Effect.Effect<DesktopSettings>;
|
||||
readonly get: Effect.Effect<DesktopSettings>;
|
||||
readonly setServerExposureMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setTailscaleServe: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port: Option.Option<number>;
|
||||
}) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setUpdateChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
}
|
||||
|
||||
export class DesktopAppSettings extends Context.Service<
|
||||
DesktopAppSettings,
|
||||
{
|
||||
readonly load: Effect.Effect<DesktopSettings>;
|
||||
readonly get: Effect.Effect<DesktopSettings>;
|
||||
readonly setServerExposureMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setTailscaleServe: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port: Option.Option<number>;
|
||||
}) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setUpdateChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
}
|
||||
DesktopAppSettingsShape
|
||||
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
|
||||
|
||||
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
|
||||
@@ -239,86 +223,77 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
|
||||
readonly settings: DesktopSettings;
|
||||
readonly defaultSettings: DesktopSettings;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, DesktopSettingsWriteError> {
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.settingsPath);
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeDesktopSettingsJson(
|
||||
toDesktopSettingsDocument(input.settings, input.defaultSettings),
|
||||
).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)),
|
||||
);
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
|
||||
export const layer = Layer.effect(
|
||||
DesktopAppSettings,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
|
||||
|
||||
const persist = (
|
||||
update: (settings: DesktopSettings) => DesktopSettings,
|
||||
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
|
||||
SynchronizedRef.modifyEffect(settingsRef, (settings) => {
|
||||
const nextSettings = update(settings);
|
||||
if (nextSettings === settings) {
|
||||
return Effect.succeed([settingsChange(settings, false), settings] as const);
|
||||
}
|
||||
const persist = (
|
||||
update: (settings: DesktopSettings) => DesktopSettings,
|
||||
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
|
||||
SynchronizedRef.modifyEffect(settingsRef, (settings) => {
|
||||
const nextSettings = update(settings);
|
||||
if (nextSettings === settings) {
|
||||
return Effect.succeed([settingsChange(settings, false), settings] as const);
|
||||
}
|
||||
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.desktopSettingsPath,
|
||||
settings: nextSettings,
|
||||
defaultSettings: environment.defaultDesktopSettings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
|
||||
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
|
||||
);
|
||||
});
|
||||
|
||||
return DesktopAppSettings.of({
|
||||
get: SynchronizedRef.get(settingsRef),
|
||||
load: Effect.gen(function* () {
|
||||
const settings = yield* readSettings(
|
||||
fileSystem,
|
||||
environment.desktopSettingsPath,
|
||||
environment.appVersion,
|
||||
);
|
||||
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
|
||||
}).pipe(Effect.withSpan("desktop.settings.load")),
|
||||
setServerExposureMode: (mode) =>
|
||||
persist((settings) => setServerExposureMode(settings, mode)).pipe(
|
||||
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.desktopSettingsPath,
|
||||
settings: nextSettings,
|
||||
defaultSettings: environment.defaultDesktopSettings,
|
||||
suffix,
|
||||
}),
|
||||
setTailscaleServe: (input) =>
|
||||
persist((settings) => setTailscaleServe(settings, input)).pipe(
|
||||
Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
|
||||
),
|
||||
setUpdateChannel: (channel) =>
|
||||
persist((settings) => setUpdateChannel(settings, channel)).pipe(
|
||||
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
|
||||
),
|
||||
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
|
||||
);
|
||||
});
|
||||
|
||||
return DesktopAppSettings.of({
|
||||
get: SynchronizedRef.get(settingsRef),
|
||||
load: Effect.gen(function* () {
|
||||
const settings = yield* readSettings(
|
||||
fileSystem,
|
||||
environment.desktopSettingsPath,
|
||||
environment.appVersion,
|
||||
);
|
||||
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
|
||||
}).pipe(Effect.withSpan("desktop.settings.load")),
|
||||
setServerExposureMode: (mode) =>
|
||||
persist((settings) => setServerExposureMode(settings, mode)).pipe(
|
||||
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
|
||||
),
|
||||
setTailscaleServe: (input) =>
|
||||
persist((settings) => setTailscaleServe(settings, input)).pipe(
|
||||
Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
|
||||
),
|
||||
setUpdateChannel: (channel) =>
|
||||
persist((settings) => setUpdateChannel(settings, channel)).pipe(
|
||||
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopAppSettings, make);
|
||||
}),
|
||||
);
|
||||
|
||||
export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SETTINGS) =>
|
||||
Layer.effect(
|
||||
|
||||
@@ -15,6 +15,7 @@ const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
defaultRuntimeMode: "full-access",
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
@@ -34,6 +35,7 @@ const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(Clien
|
||||
const decodeRecordJson = Schema.decodeEffect(
|
||||
Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
);
|
||||
|
||||
function makeLayer(baseDir: string) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
@@ -105,27 +107,6 @@ describe("DesktopClientSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports the failed client settings write operation and path", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
yield* fileSystem.makeDirectory(environment.clientSettingsPath, { recursive: true });
|
||||
|
||||
const error = yield* settings.set(clientSettings).pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsWriteError);
|
||||
assert.equal(error.operation, "replace-settings-file");
|
||||
assert.equal(error.path, environment.clientSettingsPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("loads lenient direct client settings documents", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -2,11 +2,13 @@ import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
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 Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
@@ -29,43 +31,24 @@ const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Sc
|
||||
);
|
||||
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
|
||||
|
||||
const DesktopClientSettingsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-settings-file",
|
||||
]);
|
||||
type DesktopClientSettingsWriteOperation = typeof DesktopClientSettingsWriteOperation.Type;
|
||||
|
||||
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
|
||||
export class DesktopClientSettingsWriteError extends Data.TaggedError(
|
||||
"DesktopClientSettingsWriteError",
|
||||
{
|
||||
operation: DesktopClientSettingsWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop client settings write failed during ${this.operation} at ${this.path}.`;
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop client settings: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopClientSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopClientSettingsWriteError =>
|
||||
new DesktopClientSettingsWriteError({ operation, path, cause });
|
||||
export interface DesktopClientSettingsShape {
|
||||
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
|
||||
readonly set: (settings: ClientSettings) => Effect.Effect<void, DesktopClientSettingsWriteError>;
|
||||
}
|
||||
|
||||
export class DesktopClientSettings extends Context.Service<
|
||||
DesktopClientSettings,
|
||||
{
|
||||
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
|
||||
readonly set: (
|
||||
settings: ClientSettings,
|
||||
) => Effect.Effect<void, DesktopClientSettingsWriteError>;
|
||||
}
|
||||
DesktopClientSettingsShape
|
||||
>()("@t3tools/desktop/settings/DesktopClientSettings") {}
|
||||
|
||||
const readClientSettings = (
|
||||
@@ -92,56 +75,45 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
|
||||
readonly settingsPath: string;
|
||||
readonly settings: ClientSettings;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, DesktopClientSettingsWriteError> {
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.settingsPath);
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)),
|
||||
);
|
||||
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)),
|
||||
);
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
export const layer = Layer.effect(
|
||||
DesktopClientSettings,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
return DesktopClientSettings.of({
|
||||
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
|
||||
Effect.withSpan("desktop.clientSettings.get"),
|
||||
),
|
||||
set: (settings) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.clientSettingsPath, cause),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeClientSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
settings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.clientSettings.set"),
|
||||
return DesktopClientSettings.of({
|
||||
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
|
||||
Effect.withSpan("desktop.clientSettings.get"),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopClientSettings, make);
|
||||
set: (settings) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeClientSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
settings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
|
||||
Effect.withSpan("desktop.clientSettings.set"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export const layerTest = (initialSettings: Option.Option<ClientSettings> = Option.none()) =>
|
||||
Layer.effect(
|
||||
|
||||
@@ -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";
|
||||
@@ -35,15 +34,10 @@ const SavedEnvironmentRegistryDocumentProbe = Schema.Struct({
|
||||
version: Schema.Number,
|
||||
records: Schema.Array(Schema.Unknown),
|
||||
});
|
||||
const SavedEnvironmentRegistryDocumentProbeJson = Schema.fromJsonString(
|
||||
SavedEnvironmentRegistryDocumentProbe,
|
||||
);
|
||||
const decodeSavedEnvironmentRegistryDocumentProbe = Schema.decodeEffect(
|
||||
SavedEnvironmentRegistryDocumentProbeJson,
|
||||
);
|
||||
const encodeSavedEnvironmentRegistryDocumentProbe = Schema.encodeEffect(
|
||||
SavedEnvironmentRegistryDocumentProbeJson,
|
||||
Schema.fromJsonString(SavedEnvironmentRegistryDocumentProbe),
|
||||
);
|
||||
|
||||
function makeSafeStorageLayer(input: {
|
||||
readonly available: boolean;
|
||||
readonly availabilityError?: unknown;
|
||||
@@ -86,7 +80,7 @@ function makeSafeStorageLayer(input: {
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
@@ -97,7 +91,6 @@ function makeLayer(
|
||||
readonly encryptError?: unknown;
|
||||
readonly decryptError?: unknown;
|
||||
},
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
|
||||
) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
@@ -115,20 +108,18 @@ function makeLayer(
|
||||
),
|
||||
);
|
||||
|
||||
const safeStorageLayer = makeSafeStorageLayer({
|
||||
available: options?.availableSecretStorage ?? true,
|
||||
availabilityError: options?.availabilityError,
|
||||
encryptError: options?.encryptError,
|
||||
decryptError: options?.decryptError,
|
||||
});
|
||||
const dependencies = Layer.mergeAll(
|
||||
environmentLayer,
|
||||
safeStorageLayer,
|
||||
NodeServices.layer,
|
||||
fileSystemLayer,
|
||||
return DesktopSavedEnvironments.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(
|
||||
makeSafeStorageLayer({
|
||||
available: options?.availableSecretStorage ?? true,
|
||||
availabilityError: options?.availabilityError,
|
||||
encryptError: options?.encryptError,
|
||||
decryptError: options?.decryptError,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return DesktopSavedEnvironments.layer.pipe(Layer.provideMerge(dependencies));
|
||||
}
|
||||
|
||||
const withSavedEnvironments = <A, E, R>(
|
||||
@@ -224,36 +215,6 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports invalid saved secret encoding without exposing the secret", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentProbe({
|
||||
version: 1,
|
||||
records: [{ ...savedRegistryRecord, encryptedBearerToken: "%%%" }],
|
||||
});
|
||||
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, `${encoded}\n`);
|
||||
|
||||
const error = yield* savedEnvironments
|
||||
.getSecret(savedRegistryRecord.environmentId)
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentSecretDecodeError);
|
||||
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
|
||||
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
|
||||
assert.equal(error.field, "encryptedBearerToken");
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to decode encryptedBearerToken for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "%%%");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns false when writing secrets while encryption is unavailable", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
@@ -360,96 +321,16 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
registryError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
|
||||
);
|
||||
assert.equal(registryError.registryPath, environment.savedEnvironmentRegistryPath);
|
||||
assert.exists(registryError.cause);
|
||||
const secretError = yield* savedEnvironments
|
||||
.getSecret(savedRegistryRecord.environmentId)
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
secretError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
const mutationError = yield* savedEnvironments
|
||||
.setRegistry([savedRegistryRecord])
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
mutationError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports saved environment filesystem reads separately from document decoding", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
const registryPath = `${baseDir}/userdata/saved-environments.json`;
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: registryPath,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments.pipe(
|
||||
Effect.provide(makeLayer(baseDir, undefined, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
|
||||
assert.equal(error.registryPath, registryPath);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(error.message, `Failed to read desktop saved environments at ${registryPath}.`);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the failed saved environment write operation and path", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: baseFileSystem.readFileString,
|
||||
makeDirectory: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments.pipe(
|
||||
Effect.provide(makeLayer(baseDir, undefined, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("returns false when writing a secret without metadata", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -2,12 +2,14 @@ import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/co
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
@@ -70,118 +72,73 @@ const encodeSavedEnvironmentRegistryDocumentJson = Schema.encodeEffect(
|
||||
SavedEnvironmentRegistryDocumentJson,
|
||||
);
|
||||
|
||||
const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-registry",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-registry-file",
|
||||
]);
|
||||
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
|
||||
|
||||
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
|
||||
export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
|
||||
"DesktopSavedEnvironmentsWriteError",
|
||||
{
|
||||
operation: DesktopSavedEnvironmentsWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop saved-environment write failed during ${this.operation} at ${this.path}.`;
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop saved environments: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSavedEnvironmentsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSavedEnvironmentsWriteError =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
|
||||
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
|
||||
"DesktopSavedEnvironmentsReadError",
|
||||
{
|
||||
registryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read desktop saved environments at ${this.registryPath}.`;
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to read desktop saved environments: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentsDocumentDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsDocumentDecodeError>()(
|
||||
"DesktopSavedEnvironmentsDocumentDecodeError",
|
||||
{
|
||||
registryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode desktop saved environments at ${this.registryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretDecodeError>()(
|
||||
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
|
||||
"DesktopSavedEnvironmentSecretDecodeError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
registryPath: Schema.String,
|
||||
field: Schema.Literal("encryptedBearerToken"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.field} for environment ${this.environmentId} at ${this.registryPath}.`;
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode desktop saved environment secret.";
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopSavedEnvironmentsReadRegistryError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
|
||||
export type DesktopSavedEnvironmentsMutationError =
|
||||
| DesktopSavedEnvironmentsReadRegistryError
|
||||
| DesktopSavedEnvironmentsWriteError;
|
||||
|
||||
export type DesktopSavedEnvironmentsGetSecretError =
|
||||
| DesktopSavedEnvironmentsReadRegistryError
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentSecretDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
|
||||
export type DesktopSavedEnvironmentsSetSecretError =
|
||||
| DesktopSavedEnvironmentsMutationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
| DesktopSavedEnvironmentsWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
|
||||
|
||||
export interface DesktopSavedEnvironmentsShape {
|
||||
readonly getRegistry: Effect.Effect<
|
||||
readonly PersistedSavedEnvironmentRecord[],
|
||||
DesktopSavedEnvironmentsReadError
|
||||
>;
|
||||
readonly setRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly removeEnvironment: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly getSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
|
||||
readonly setSecret: (input: {
|
||||
readonly environmentId: string;
|
||||
readonly secret: string;
|
||||
}) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
|
||||
readonly removeSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironments extends Context.Service<
|
||||
DesktopSavedEnvironments,
|
||||
{
|
||||
readonly getRegistry: Effect.Effect<
|
||||
readonly PersistedSavedEnvironmentRecord[],
|
||||
DesktopSavedEnvironmentsReadRegistryError
|
||||
>;
|
||||
readonly setRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
|
||||
readonly removeEnvironment: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
|
||||
readonly getSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
|
||||
readonly setSecret: (input: {
|
||||
readonly environmentId: string;
|
||||
readonly secret: string;
|
||||
}) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
|
||||
readonly removeSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
|
||||
}
|
||||
DesktopSavedEnvironmentsShape
|
||||
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
@@ -236,30 +193,19 @@ function normalizeSavedEnvironmentRegistryDocument(
|
||||
function readRegistryDocument(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
registryPath: string,
|
||||
): Effect.Effect<SavedEnvironmentRegistryDocument, DesktopSavedEnvironmentsReadRegistryError> {
|
||||
): Effect.Effect<
|
||||
SavedEnvironmentRegistryDocument,
|
||||
PlatformError.PlatformError | Schema.SchemaError
|
||||
> {
|
||||
return fileSystem.readFileString(registryPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound"
|
||||
? Effect.succeed<string | null>(null)
|
||||
: Effect.fail(
|
||||
new DesktopSavedEnvironmentsReadError({
|
||||
registryPath,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed({ version: 1, records: [] })
|
||||
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
|
||||
Effect.map(normalizeSavedEnvironmentRegistryDocument),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsDocumentDecodeError({
|
||||
registryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -272,23 +218,13 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
|
||||
readonly registryPath: string;
|
||||
readonly document: SavedEnvironmentRegistryDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, DesktopSavedEnvironmentsWriteError> {
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.registryPath);
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-registry", input.registryPath, cause)),
|
||||
);
|
||||
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)),
|
||||
);
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.registryPath);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -314,159 +250,147 @@ function preserveExistingSecrets(
|
||||
}
|
||||
|
||||
function decodeSecretBytes(
|
||||
environmentId: string,
|
||||
registryPath: string,
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopSavedEnvironmentSecretDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretDecodeError({
|
||||
environmentId,
|
||||
registryPath,
|
||||
field: "encryptedBearerToken",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSavedEnvironmentSecretDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
export const layer = Layer.effect(
|
||||
DesktopSavedEnvironments,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeRegistryDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
document,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopSavedEnvironments.of({
|
||||
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
|
||||
Effect.map((document) =>
|
||||
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
),
|
||||
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
|
||||
),
|
||||
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
|
||||
const currentDocument = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeRegistryDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
document,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })),
|
||||
);
|
||||
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
|
||||
}),
|
||||
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
|
||||
function* (environmentId) {
|
||||
|
||||
return DesktopSavedEnvironments.of({
|
||||
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
|
||||
Effect.map((document) =>
|
||||
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
|
||||
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
|
||||
),
|
||||
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
|
||||
const currentDocument = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
|
||||
}),
|
||||
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
|
||||
function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (!document.records.some((record) => record.environmentId === environmentId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.filter((record) => record.environmentId !== environmentId),
|
||||
});
|
||||
},
|
||||
),
|
||||
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
|
||||
const encoded = Option.fromNullishOr(
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
);
|
||||
if (!document.records.some((record) => record.environmentId === environmentId)) {
|
||||
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
const secretBytes = yield* decodeSecretBytes(encoded.value);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}),
|
||||
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
|
||||
const { environmentId, secret } = input;
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedBearerToken = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(secret),
|
||||
);
|
||||
let found = false;
|
||||
const nextDocument: SavedEnvironmentRegistryDocument = {
|
||||
version: document.version,
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
found = true;
|
||||
return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));
|
||||
}),
|
||||
};
|
||||
|
||||
if (found) {
|
||||
yield* writeDocument(nextDocument);
|
||||
}
|
||||
return found;
|
||||
}),
|
||||
removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
record.environmentId === environmentId && record.encryptedBearerToken !== undefined,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.filter((record) => record.environmentId !== environmentId),
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
return toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
});
|
||||
},
|
||||
),
|
||||
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
const encoded = Option.fromNullishOr(
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
);
|
||||
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
const secretBytes = yield* decodeSecretBytes(
|
||||
environmentId,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
encoded.value,
|
||||
);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}),
|
||||
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
|
||||
const { environmentId, secret } = input;
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
|
||||
let found = false;
|
||||
const nextDocument: SavedEnvironmentRegistryDocument = {
|
||||
version: document.version,
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
found = true;
|
||||
return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));
|
||||
}),
|
||||
};
|
||||
|
||||
if (found) {
|
||||
yield* writeDocument(nextDocument);
|
||||
}
|
||||
return found;
|
||||
}),
|
||||
removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
record.environmentId === environmentId && record.encryptedBearerToken !== undefined,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
return toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
});
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopSavedEnvironments, make);
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export const layerTest = (input?: {
|
||||
readonly records?: readonly PersistedSavedEnvironmentRecord[];
|
||||
|
||||
@@ -64,7 +64,7 @@ function runShellEnvironment(input: {
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
platform: input.platform,
|
||||
} as DesktopEnvironment.DesktopEnvironment["Service"]),
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape),
|
||||
);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
|
||||
@@ -3,8 +3,7 @@ import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as 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";
|
||||
|
||||
@@ -20,11 +19,13 @@ interface WindowsProbeOptions {
|
||||
readonly loadProfile: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopShellEnvironmentShape {
|
||||
readonly installIntoProcess: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export class DesktopShellEnvironment extends Context.Service<
|
||||
DesktopShellEnvironment,
|
||||
{
|
||||
readonly installIntoProcess: Effect.Effect<void>;
|
||||
}
|
||||
DesktopShellEnvironmentShape
|
||||
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
@@ -211,7 +212,11 @@ const readLoginShellEnvironment = (
|
||||
timeout: LOGIN_SHELL_TIMEOUT,
|
||||
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
|
||||
|
||||
const readLaunchctlPath = runCommandOutput({
|
||||
const readLaunchctlPath: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = runCommandOutput({
|
||||
command: "/bin/launchctl",
|
||||
args: ["getenv", "PATH"],
|
||||
timeout: LAUNCHCTL_TIMEOUT,
|
||||
@@ -331,20 +336,20 @@ const installShellEnvironment = (
|
||||
return Effect.void;
|
||||
};
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
|
||||
installShellEnvironment({
|
||||
env: process.env,
|
||||
platform: environment.platform,
|
||||
userShell: Option.none(),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
|
||||
);
|
||||
|
||||
return DesktopShellEnvironment.of({ installIntoProcess });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopShellEnvironment, make);
|
||||
export const layer = Layer.effect(
|
||||
DesktopShellEnvironment,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
return DesktopShellEnvironment.of({
|
||||
installIntoProcess: installShellEnvironment({
|
||||
env: process.env,
|
||||
platform: environment.platform,
|
||||
userShell: Option.none(),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -19,20 +19,6 @@ function makeTempHomeDir() {
|
||||
}
|
||||
|
||||
describe("sshEnvironment", () => {
|
||||
it("keeps prompt presentation diagnostics distinct from the legacy wrapper message", () => {
|
||||
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
|
||||
requestId: "prompt-1",
|
||||
destination: "devbox",
|
||||
cause: new Error("renderer send failed"),
|
||||
});
|
||||
|
||||
assert.equal(cause.message, "Failed to present SSH password prompt for devbox.");
|
||||
assert.equal(
|
||||
DesktopSshEnvironment.toSshPasswordPromptError(cause).message,
|
||||
"T3 Code window is not available for SSH authentication.",
|
||||
);
|
||||
});
|
||||
|
||||
it("treats password prompt timeouts as cancellable authentication prompts", () => {
|
||||
assert.equal(
|
||||
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(
|
||||
@@ -118,6 +104,7 @@ describe("sshEnvironment", () => {
|
||||
Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {
|
||||
request: () => Effect.die("unexpected password prompt request"),
|
||||
resolve: () => Effect.die("unexpected password prompt resolution"),
|
||||
cancelPending: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
|
||||
@@ -4,7 +4,11 @@ import type {
|
||||
DesktopSshEnvironmentTarget,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as SshAuth from "@t3tools/ssh/auth";
|
||||
import {
|
||||
SshPasswordPrompt,
|
||||
type SshPasswordPromptShape,
|
||||
type SshPasswordRequest,
|
||||
} from "@t3tools/ssh/auth";
|
||||
import { discoverSshHosts } from "@t3tools/ssh/config";
|
||||
import {
|
||||
SshCommandError,
|
||||
@@ -15,14 +19,14 @@ import {
|
||||
SshPasswordPromptError,
|
||||
SshReadinessError,
|
||||
} from "@t3tools/ssh/errors";
|
||||
import * as SshTunnel from "@t3tools/ssh/tunnel";
|
||||
import { SshEnvironmentManager, type RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
|
||||
|
||||
@@ -48,25 +52,27 @@ export type DesktopSshEnvironmentError =
|
||||
| DesktopSshEnvironmentDiscoverError
|
||||
| DesktopSshEnvironmentOperationError;
|
||||
|
||||
export interface DesktopSshEnvironmentShape {
|
||||
readonly discoverHosts: (input?: {
|
||||
readonly homeDir?: string;
|
||||
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
|
||||
readonly ensureEnvironment: (
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
options?: { readonly issuePairingToken?: boolean },
|
||||
) => Effect.Effect<DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentOperationError>;
|
||||
readonly disconnectEnvironment: (
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
|
||||
}
|
||||
|
||||
export class DesktopSshEnvironment extends Context.Service<
|
||||
DesktopSshEnvironment,
|
||||
{
|
||||
readonly discoverHosts: (input?: {
|
||||
readonly homeDir?: string;
|
||||
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
|
||||
readonly ensureEnvironment: (
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
options?: { readonly issuePairingToken?: boolean },
|
||||
) => Effect.Effect<DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentOperationError>;
|
||||
readonly disconnectEnvironment: (
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
|
||||
}
|
||||
DesktopSshEnvironmentShape
|
||||
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
|
||||
|
||||
export interface DesktopSshEnvironmentLayerOptions {
|
||||
readonly resolveCliPackageSpec?: () => string;
|
||||
readonly resolveCliRunner?: Effect.Effect<SshTunnel.RemoteT3RunnerOptions>;
|
||||
readonly resolveCliRunner?: Effect.Effect<RemoteT3RunnerOptions>;
|
||||
}
|
||||
|
||||
function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
|
||||
@@ -82,53 +88,27 @@ export function isDesktopSshPasswordPromptCancellation(
|
||||
);
|
||||
}
|
||||
|
||||
function unexpectedPasswordPromptError(error: never): never {
|
||||
throw new Error(`Unhandled desktop SSH password prompt error: ${String(error)}`);
|
||||
}
|
||||
|
||||
export function toSshPasswordPromptError(
|
||||
cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptRequestError,
|
||||
): SshPasswordPromptError {
|
||||
let message: string;
|
||||
switch (cause._tag) {
|
||||
case "DesktopSshPromptRequestIdGenerationError":
|
||||
message = "Secure randomness is unavailable.";
|
||||
break;
|
||||
case "DesktopSshPromptWindowUnavailableError":
|
||||
case "DesktopSshPromptPresentationError":
|
||||
message = "T3 Code window is not available for SSH authentication.";
|
||||
break;
|
||||
case "DesktopSshPromptTimedOutError":
|
||||
message = `SSH authentication timed out for ${cause.destination}.`;
|
||||
break;
|
||||
case "DesktopSshPromptCancelledError":
|
||||
message = `SSH authentication cancelled for ${cause.destination}.`;
|
||||
break;
|
||||
case "DesktopSshPromptWindowClosedError":
|
||||
message = "SSH authentication was cancelled because the app window closed.";
|
||||
break;
|
||||
case "DesktopSshPromptServiceStoppedError":
|
||||
message = "SSH password prompt service stopped.";
|
||||
break;
|
||||
default:
|
||||
return unexpectedPasswordPromptError(cause);
|
||||
}
|
||||
return new SshPasswordPromptError({ message, cause });
|
||||
}
|
||||
|
||||
const makePasswordPrompt = (
|
||||
prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPrompts["Service"],
|
||||
): SshAuth.SshPasswordPrompt["Service"] => ({
|
||||
prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPromptsShape,
|
||||
): SshPasswordPromptShape => ({
|
||||
isAvailable: true,
|
||||
request: (request: SshAuth.SshPasswordRequest) =>
|
||||
prompts.request(request).pipe(Effect.mapError(toSshPasswordPromptError)),
|
||||
request: (request: SshPasswordRequest) =>
|
||||
prompts.request(request).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SshPasswordPromptError({
|
||||
message: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const manager = yield* SshTunnel.SshEnvironmentManager;
|
||||
const make = Effect.gen(function* () {
|
||||
const manager = yield* SshEnvironmentManager;
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>();
|
||||
const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts));
|
||||
const passwordPrompt = SshPasswordPrompt.of(makePasswordPrompt(prompts));
|
||||
|
||||
return DesktopSshEnvironment.of({
|
||||
discoverHosts: (input) =>
|
||||
@@ -140,7 +120,7 @@ export const make = Effect.gen(function* () {
|
||||
manager
|
||||
.ensureEnvironment(target, ensureOptions)
|
||||
.pipe(
|
||||
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
|
||||
Effect.provideService(SshPasswordPrompt, passwordPrompt),
|
||||
Effect.provide(runtimeContext),
|
||||
Effect.withSpan("desktop.ssh.ensureEnvironment"),
|
||||
),
|
||||
@@ -148,7 +128,7 @@ export const make = Effect.gen(function* () {
|
||||
manager
|
||||
.disconnectEnvironment(target)
|
||||
.pipe(
|
||||
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
|
||||
Effect.provideService(SshPasswordPrompt, passwordPrompt),
|
||||
Effect.provide(runtimeContext),
|
||||
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
|
||||
),
|
||||
@@ -158,7 +138,7 @@ export const make = Effect.gen(function* () {
|
||||
export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) =>
|
||||
Layer.effect(DesktopSshEnvironment, make).pipe(
|
||||
Layer.provide(
|
||||
SshTunnel.SshEnvironmentManager.layer({
|
||||
SshEnvironmentManager.layer({
|
||||
...(options.resolveCliPackageSpec === undefined
|
||||
? {}
|
||||
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
|
||||
|
||||
@@ -9,7 +9,7 @@ import * as TestClock from "effect/testing/TestClock";
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { SSH_PASSWORD_PROMPT_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
|
||||
|
||||
interface SentMessage {
|
||||
@@ -111,7 +111,7 @@ describe("DesktopSshPasswordPrompts", () => {
|
||||
assert.equal(testWindow.sentMessages.length, 1);
|
||||
const sent = testWindow.sentMessages[0];
|
||||
assert.ok(sent);
|
||||
assert.equal(sent.channel, SSH_PASSWORD_PROMPT_CHANNEL);
|
||||
assert.equal(sent.channel, IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL);
|
||||
const request = sent.args[0] as { readonly requestId: string; readonly destination: string };
|
||||
assert.equal(request.destination, "devbox");
|
||||
assert.equal(testWindow.isRestored(), true);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contract
|
||||
import type { SshPasswordRequest } from "@t3tools/ssh/auth";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -10,134 +11,93 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { SSH_PASSWORD_PROMPT_CHANNEL } from "../ipc/channels.ts";
|
||||
|
||||
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
|
||||
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
|
||||
|
||||
type DesktopSshPasswordPromptResolutionInput =
|
||||
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
|
||||
|
||||
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
|
||||
|
||||
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
|
||||
"DesktopSshPromptRequestIdGenerationError",
|
||||
{
|
||||
destination: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Secure randomness is unavailable.";
|
||||
export class DesktopSshPromptUnavailableError extends Data.TaggedError(
|
||||
"DesktopSshPromptUnavailableError",
|
||||
)<{
|
||||
readonly reason: string;
|
||||
}> {
|
||||
override get message() {
|
||||
return this.reason;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorClass<DesktopSshPromptWindowUnavailableError>()(
|
||||
export class DesktopSshPromptWindowUnavailableError extends Data.TaggedError(
|
||||
"DesktopSshPromptWindowUnavailableError",
|
||||
{
|
||||
destination: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly destination: string;
|
||||
}> {
|
||||
override get message() {
|
||||
return WINDOW_UNAVAILABLE_MESSAGE;
|
||||
}
|
||||
}
|
||||
|
||||
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
|
||||
|
||||
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
|
||||
"DesktopSshPromptPresentationError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
destination: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to present SSH password prompt for ${this.destination}.`;
|
||||
export class DesktopSshPromptSendError extends Data.TaggedError("DesktopSshPromptSendError")<{
|
||||
readonly requestId: string;
|
||||
readonly destination: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return WINDOW_UNAVAILABLE_MESSAGE;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSshPromptTimedOutError extends Schema.TaggedErrorClass<DesktopSshPromptTimedOutError>()(
|
||||
export class DesktopSshPromptTimedOutError extends Data.TaggedError(
|
||||
"DesktopSshPromptTimedOutError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
destination: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly requestId: string;
|
||||
readonly destination: string;
|
||||
}> {
|
||||
override get message() {
|
||||
return `SSH authentication timed out for ${this.destination}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSshPromptCancelledError extends Schema.TaggedErrorClass<DesktopSshPromptCancelledError>()(
|
||||
export class DesktopSshPromptCancelledError extends Data.TaggedError(
|
||||
"DesktopSshPromptCancelledError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
destination: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `SSH authentication cancelled for ${this.destination}.`;
|
||||
)<{
|
||||
readonly requestId: string;
|
||||
readonly destination: string;
|
||||
readonly reason: string;
|
||||
}> {
|
||||
override get message() {
|
||||
return this.reason;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSshPromptWindowClosedError extends Schema.TaggedErrorClass<DesktopSshPromptWindowClosedError>()(
|
||||
"DesktopSshPromptWindowClosedError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
destination: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "SSH authentication was cancelled because the app window closed.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSshPromptServiceStoppedError extends Schema.TaggedErrorClass<DesktopSshPromptServiceStoppedError>()(
|
||||
"DesktopSshPromptServiceStoppedError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
destination: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "SSH password prompt service stopped.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSshPromptInvalidRequestIdError extends Schema.TaggedErrorClass<DesktopSshPromptInvalidRequestIdError>()(
|
||||
export class DesktopSshPromptInvalidRequestIdError extends Data.TaggedError(
|
||||
"DesktopSshPromptInvalidRequestIdError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly requestId: string;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Invalid SSH password prompt id.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSshPromptExpiredError extends Schema.TaggedErrorClass<DesktopSshPromptExpiredError>()(
|
||||
"DesktopSshPromptExpiredError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
export class DesktopSshPromptExpiredError extends Data.TaggedError("DesktopSshPromptExpiredError")<{
|
||||
readonly requestId: string;
|
||||
}> {
|
||||
override get message() {
|
||||
return "SSH password prompt expired. Try connecting again.";
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopSshPasswordPromptRequestError =
|
||||
| DesktopSshPromptRequestIdGenerationError
|
||||
| DesktopSshPromptUnavailableError
|
||||
| DesktopSshPromptWindowUnavailableError
|
||||
| DesktopSshPromptPresentationError
|
||||
| DesktopSshPromptSendError
|
||||
| DesktopSshPromptTimedOutError
|
||||
| DesktopSshPromptCancelledError
|
||||
| DesktopSshPromptWindowClosedError
|
||||
| DesktopSshPromptServiceStoppedError;
|
||||
| DesktopSshPromptCancelledError;
|
||||
|
||||
export type DesktopSshPasswordPromptResolveError =
|
||||
| DesktopSshPromptInvalidRequestIdError
|
||||
@@ -147,28 +107,28 @@ export type DesktopSshPasswordPromptError =
|
||||
| DesktopSshPasswordPromptRequestError
|
||||
| DesktopSshPasswordPromptResolveError;
|
||||
|
||||
export const DesktopSshPasswordPromptCancellation = Schema.Union([
|
||||
DesktopSshPromptCancelledError,
|
||||
DesktopSshPromptWindowClosedError,
|
||||
DesktopSshPromptServiceStoppedError,
|
||||
DesktopSshPromptTimedOutError,
|
||||
]);
|
||||
export type DesktopSshPasswordPromptCancellation = typeof DesktopSshPasswordPromptCancellation.Type;
|
||||
export function isDesktopSshPasswordPromptCancellation(
|
||||
error: unknown,
|
||||
): error is DesktopSshPromptCancelledError | DesktopSshPromptTimedOutError {
|
||||
return (
|
||||
error instanceof DesktopSshPromptCancelledError ||
|
||||
error instanceof DesktopSshPromptTimedOutError
|
||||
);
|
||||
}
|
||||
|
||||
export const isDesktopSshPasswordPromptCancellation = Schema.is(
|
||||
DesktopSshPasswordPromptCancellation,
|
||||
);
|
||||
export interface DesktopSshPasswordPromptsShape {
|
||||
readonly request: (
|
||||
request: SshPasswordRequest,
|
||||
) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
|
||||
readonly resolve: (
|
||||
input: DesktopSshPasswordPromptResolutionInput,
|
||||
) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
|
||||
readonly cancelPending: (reason: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopSshPasswordPrompts extends Context.Service<
|
||||
DesktopSshPasswordPrompts,
|
||||
{
|
||||
readonly request: (
|
||||
request: SshPasswordRequest,
|
||||
) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
|
||||
readonly resolve: (
|
||||
input: DesktopSshPasswordPromptResolutionInput,
|
||||
) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
|
||||
}
|
||||
DesktopSshPasswordPromptsShape
|
||||
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
|
||||
|
||||
interface PendingSshPasswordPrompt {
|
||||
@@ -177,7 +137,7 @@ interface PendingSshPasswordPrompt {
|
||||
readonly deferred: Deferred.Deferred<string, DesktopSshPasswordPromptRequestError>;
|
||||
}
|
||||
|
||||
export interface DesktopSshPasswordPromptsOptions {
|
||||
interface LayerOptions {
|
||||
readonly passwordPromptTimeoutMs?: number;
|
||||
}
|
||||
|
||||
@@ -201,16 +161,14 @@ const failPending = (
|
||||
error: DesktopSshPasswordPromptRequestError,
|
||||
) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid);
|
||||
|
||||
export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
options: DesktopSshPasswordPromptsOptions = {},
|
||||
) {
|
||||
const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
|
||||
const passwordPromptTimeoutMs =
|
||||
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
|
||||
|
||||
const cancelPending = () =>
|
||||
const cancelPending = (reason: string): Effect.Effect<void> =>
|
||||
Ref.getAndSet(pendingRef, new Map()).pipe(
|
||||
Effect.flatMap((pending) =>
|
||||
Effect.forEach(
|
||||
@@ -218,9 +176,10 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
(entry) =>
|
||||
failPending(
|
||||
entry,
|
||||
new DesktopSshPromptServiceStoppedError({
|
||||
new DesktopSshPromptCancelledError({
|
||||
requestId: entry.requestId,
|
||||
destination: entry.destination,
|
||||
reason,
|
||||
}),
|
||||
),
|
||||
{ discard: true },
|
||||
@@ -229,11 +188,13 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() => cancelPending().pipe(Effect.ignore));
|
||||
yield* Effect.addFinalizer(() =>
|
||||
cancelPending("SSH password prompt service stopped.").pipe(Effect.ignore),
|
||||
);
|
||||
|
||||
const resolve: DesktopSshPasswordPrompts["Service"]["resolve"] = Effect.fn(
|
||||
"desktop.sshPasswordPrompts.resolve",
|
||||
)(function* (input) {
|
||||
const resolve = Effect.fn("desktop.sshPasswordPrompts.resolve")(function* (
|
||||
input: DesktopSshPasswordPromptResolutionInput,
|
||||
): Effect.fn.Return<void, DesktopSshPasswordPromptResolveError> {
|
||||
const requestId = input.requestId.trim();
|
||||
if (requestId.length === 0) {
|
||||
return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId });
|
||||
@@ -251,6 +212,7 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
new DesktopSshPromptCancelledError({
|
||||
requestId,
|
||||
destination: entry.destination,
|
||||
reason: `SSH authentication cancelled for ${entry.destination}.`,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
@@ -259,9 +221,9 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid);
|
||||
});
|
||||
|
||||
const request: DesktopSshPasswordPrompts["Service"]["request"] = Effect.fn(
|
||||
"desktop.sshPasswordPrompts.request",
|
||||
)(function* (input) {
|
||||
const request = Effect.fn("desktop.sshPasswordPrompts.request")(function* (
|
||||
input: SshPasswordRequest,
|
||||
): Effect.fn.Return<string, DesktopSshPasswordPromptRequestError> {
|
||||
const window = yield* electronWindow.main;
|
||||
if (Option.isNone(window) || window.value.isDestroyed()) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
@@ -271,11 +233,7 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
|
||||
const requestId = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSshPromptRequestIdGenerationError({
|
||||
destination: input.destination,
|
||||
cause,
|
||||
}),
|
||||
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
|
||||
),
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
@@ -309,9 +267,10 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
onSome: (pending) =>
|
||||
failPending(
|
||||
pending,
|
||||
new DesktopSshPromptWindowClosedError({
|
||||
new DesktopSshPromptCancelledError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
reason: "SSH authentication was cancelled because the app window closed.",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
@@ -343,43 +302,36 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
return yield* Effect.try({
|
||||
try: () => {
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
});
|
||||
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
|
||||
}
|
||||
window.value.once("closed", cancelOnWindowClosed);
|
||||
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
|
||||
window.value.webContents.send(IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
});
|
||||
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
|
||||
}
|
||||
if (window.value.isMinimized()) {
|
||||
window.value.restore();
|
||||
}
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
});
|
||||
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
|
||||
}
|
||||
window.value.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
isDesktopSshPromptWindowUnavailableError(cause)
|
||||
? cause
|
||||
: new DesktopSshPromptPresentationError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
cause,
|
||||
}),
|
||||
new DesktopSshPromptSendError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
return DesktopSshPasswordPrompts.of({
|
||||
request,
|
||||
resolve,
|
||||
cancelPending,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = (options: DesktopSshPasswordPromptsOptions = {}) =>
|
||||
export const layer = (options: LayerOptions = {}) =>
|
||||
Layer.effect(DesktopSshPasswordPrompts, make(options));
|
||||
@@ -83,7 +83,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
} satisfies ElectronUpdater.ElectronUpdaterShape);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
@@ -99,7 +99,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
} satisfies ElectronWindow.ElectronWindowShape);
|
||||
|
||||
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -59,26 +60,23 @@ const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressIn
|
||||
|
||||
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
|
||||
export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<DesktopUpdateActionInProgressError>()(
|
||||
export class DesktopUpdateActionInProgressError extends Data.TaggedError(
|
||||
"DesktopUpdateActionInProgressError",
|
||||
{
|
||||
action: Schema.Literals(["check", "download", "install"]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly action: "check" | "download" | "install";
|
||||
}> {
|
||||
override get message() {
|
||||
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
|
||||
export class DesktopUpdatePersistenceError extends Data.TaggedError(
|
||||
"DesktopUpdatePersistenceError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
|
||||
return `Failed to persist desktop update settings: ${detail}`;
|
||||
)<{
|
||||
readonly cause: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to persist desktop update settings.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,21 +86,22 @@ export type DesktopUpdateSetChannelError =
|
||||
| DesktopUpdateActionInProgressError
|
||||
| DesktopUpdatePersistenceError;
|
||||
|
||||
export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopUpdateState>;
|
||||
readonly emitState: Effect.Effect<void>;
|
||||
readonly disabledReason: Effect.Effect<Option.Option<string>>;
|
||||
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
|
||||
readonly setChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
|
||||
readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
|
||||
readonly download: Effect.Effect<DesktopUpdateActionResult>;
|
||||
readonly install: Effect.Effect<DesktopUpdateActionResult>;
|
||||
}
|
||||
>()("@t3tools/desktop/updates/DesktopUpdates") {}
|
||||
export interface DesktopUpdatesShape {
|
||||
readonly getState: Effect.Effect<DesktopUpdateState>;
|
||||
readonly emitState: Effect.Effect<void>;
|
||||
readonly disabledReason: Effect.Effect<Option.Option<string>>;
|
||||
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
|
||||
readonly setChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
|
||||
readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
|
||||
readonly download: Effect.Effect<DesktopUpdateActionResult>;
|
||||
readonly install: Effect.Effect<DesktopUpdateActionResult>;
|
||||
}
|
||||
|
||||
export class DesktopUpdates extends Context.Service<DesktopUpdates, DesktopUpdatesShape>()(
|
||||
"@t3tools/desktop/updates/DesktopUpdates",
|
||||
) {}
|
||||
|
||||
const {
|
||||
logInfo: logUpdaterInfo,
|
||||
@@ -128,7 +127,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
|
||||
function createBaseUpdateState(
|
||||
channel: DesktopUpdateChannel,
|
||||
enabled: boolean,
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
environment: DesktopEnvironment.DesktopEnvironmentShape,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
|
||||
@@ -186,7 +185,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
|
||||
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
|
||||
@@ -46,14 +46,14 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
} satisfies ElectronApp.ElectronAppShape);
|
||||
|
||||
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
pickFolder: () => Effect.succeed(Option.none()),
|
||||
confirm: () => Effect.succeed(false),
|
||||
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
|
||||
showErrorBox: () => Effect.void,
|
||||
} satisfies ElectronDialog.ElectronDialog["Service"]);
|
||||
} satisfies ElectronDialog.ElectronDialogShape);
|
||||
|
||||
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
@@ -64,7 +64,7 @@ const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
|
||||
check: () => Effect.die("unexpected check"),
|
||||
download: Effect.die("unexpected download"),
|
||||
install: Effect.die("unexpected install"),
|
||||
} satisfies DesktopUpdates.DesktopUpdates["Service"]);
|
||||
} satisfies DesktopUpdates.DesktopUpdatesShape);
|
||||
|
||||
const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
@@ -76,7 +76,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
handleBackendReady: Effect.void,
|
||||
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]);
|
||||
} satisfies DesktopWindow.DesktopWindowShape);
|
||||
|
||||
const makeElectronMenuLayer = (
|
||||
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
|
||||
@@ -86,7 +86,7 @@ const makeElectronMenuLayer = (
|
||||
Deferred.succeed(applicationMenuTemplate, template).pipe(Effect.asVoid),
|
||||
popupTemplate: () => Effect.void,
|
||||
showContextMenu: () => Effect.succeed(Option.none()),
|
||||
} satisfies ElectronMenu.ElectronMenu["Service"]);
|
||||
} satisfies ElectronMenu.ElectronMenuShape);
|
||||
|
||||
describe("DesktopApplicationMenu", () => {
|
||||
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
|
||||
|
||||
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import { makeComponentLogger } from "../app/DesktopObservability.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
@@ -14,11 +14,13 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
|
||||
export interface DesktopApplicationMenuShape {
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopApplicationMenu extends Context.Service<
|
||||
DesktopApplicationMenu,
|
||||
{
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
DesktopApplicationMenuShape
|
||||
>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
|
||||
|
||||
type DesktopApplicationMenuRuntimeServices =
|
||||
@@ -26,9 +28,9 @@ type DesktopApplicationMenuRuntimeServices =
|
||||
| DesktopWindow.DesktopWindow
|
||||
| ElectronDialog.ElectronDialog;
|
||||
|
||||
const { logInfo: logUpdaterInfo } = makeComponentLogger("desktop-updater");
|
||||
const { logInfo: logUpdaterInfo } = DesktopObservability.makeComponentLogger("desktop-updater");
|
||||
|
||||
const { logError: logMenuError } = makeComponentLogger("desktop-menu");
|
||||
const { logError: logMenuError } = DesktopObservability.makeComponentLogger("desktop-menu");
|
||||
|
||||
const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function* (
|
||||
action: string,
|
||||
@@ -37,7 +39,11 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
|
||||
yield* desktopWindow.dispatchMenuAction(action);
|
||||
});
|
||||
|
||||
const checkForUpdatesFromMenu = Effect.gen(function* () {
|
||||
const checkForUpdatesFromMenu: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
DesktopUpdates.DesktopUpdates | ElectronDialog.ElectronDialog
|
||||
> = Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
const result = yield* updates.check("menu");
|
||||
@@ -61,7 +67,11 @@ const checkForUpdatesFromMenu = Effect.gen(function* () {
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.menu.checkForUpdates"));
|
||||
|
||||
const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
|
||||
const handleCheckForUpdatesMenuClick: Effect.Effect<
|
||||
void,
|
||||
DesktopWindow.DesktopWindowError,
|
||||
DesktopUpdates.DesktopUpdates | ElectronDialog.ElectronDialog | DesktopWindow.DesktopWindow
|
||||
> = Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
const disabledReason = yield* updates.disabledReason;
|
||||
@@ -84,7 +94,7 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
|
||||
yield* checkForUpdatesFromMenu;
|
||||
}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
|
||||
@@ -91,7 +91,7 @@ const desktopAssetsLayer = Layer.succeed(DesktopAssets.DesktopAssets, {
|
||||
png: Option.none<string>(),
|
||||
}),
|
||||
resolveResourcePath: () => Effect.succeed(Option.none<string>()),
|
||||
} satisfies DesktopAssets.DesktopAssets["Service"]);
|
||||
} satisfies DesktopAssets.DesktopAssetsShape);
|
||||
|
||||
const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
@@ -106,19 +106,19 @@ const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopSe
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.die("unexpected getAdvertisedEndpoints"),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
} satisfies DesktopServerExposure.DesktopServerExposureShape);
|
||||
|
||||
const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
|
||||
setApplicationMenu: () => Effect.void,
|
||||
popupTemplate: () => Effect.void,
|
||||
showContextMenu: () => Effect.succeed(Option.none()),
|
||||
} satisfies ElectronMenu.ElectronMenu["Service"]);
|
||||
} satisfies ElectronMenu.ElectronMenuShape);
|
||||
|
||||
const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
|
||||
shouldUseDarkColors: Effect.succeed(false),
|
||||
setSource: () => Effect.void,
|
||||
onUpdated: () => Effect.void,
|
||||
} satisfies ElectronTheme.ElectronTheme["Service"]);
|
||||
} satisfies ElectronTheme.ElectronThemeShape);
|
||||
|
||||
const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe(
|
||||
Layer.provide(
|
||||
@@ -156,7 +156,7 @@ function makeTestLayer(input: {
|
||||
sendAll: () => Effect.void,
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: (sync) => sync(input.window),
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
} satisfies ElectronWindow.ElectronWindowShape);
|
||||
|
||||
return DesktopWindow.layer.pipe(
|
||||
Layer.provide(
|
||||
@@ -173,7 +173,7 @@ function makeTestLayer(input: {
|
||||
return true;
|
||||
}),
|
||||
copyText: () => Effect.void,
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
} satisfies ElectronShell.ElectronShellShape),
|
||||
electronThemeLayer,
|
||||
electronWindowLayer,
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
|
||||
@@ -8,15 +8,15 @@ import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "../app/DesktopObservability.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
@@ -42,22 +42,23 @@ export type DesktopWindowError =
|
||||
| ElectronWindow.ElectronWindowCreateError
|
||||
| PreviewManager.PreviewManagerError;
|
||||
|
||||
export class DesktopWindow extends Context.Service<
|
||||
DesktopWindow,
|
||||
{
|
||||
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly activate: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/window/DesktopWindow") {}
|
||||
export interface DesktopWindowShape {
|
||||
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly activate: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowShape>()(
|
||||
"@t3tools/desktop/window/DesktopWindow",
|
||||
) {}
|
||||
|
||||
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
|
||||
makeComponentLogger("desktop-window");
|
||||
DesktopObservability.makeComponentLogger("desktop-window");
|
||||
|
||||
function getIconOption(
|
||||
iconPaths: DesktopAssets.DesktopIconPaths,
|
||||
@@ -142,7 +143,7 @@ function bindFirstRevealTrigger(
|
||||
}
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const assets = yield* DesktopAssets.DesktopAssets;
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
@@ -380,7 +381,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||
targetWindow.webContents.send(IpcChannels.MENU_ACTION_CHANNEL, action);
|
||||
void runPromise(electronWindow.reveal(targetWindow));
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
included:
|
||||
- ios/T3Code
|
||||
- modules/t3-composer-editor/ios
|
||||
- modules/t3-terminal/ios
|
||||
- modules/t3-review-diff/ios
|
||||
|
||||
|
||||
+1
-21
@@ -192,31 +192,11 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ─── Typography ────────────────────────────────────────────────────── */
|
||||
/* ─── Font family ───────────────────────────────────────────────────── */
|
||||
@theme {
|
||||
--font-sans: "DMSans_400Regular";
|
||||
--font-medium: "DMSans_500Medium";
|
||||
--font-bold: "DMSans_700Bold";
|
||||
|
||||
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
|
||||
--text-3xs: 10px;
|
||||
--text-3xs--line-height: 13px;
|
||||
--text-2xs: 11px;
|
||||
--text-2xs--line-height: 15px;
|
||||
--text-xs: 12px;
|
||||
--text-xs--line-height: 16px;
|
||||
--text-sm: 13px;
|
||||
--text-sm--line-height: 18px;
|
||||
--text-base: 15px;
|
||||
--text-base--line-height: 22px;
|
||||
--text-lg: 17px;
|
||||
--text-lg--line-height: 22px;
|
||||
--text-xl: 20px;
|
||||
--text-xl--line-height: 26px;
|
||||
--text-2xl: 24px;
|
||||
--text-2xl--line-height: 30px;
|
||||
--text-3xl: 28px;
|
||||
--text-3xl--line-height: 34px;
|
||||
}
|
||||
|
||||
/* ─── Custom utilities ──────────────────────────────────────────────── */
|
||||
|
||||
@@ -275,8 +275,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
fileTint: "#737373"
|
||||
)
|
||||
private var fontFamily = "DMSans_400Regular"
|
||||
private var fontSize: CGFloat = 14
|
||||
private var lineHeight: CGFloat = 20
|
||||
private var fontSize: CGFloat = 15
|
||||
private var lineHeight: CGFloat = 22
|
||||
private var contentInsetVertical: CGFloat = 0
|
||||
private var shouldAutoFocus = false
|
||||
private var didAutoFocus = false
|
||||
@@ -460,19 +460,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
guard !isApplyingControlledValue else {
|
||||
return
|
||||
}
|
||||
restoreBaseTypingAttributes()
|
||||
emitSelection()
|
||||
}
|
||||
|
||||
public func textView(
|
||||
_ textView: UITextView,
|
||||
shouldChangeTextIn range: NSRange,
|
||||
replacementText text: String
|
||||
) -> Bool {
|
||||
restoreBaseTypingAttributes()
|
||||
return true
|
||||
}
|
||||
|
||||
public func textViewDidBeginEditing(_ textView: UITextView) {
|
||||
onComposerFocus()
|
||||
}
|
||||
@@ -494,7 +484,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
let targetSelection = requestedSelection ?? previousSelection
|
||||
requestedSelection = nil
|
||||
textView.selectedRange = displayRange(for: targetSelection)
|
||||
restoreBaseTypingAttributes()
|
||||
isApplyingControlledValue = false
|
||||
updatePlaceholderVisibility()
|
||||
emitContentSizeIfNeeded()
|
||||
@@ -567,12 +556,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
size: image.size,
|
||||
baselineOffset: baselineOffset
|
||||
)
|
||||
let attributedAttachment = NSMutableAttributedString(attachment: attachment)
|
||||
attributedAttachment.addAttributes(
|
||||
baseAttributes(),
|
||||
range: NSRange(location: 0, length: attributedAttachment.length)
|
||||
)
|
||||
return attributedAttachment
|
||||
return NSAttributedString(attachment: attachment)
|
||||
}
|
||||
|
||||
private func renderChip(
|
||||
@@ -676,18 +660,11 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
let font = UIFont(name: fontFamily, size: fontSize)
|
||||
?? UIFont.systemFont(ofSize: fontSize)
|
||||
textView.font = font
|
||||
restoreBaseTypingAttributes()
|
||||
textView.typingAttributes = baseAttributes()
|
||||
placeholderLabel.font = font
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
private func restoreBaseTypingAttributes() {
|
||||
guard textView.markedTextRange == nil else {
|
||||
return
|
||||
}
|
||||
textView.typingAttributes = baseAttributes()
|
||||
}
|
||||
|
||||
private func applyTheme() {
|
||||
textView.textColor = UIColor(composerHex: theme.text) ?? .label
|
||||
placeholderLabel.textColor = UIColor(composerHex: theme.placeholder) ?? .placeholderText
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { getBuiltInSpriteSheet } from "@pierre/trees";
|
||||
|
||||
const scriptDirectory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const moduleDirectory = NodePath.resolve(scriptDirectory, "..");
|
||||
const repositoryRoot = NodePath.resolve(moduleDirectory, "../../../..");
|
||||
const outputDirectory = NodePath.join(moduleDirectory, "assets/file-icons");
|
||||
const generatedModulePath = NodePath.join(moduleDirectory, "src/markdownFileIcons.generated.ts");
|
||||
const webIconSource = NodeFS.readFileSync(
|
||||
NodePath.join(repositoryRoot, "apps/web/src/pierre-icons.ts"),
|
||||
"utf8",
|
||||
);
|
||||
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
|
||||
const moduleDirectory = resolve(scriptDirectory, "..");
|
||||
const repositoryRoot = resolve(moduleDirectory, "../../../..");
|
||||
const outputDirectory = join(moduleDirectory, "assets/file-icons");
|
||||
const generatedModulePath = join(moduleDirectory, "src/markdownFileIcons.generated.ts");
|
||||
const webIconSource = readFileSync(join(repositoryRoot, "apps/web/src/pierre-icons.ts"), "utf8");
|
||||
const customSprite = webIconSource.match(/const T3_FILE_ICON_SPRITE = `([\s\S]*?)`;/)?.[1];
|
||||
|
||||
if (!customSprite) {
|
||||
@@ -98,20 +95,20 @@ function symbolFromSprite(sprite, id) {
|
||||
}
|
||||
|
||||
function renderIcon(token, symbol, color) {
|
||||
const svgPath = NodePath.join(outputDirectory, `.pierre-${token}.svg`);
|
||||
const pngPath = NodePath.join(outputDirectory, `pierre_${token}.png`);
|
||||
NodeFS.writeFileSync(
|
||||
const svgPath = join(outputDirectory, `.pierre-${token}.svg`);
|
||||
const pngPath = join(outputDirectory, `pierre_${token}.png`);
|
||||
writeFileSync(
|
||||
svgPath,
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="${symbol.viewBox}" style="color:${color}">${symbol.body}</svg>`,
|
||||
);
|
||||
NodeChildProcess.execFileSync("sips", ["-s", "format", "png", svgPath, "--out", pngPath], {
|
||||
execFileSync("sips", ["-s", "format", "png", svgPath, "--out", pngPath], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
NodeFS.rmSync(svgPath);
|
||||
rmSync(svgPath);
|
||||
}
|
||||
|
||||
NodeFS.rmSync(outputDirectory, { recursive: true, force: true });
|
||||
NodeFS.mkdirSync(outputDirectory, { recursive: true });
|
||||
rmSync(outputDirectory, { recursive: true, force: true });
|
||||
mkdirSync(outputDirectory, { recursive: true });
|
||||
|
||||
const builtInSprite = getBuiltInSpriteSheet("complete");
|
||||
const builtInTokens = [...builtInSprite.matchAll(/<symbol id="file-tree-builtin-([^"]+)"/g)]
|
||||
@@ -133,4 +130,4 @@ const tokens = [...new Set([...builtInTokens, ...Object.keys(customIcons)])].sor
|
||||
const generatedSource = `import type { ImageSourcePropType } from "react-native";\n\nexport const MARKDOWN_FILE_ICON_SOURCES = {\n${tokens
|
||||
.map((token) => ` ${token}: require("../assets/file-icons/pierre_${token}.png"),`)
|
||||
.join("\n")}\n} as const satisfies Readonly<Record<string, ImageSourcePropType>>;\n`;
|
||||
NodeFS.writeFileSync(generatedModulePath, generatedSource);
|
||||
writeFileSync(generatedModulePath, generatedSource);
|
||||
@@ -21,7 +21,7 @@ export default function NotFoundRoute() {
|
||||
}}
|
||||
style={[{ flex: 1 }, screenBgStyle]}
|
||||
>
|
||||
<Text className="text-3xl font-t3-bold text-foreground" selectable>
|
||||
<Text className="text-[28px] font-t3-bold text-foreground" selectable>
|
||||
Route not found
|
||||
</Text>
|
||||
<Link href="/" asChild>
|
||||
@@ -35,7 +35,7 @@ export default function NotFoundRoute() {
|
||||
primaryBgStyle,
|
||||
]}
|
||||
>
|
||||
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
|
||||
<Text className="text-[16px] font-t3-bold text-primary-foreground">Return home</Text>
|
||||
</Pressable>
|
||||
</Link>
|
||||
</ScrollView>
|
||||
|
||||
@@ -85,7 +85,7 @@ export default function ConnectionsRouteScreen() {
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
No environments connected yet.{"\n"}Tap{" "}
|
||||
<Text className="font-t3-bold text-foreground">+</Text> to add one.
|
||||
</Text>
|
||||
|
||||
@@ -171,7 +171,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
Camera permission is required to scan a QR code.
|
||||
</Text>
|
||||
<ConnectionSheetButton
|
||||
@@ -189,7 +189,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
|
||||
<View collapsable={false} className="gap-1.5">
|
||||
<Text
|
||||
className="text-2xs font-t3-bold uppercase text-foreground-muted"
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.8 }}
|
||||
>
|
||||
Host
|
||||
@@ -202,13 +202,13 @@ export default function ConnectionsNewRouteScreen() {
|
||||
placeholderTextColor={placeholderColor}
|
||||
value={hostInput}
|
||||
onChangeText={handleHostChange}
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View collapsable={false} className="gap-1.5">
|
||||
<Text
|
||||
className="text-2xs font-t3-bold uppercase text-foreground-muted"
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.8 }}
|
||||
>
|
||||
Pairing code
|
||||
@@ -220,7 +220,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
placeholderTextColor={placeholderColor}
|
||||
value={codeInput}
|
||||
onChangeText={handleCodeChange}
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
|
||||
/>
|
||||
</View>
|
||||
|
||||
|
||||
@@ -129,10 +129,10 @@ export default function NewTaskRoute() {
|
||||
{items.length === 0 ? (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
|
||||
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
|
||||
<Text className="text-center text-lg font-t3-bold text-foreground">
|
||||
<Text className="text-center text-[17px] font-t3-bold text-foreground">
|
||||
{projectEmptyState.title}
|
||||
</Text>
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
{projectEmptyState.detail}
|
||||
</Text>
|
||||
{!catalogState.hasReadyEnvironment ? (
|
||||
@@ -140,7 +140,7 @@ export default function NewTaskRoute() {
|
||||
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={() => router.push("/connections/new")}
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
Add environment
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -149,7 +149,7 @@ export default function NewTaskRoute() {
|
||||
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={() => router.push("/new/add-project")}
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
Add new project
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -197,7 +197,9 @@ export default function NewTaskRoute() {
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<Text className="text-base leading-[21px] font-t3-bold">{item.title}</Text>
|
||||
<Text className="text-[16px] leading-[21px] font-t3-bold">
|
||||
{item.title}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
|
||||
@@ -111,7 +111,7 @@ export default function SettingsEnvironmentsRouteScreen() {
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
No environments connected yet.{"\n"}Tap{" "}
|
||||
<Text className="font-t3-bold text-foreground">+</Text> to add one.
|
||||
</Text>
|
||||
@@ -160,7 +160,7 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
return (
|
||||
<View collapsable={false} className="mt-5 gap-3">
|
||||
<View className="flex-row items-center justify-between px-1">
|
||||
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
|
||||
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
@@ -204,16 +204,16 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
) : controller.relayDiscovery.isRefreshing ? (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
|
||||
<ActivityIndicator color={iconColor} />
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
Loading linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
) : controller.relayDiscovery.error ? (
|
||||
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
|
||||
<Text className="text-base font-t3-bold text-foreground">
|
||||
<Text className="text-[15px] font-t3-bold text-foreground">
|
||||
Could not load T3 Cloud environments
|
||||
</Text>
|
||||
<Text className="text-sm leading-[18px] text-foreground-muted">
|
||||
<Text className="text-[13px] leading-[18px] text-foreground-muted">
|
||||
{controller.relayDiscovery.error}
|
||||
</Text>
|
||||
{controller.relayDiscovery.errorTraceId ? (
|
||||
@@ -222,7 +222,7 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="rounded-[24px] bg-card p-5">
|
||||
<Text className="text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-[14px] leading-[20px] text-foreground-muted">
|
||||
No additional linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
@@ -361,7 +361,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
<View className="min-w-0 flex-row items-center gap-2">
|
||||
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
|
||||
<Text
|
||||
className="min-w-0 flex-shrink text-base font-t3-bold leading-[21px] text-foreground"
|
||||
className="min-w-0 flex-shrink text-[16px] font-t3-bold leading-[21px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
@@ -370,7 +370,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
{props.connectionError ? (
|
||||
<Text
|
||||
aria-hidden
|
||||
className={cn("absolute left-0 right-0 text-xs leading-[16px]", statusClassName)}
|
||||
className={cn("absolute left-0 right-0 text-[12px] leading-[16px]", statusClassName)}
|
||||
onTextLayout={onMeasuredErrorTextLayout}
|
||||
style={{ opacity: 0, zIndex: -1 }}
|
||||
>
|
||||
@@ -384,7 +384,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
className="min-w-0 flex-row items-start gap-1"
|
||||
>
|
||||
<Text
|
||||
className={cn("min-w-0 flex-1 text-xs leading-[16px]", statusClassName)}
|
||||
className={cn("min-w-0 flex-1 text-[12px] leading-[16px]", statusClassName)}
|
||||
numberOfLines={isErrorExpanded ? undefined : 1}
|
||||
>
|
||||
{statusText}
|
||||
@@ -394,7 +394,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
<Text
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className={cn("text-xs leading-[16px] underline", statusClassName)}
|
||||
className={cn("text-[12px] leading-[16px] underline", statusClassName)}
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(errorTraceId);
|
||||
@@ -446,7 +446,7 @@ function CopyTraceIdButton(props: { readonly traceId: string }) {
|
||||
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
|
||||
>
|
||||
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
|
||||
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
|
||||
<Text className="text-[12px] font-t3-bold text-foreground">Copy trace ID</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -346,7 +346,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
onPress={openAccount}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm leading-[18px] text-foreground-muted">
|
||||
<Text className="px-2 text-[13px] leading-[18px] text-foreground-muted">
|
||||
T3 Code works locally without signing in. Cloud features are optional.
|
||||
</Text>
|
||||
</View>
|
||||
@@ -389,7 +389,7 @@ type SymbolName = ComponentProps<typeof SymbolView>["name"];
|
||||
function SettingsSection(props: { readonly title: string; readonly children: ReactNode }) {
|
||||
return (
|
||||
<View className="gap-2">
|
||||
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">{props.title}</Text>
|
||||
<Text className="px-2 text-[13px] font-t3-medium text-foreground-muted">{props.title}</Text>
|
||||
<View
|
||||
className="overflow-hidden rounded-[28px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
@@ -413,8 +413,8 @@ function AppSettingsSection() {
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-lg text-foreground">Version</Text>
|
||||
<Text className="text-lg text-foreground-muted">Alpha</Text>
|
||||
<Text className="flex-1 text-[17px] text-foreground">Version</Text>
|
||||
<Text className="text-[17px] text-foreground-muted">Alpha</Text>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
);
|
||||
@@ -444,13 +444,13 @@ function SettingsRow(props: {
|
||||
style={{ opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
|
||||
<Text className="shrink-0 text-lg text-foreground" numberOfLines={1}>
|
||||
<Text className="shrink-0 text-[17px] text-foreground" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
<View className="min-w-0 flex-1 items-end">
|
||||
{props.value ? (
|
||||
<Text
|
||||
className="max-w-[180px] text-right text-base text-foreground-muted"
|
||||
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
@@ -502,7 +502,7 @@ function SettingsSwitchRow(props: {
|
||||
style={{ opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
|
||||
<Text className="flex-1 text-lg text-foreground">{props.label}</Text>
|
||||
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
ios_backgroundColor={track}
|
||||
|
||||
@@ -40,7 +40,7 @@ export function AppTextInput({
|
||||
<RNTextInput
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
|
||||
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-[15px] text-foreground",
|
||||
className,
|
||||
)}
|
||||
placeholderTextColor={placeholderTextColor ?? placeholderColor}
|
||||
|
||||
@@ -22,12 +22,15 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
|
||||
/>
|
||||
<View className="gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text className="text-lg font-t3-bold text-foreground" style={{ letterSpacing: -0.4 }}>
|
||||
<Text
|
||||
className="text-[17px] font-t3-bold text-foreground"
|
||||
style={{ letterSpacing: -0.4 }}
|
||||
>
|
||||
T3 Code
|
||||
</Text>
|
||||
<View className="rounded-full bg-subtle px-2 py-1">
|
||||
<Text
|
||||
className="text-3xs font-t3-bold uppercase text-foreground-muted"
|
||||
className="text-[10px] font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 1.1 }}
|
||||
>
|
||||
{stageLabel}
|
||||
@@ -35,7 +38,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
|
||||
</View>
|
||||
</View>
|
||||
{!compact ? (
|
||||
<Text className="text-xs font-medium text-foreground-muted">
|
||||
<Text className="text-[12px] font-medium text-foreground-muted">
|
||||
Mobile control surface for your live coding environments
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
@@ -223,7 +223,7 @@ export function ComposerToolbarButton(props: {
|
||||
{props.label ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"shrink text-center text-sm font-t3-bold",
|
||||
"shrink text-center text-[13px] font-t3-bold",
|
||||
variant === "primary"
|
||||
? props.disabled
|
||||
? "text-foreground-muted"
|
||||
|
||||
@@ -48,7 +48,7 @@ export function ControlPill(props: {
|
||||
: "bg-subtle",
|
||||
);
|
||||
const labelClassName = cn(
|
||||
"text-center text-xs font-t3-bold",
|
||||
"text-center text-[12px] font-t3-bold",
|
||||
variant === "primary"
|
||||
? props.disabled
|
||||
? "text-foreground-muted"
|
||||
|
||||
@@ -19,7 +19,9 @@ export function EmptyState(props: {
|
||||
className="mt-4 self-start rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={props.onAction}
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">{props.actionLabel}</Text>
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
{props.actionLabel}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { AppText as Text } from "./AppText";
|
||||
export function ErrorBanner(props: { readonly message: string }) {
|
||||
return (
|
||||
<View className="rounded-2xl border border-rose-300/70 bg-rose-100/80 px-3.5 py-3 dark:border-rose-400/28 dark:bg-rose-500/12">
|
||||
<Text className="font-t3-medium text-sm leading-[18px] text-rose-700 dark:text-rose-300">
|
||||
<Text className="font-t3-medium text-[13px] leading-[18px] text-rose-700 dark:text-rose-300">
|
||||
{props.message}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
@@ -26,7 +26,7 @@ export function StatusPill(
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-bold",
|
||||
size === "compact" ? "text-2xs" : "text-xs",
|
||||
size === "compact" ? "text-[11px]" : "text-xs",
|
||||
props.textClassName,
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -18,7 +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: ${String(cause)}`,
|
||||
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
import {
|
||||
ConnectionBlockedError,
|
||||
ConnectionTransientError,
|
||||
ConnectionWakeups,
|
||||
Connectivity,
|
||||
Wakeups,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
|
||||
import { AuthStandardClientScopes } from "@t3tools/contracts";
|
||||
@@ -41,47 +41,53 @@ function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "on
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const connectivityLayer = Connectivity.layer({
|
||||
status: Effect.tryPromise({
|
||||
try: () => Network.getNetworkStateAsync(),
|
||||
catch: () => undefined,
|
||||
}).pipe(
|
||||
Effect.match({
|
||||
onFailure: () => "unknown" as const,
|
||||
onSuccess: networkStatus,
|
||||
}),
|
||||
),
|
||||
changes: Stream.callback((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
Network.addNetworkStateListener((state) => {
|
||||
Queue.offerUnsafe(queue, networkStatus(state));
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
});
|
||||
|
||||
const wakeupsLayer = Wakeups.layer({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active">((queue) =>
|
||||
const connectivityLayer = Layer.succeed(
|
||||
Connectivity,
|
||||
Connectivity.of({
|
||||
status: Effect.tryPromise({
|
||||
try: () => Network.getNetworkStateAsync(),
|
||||
catch: () => undefined,
|
||||
}).pipe(
|
||||
Effect.match({
|
||||
onFailure: () => "unknown" as const,
|
||||
onSuccess: networkStatus,
|
||||
}),
|
||||
),
|
||||
changes: Stream.callback((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
Queue.offerUnsafe(queue, "application-active");
|
||||
}
|
||||
Network.addNetworkStateListener((state) => {
|
||||
Queue.offerUnsafe(queue, networkStatus(state));
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
}),
|
||||
);
|
||||
|
||||
const wakeupsLayer = Layer.succeed(
|
||||
ConnectionWakeups,
|
||||
ConnectionWakeups.of({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
Queue.offerUnsafe(queue, "application-active");
|
||||
}
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const capabilitiesLayer = Layer.succeedContext(
|
||||
Context.make(
|
||||
@@ -92,7 +98,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
if (session === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "Sign in to T3 Cloud to connect this environment.",
|
||||
message: "Sign in to T3 Cloud to connect this environment.",
|
||||
});
|
||||
}
|
||||
const token = yield* session.readClerkToken().pipe(
|
||||
@@ -100,14 +106,14 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
(error) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "network",
|
||||
detail: error.message,
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (token === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
message: "The T3 Cloud session is unavailable.",
|
||||
});
|
||||
}
|
||||
return token;
|
||||
@@ -126,7 +132,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not load the mobile device identity: ${String(cause)}`,
|
||||
message: `Could not load the mobile device identity: ${String(cause)}`,
|
||||
}),
|
||||
}).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
@@ -145,14 +151,14 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
Effect.fail(
|
||||
new ConnectionBlockedError({
|
||||
reason: "unsupported",
|
||||
detail: "SSH environments are only available in the desktop app.",
|
||||
message: "SSH environments are only available in the desktop app.",
|
||||
}),
|
||||
),
|
||||
prepare: () =>
|
||||
Effect.fail(
|
||||
new ConnectionBlockedError({
|
||||
reason: "unsupported",
|
||||
detail: "SSH environments are only available in the desktop app.",
|
||||
message: "SSH environments are only available in the desktop app.",
|
||||
}),
|
||||
),
|
||||
disconnect: () => Effect.void,
|
||||
@@ -189,19 +195,7 @@ const environmentOwnedDataCleanupLayer = Layer.succeed(
|
||||
}),
|
||||
);
|
||||
|
||||
type ConnectionPlatformLayerSource =
|
||||
| typeof connectionStorageLayer
|
||||
| typeof connectivityLayer
|
||||
| typeof wakeupsLayer
|
||||
| typeof capabilitiesLayer
|
||||
| typeof platformConnectionSourceLayer
|
||||
| typeof environmentOwnedDataCleanupLayer;
|
||||
|
||||
export const connectionPlatformLayer: Layer.Layer<
|
||||
Layer.Success<ConnectionPlatformLayerSource>,
|
||||
Layer.Error<ConnectionPlatformLayerSource>,
|
||||
Layer.Services<ConnectionPlatformLayerSource>
|
||||
> = Layer.mergeAll(
|
||||
export const connectionPlatformLayer = Layer.mergeAll(
|
||||
connectionStorageLayer,
|
||||
connectivityLayer,
|
||||
wakeupsLayer,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Connection } from "@t3tools/client-runtime/connection";
|
||||
import { connectionLayer as clientConnectionLayer } from "@t3tools/client-runtime/connection";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -9,16 +9,8 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
|
||||
type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
| typeof runtimeContextLayer
|
||||
| typeof connectionPlatformLayer;
|
||||
|
||||
const connectionLayer = Connection.layer.pipe(
|
||||
export const connectionLayer = clientConnectionLayer.pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
);
|
||||
|
||||
export const connectionAtomRuntime: Atom.AtomRuntime<
|
||||
Layer.Success<ConnectionLayerSource>,
|
||||
Layer.Error<ConnectionLayerSource>
|
||||
> = Atom.runtime(connectionLayer);
|
||||
export const connectionAtomRuntime = Atom.runtime(connectionLayer);
|
||||
@@ -8,11 +8,11 @@ import {
|
||||
removeCatalogValue,
|
||||
replaceCatalogValue,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { TokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import { RemoteDpopAccessTokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import {
|
||||
ConnectionCredentialStore,
|
||||
ConnectionProfileStore,
|
||||
ConnectionTransientError,
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
@@ -58,7 +58,7 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -197,7 +197,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
});
|
||||
const profileStore = ProfileStore.make({
|
||||
const profileStore = ConnectionProfileStore.of({
|
||||
get: (connectionId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
@@ -221,7 +221,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
})),
|
||||
});
|
||||
const credentialStore = CredentialStore.make({
|
||||
const credentialStore = ConnectionCredentialStore.of({
|
||||
get: (connectionId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
@@ -248,7 +248,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
})),
|
||||
});
|
||||
const remoteTokenStore = TokenStore.make({
|
||||
const remoteTokenStore = RemoteDpopAccessTokenStore.of({
|
||||
get: (environmentId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
@@ -423,9 +423,9 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
|
||||
return Context.make(ConnectionTargetStore, targetStore).pipe(
|
||||
Context.add(ConnectionRegistrationStore, registrationStore),
|
||||
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
|
||||
Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
|
||||
Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
|
||||
Context.add(ConnectionProfileStore, profileStore),
|
||||
Context.add(ConnectionCredentialStore, credentialStore),
|
||||
Context.add(RemoteDpopAccessTokenStore, remoteTokenStore),
|
||||
Context.add(EnvironmentCacheStore, cacheStore),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -2,7 +2,7 @@ import { beforeEach, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
@@ -35,7 +35,7 @@ const connection: SavedRemoteConnection = {
|
||||
};
|
||||
|
||||
const testLayer = Layer.mergeAll(
|
||||
Layer.succeed(ManagedRelay.ManagedRelayClient, null as never),
|
||||
Layer.succeed(ManagedRelayClient, null as never),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unexpected HTTP request")),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
|
||||
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { savePreferencesPatch } from "../../lib/storage";
|
||||
@@ -11,7 +11,7 @@ export function setLiveActivityUpdatesEnabled(input: {
|
||||
readonly enabled: boolean;
|
||||
readonly clerkToken: string | null;
|
||||
readonly connections: ReadonlyArray<SavedRemoteConnection>;
|
||||
}): Effect.Effect<void, unknown, HttpClient.HttpClient | ManagedRelay.ManagedRelayClient> {
|
||||
}): Effect.Effect<void, unknown, HttpClient.HttpClient | ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.tryPromise({
|
||||
try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }),
|
||||
|
||||
@@ -9,7 +9,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { type ManagedRelayClient } from "@t3tools/client-runtime/relay";
|
||||
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
@@ -158,7 +158,7 @@ const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundO
|
||||
}
|
||||
idlePasses = 0;
|
||||
const exit = yield* Effect.exit(
|
||||
pending.operation as Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
|
||||
pending.operation as Effect.Effect<unknown, unknown, ManagedRelayClient>,
|
||||
);
|
||||
yield* Effect.sync(() => {
|
||||
pending.resolve(exit);
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type RelayLiveActivityRegistrationRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
settleAsyncResult,
|
||||
@@ -175,7 +175,7 @@ const relayToken = Effect.gen(function* () {
|
||||
function registerDeviceWithRelay(
|
||||
body: RelayDeviceRegistrationRequest,
|
||||
expectedGeneration: number,
|
||||
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
logRegistrationDebug("device registration cancelled before relay request", {
|
||||
@@ -198,7 +198,7 @@ function registerDeviceWithRelay(
|
||||
return;
|
||||
}
|
||||
|
||||
const client = yield* ManagedRelay.ManagedRelayClient;
|
||||
const client = yield* ManagedRelayClient;
|
||||
logRegistrationDebug("relay device registration request started", {
|
||||
expectedGeneration,
|
||||
});
|
||||
@@ -215,7 +215,7 @@ function registerDeviceWithRelay(
|
||||
function unregisterDeviceWithRelay(input: {
|
||||
readonly deviceId: string;
|
||||
readonly tokenProvider: () => Promise<string | null>;
|
||||
}): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
}): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (!readRelayConfig()) return;
|
||||
const token = yield* Effect.tryPromise({
|
||||
@@ -227,7 +227,7 @@ function unregisterDeviceWithRelay(input: {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = yield* ManagedRelay.ManagedRelayClient;
|
||||
const client = yield* ManagedRelayClient;
|
||||
yield* client.unregisterDevice({
|
||||
clerkToken: token,
|
||||
deviceId: input.deviceId,
|
||||
@@ -237,7 +237,7 @@ function unregisterDeviceWithRelay(input: {
|
||||
|
||||
function registerLiveActivityWithRelay(
|
||||
body: RelayLiveActivityRegistrationRequest,
|
||||
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
): Effect.Effect<boolean, unknown, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (!readRelayConfig()) return false;
|
||||
const token = yield* relayToken;
|
||||
@@ -246,7 +246,7 @@ function registerLiveActivityWithRelay(
|
||||
return false;
|
||||
}
|
||||
|
||||
const client = yield* ManagedRelay.ManagedRelayClient;
|
||||
const client = yield* ManagedRelayClient;
|
||||
yield* client.registerLiveActivity({
|
||||
clerkToken: token,
|
||||
payload: body,
|
||||
@@ -274,7 +274,7 @@ function logRegistrationDebug(context: string, details?: unknown): void {
|
||||
}
|
||||
|
||||
function runRegistrationInBackground(
|
||||
operation: Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
|
||||
operation: Effect.Effect<unknown, unknown, ManagedRelayClient>,
|
||||
context: string,
|
||||
): void {
|
||||
void (async () => {
|
||||
@@ -370,7 +370,7 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri
|
||||
function registerDevice(
|
||||
input: DeviceRegistrationInput = {},
|
||||
expectedGeneration = deviceRegistrationGeneration,
|
||||
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (!canRegisterRemoteLiveActivities()) {
|
||||
logRegistrationDebug("device registration skipped; platform does not support it");
|
||||
@@ -411,7 +411,7 @@ function registerDevice(
|
||||
|
||||
function registerDeviceForCurrentUser(
|
||||
pushToStartToken?: string,
|
||||
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
return registerDevice(pushToStartToken ? { pushToStartToken } : undefined);
|
||||
}
|
||||
|
||||
@@ -485,7 +485,7 @@ export function unregisterAllAgentAwarenessConnections(): void {
|
||||
export function refreshAgentAwarenessRegistration(): Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ManagedRelay.ManagedRelayClient
|
||||
ManagedRelayClient
|
||||
> {
|
||||
return registerDeviceForCurrentUser().pipe(
|
||||
Effect.catch((error) =>
|
||||
@@ -515,7 +515,7 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
|
||||
|
||||
export function unregisterAgentAwarenessDeviceForCurrentUser(
|
||||
tokenProvider: () => Promise<string | null>,
|
||||
): Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> {
|
||||
): Effect.Effect<void, never, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadAgentAwarenessDeviceId(),
|
||||
@@ -536,7 +536,7 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(
|
||||
|
||||
export function registerLiveActivityPushToken(input: {
|
||||
readonly activity: LiveActivity<AgentActivityProps>;
|
||||
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
}): Effect.Effect<boolean, unknown, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (!canRegisterRemoteLiveActivities()) {
|
||||
return false;
|
||||
@@ -588,7 +588,7 @@ export function registerLiveActivityPushToken(input: {
|
||||
|
||||
function registerLiveActivityPushTokenValue(input: {
|
||||
readonly activityPushToken: string;
|
||||
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
}): Effect.Effect<boolean, unknown, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
@@ -624,7 +624,7 @@ function scheduleActiveLiveActivityRegistrationRetry(): void {
|
||||
export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ManagedRelay.ManagedRelayClient
|
||||
ManagedRelayClient
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
|
||||
|
||||
@@ -147,14 +147,14 @@ function ProjectGroupLabel(props: {
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
<Text
|
||||
className="flex-1 text-xs font-t3-medium uppercase text-foreground-muted"
|
||||
className="flex-1 text-[12px] font-t3-medium uppercase text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
style={{ letterSpacing: 0.5 }}
|
||||
>
|
||||
{props.project.title}
|
||||
</Text>
|
||||
{props.environmentLabel ? (
|
||||
<Text className="max-w-[42%] text-2xs text-foreground-tertiary" numberOfLines={1}>
|
||||
<Text className="max-w-[42%] text-[11px] text-foreground-tertiary" numberOfLines={1}>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
@@ -265,13 +265,13 @@ function ArchivedThreadRow(props: {
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
|
||||
className="min-w-0 flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-tertiary"
|
||||
className="text-[12px] text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
@@ -286,7 +286,7 @@ function ArchivedThreadRow(props: {
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
|
||||
className="min-w-0 flex-1 text-[11px] text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
@@ -314,12 +314,10 @@ function ArchivedThreadRow(props: {
|
||||
function ArchiveError(props: { readonly message: string; readonly onRetry: () => void }) {
|
||||
return (
|
||||
<View className="rounded-[20px] border border-danger-border bg-danger p-4">
|
||||
<Text className="text-base font-t3-bold text-danger-foreground">
|
||||
Could not load every archive
|
||||
</Text>
|
||||
<Text className="mt-1 text-sm leading-[18px] text-foreground-muted">{props.message}</Text>
|
||||
<Text className="font-t3-bold text-danger-foreground">Could not load every archive</Text>
|
||||
<Text className="mt-1 text-[13px] leading-[18px] text-foreground-muted">{props.message}</Text>
|
||||
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
|
||||
<Text className="text-sm font-t3-bold text-danger-foreground">Try again</Text>
|
||||
<Text className="text-[13px] font-t3-bold text-danger-foreground">Try again</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
@@ -388,7 +386,7 @@ export function ArchivedThreadsScreen(props: {
|
||||
{isInitialLoad ? (
|
||||
<View className="items-center py-16">
|
||||
<ActivityIndicator color={refreshTint} />
|
||||
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
|
||||
<Text className="mt-3 text-[13px] text-foreground-muted">Loading archive…</Text>
|
||||
</View>
|
||||
) : props.groups.length === 0 ? (
|
||||
<EmptyState
|
||||
|
||||
Loaded 100 of 577 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user