Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge ba5fd8459e Fix typed port scanner assertions
Co-authored-by: Julius Marminge <[email protected]>
2026-06-14 16:09:05 +00:00
Cursor AgentandJulius Marminge 5ea7466bd5 Refactor preview port scanner Effect patterns
Co-authored-by: Julius Marminge <[email protected]>
2026-06-14 16:06:09 +00:00
1530 changed files with 91397 additions and 127771 deletions

No files matched your search

-7
View File
@@ -8,13 +8,6 @@
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay # T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_... # T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
# returns a different RP ID or when multiple domains must be entitled.
# T3CODE_APPLE_TEAM_ID=ABC1234567
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# Get this from your relay deployment. `infra/relay` deploys update it automatically. # Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com # T3CODE_RELAY_URL=https://relay.example.com
+46 -1
View File
@@ -38,7 +38,6 @@ jobs:
run: | run: |
test -f apps/desktop/dist-electron/preload.cjs test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
test: test:
name: Test name: Test
@@ -61,6 +60,52 @@ jobs:
- name: Test - name: Test
run: vp run test run: vp run test
test_browser:
name: Test Browser
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install browser test runtime
run: vp run --filter @t3tools/web test:browser:install
- name: Browser test / Chat view
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
- name: Browser test / Chat markdown
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
- name: Browser test / Components
working-directory: apps/web
run: |
vp test run --mode browser --browser=chromium \
src/components/GitActionsControl.browser.tsx \
src/components/KeybindingsToast.browser.tsx \
src/components/ThreadTerminalDrawer.browser.tsx \
src/components/chat/MessagesTimeline.browser.tsx \
src/components/chat/ProviderModelPicker.browser.tsx \
src/components/chat/CompactComposerControlsMenu.browser.tsx \
src/components/settings/SettingsPanels.browser.tsx
mobile_native_static_analysis: mobile_native_static_analysis:
name: Mobile Native Static Analysis name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26 runs-on: blacksmith-12vcpu-macos-26
-2
View File
@@ -2,12 +2,10 @@ name: Mobile EAS Preview
on: on:
pull_request: pull_request:
types: [opened, reopened, synchronize, labeled, unlabeled]
jobs: jobs:
preview: preview:
name: EAS Preview name: EAS Preview
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
runs-on: blacksmith-8vcpu-ubuntu-2404 runs-on: blacksmith-8vcpu-ubuntu-2404
permissions: permissions:
contents: read contents: read
-94
View File
@@ -180,46 +180,12 @@ jobs:
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }} clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
relay_url: ${{ steps.public_config.outputs.relay_url }} relay_url: ${{ steps.public_config.outputs.relay_url }}
env: env:
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }} RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }} RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }} CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }} CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }} CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
steps: steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=t3code-relay...
- id: relay_state
name: Read production relay tracing config
shell: bash
run: |
vp run --filter t3code-relay deploy \
--stage prod \
--read-state \
--github-output \
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
- name: Upload relay client tracing config
uses: actions/upload-artifact@v7
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing.env
if-no-files-found: error
retention-days: 1
- id: public_config - id: public_config
name: Resolve production relay public config name: Resolve production relay public config
shell: bash shell: bash
@@ -306,20 +272,6 @@ jobs:
cache: true cache: true
run-install: true run-install: true
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version - name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}" run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -425,9 +377,6 @@ jobs:
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
@@ -455,21 +404,9 @@ jobs:
if [[ "${{ matrix.platform }}" == "mac" ]]; then if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
exit 1
fi
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8" key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path" printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path" export APPLE_API_KEY="$key_path"
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
security cms -D -i "$profile_path" >/dev/null
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
echo "macOS signing enabled." echo "macOS signing enabled."
args+=(--signed) args+=(--signed)
else else
@@ -571,20 +508,6 @@ jobs:
- --filter=@t3tools/web... - --filter=@t3tools/web...
- --filter=@t3tools/scripts... - --filter=@t3tools/scripts...
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version - name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}" run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -747,20 +670,6 @@ jobs:
- --filter=@t3tools/scripts... - --filter=@t3tools/scripts...
- --filter=@t3tools/web... - --filter=@t3tools/web...
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version - name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}" run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -807,9 +716,6 @@ jobs:
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \ --build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \ --build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \ --build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \ --build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name" --build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)" )"
@@ -1,83 +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.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- 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.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- 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.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## 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.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
-3
View File
@@ -12,8 +12,6 @@
"smoke-test": "node scripts/smoke-test.mjs" "smoke-test": "node scripts/smoke-test.mjs"
}, },
"dependencies": { "dependencies": {
"@clerk/electron": "catalog:",
"@clerk/electron-passkeys": "catalog:",
"@effect/platform-node": "catalog:", "@effect/platform-node": "catalog:",
"@t3tools/client-runtime": "workspace:*", "@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*", "@t3tools/contracts": "workspace:*",
@@ -22,7 +20,6 @@
"@t3tools/tailscale": "workspace:*", "@t3tools/tailscale": "workspace:*",
"effect": "catalog:", "effect": "catalog:",
"electron": "41.5.0", "electron": "41.5.0",
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2", "electron-updater": "^6.6.2",
"playwright-core": "1.60.0", "playwright-core": "1.60.0",
"react-grab": "^0.1.32" "react-grab": "^0.1.32"
@@ -1,23 +1,23 @@
import * as NodeFSP from "node:fs/promises"; import { readFile, writeFile } from "node:fs/promises";
import * as NodeModule from "node:module"; import { createRequire } from "node:module";
import * as NodePath from "node:path"; import { dirname, join } from "node:path";
import * as NodeURL from "node:url"; import { fileURLToPath } from "node:url";
import { compile } from "tailwindcss"; import { compile } from "tailwindcss";
const directory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); const directory = dirname(fileURLToPath(import.meta.url));
const appRoot = NodePath.join(directory, ".."); const appRoot = join(directory, "..");
const sourcePath = NodePath.join(appRoot, "src", "preview", "Annotation.css"); const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = NodePath.join(appRoot, "src", "preview", "PickPreload.ts"); const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = NodePath.join(appRoot, "src", "preview", "AnnotationStyles.generated.ts"); const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = NodeModule.createRequire(import.meta.url); const require = createRequire(import.meta.url);
const tailwindRoot = NodePath.dirname(require.resolve("tailwindcss/package.json")); const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([ const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
NodeFSP.readFile(sourcePath, "utf8"), readFile(sourcePath, "utf8"),
NodeFSP.readFile(preloadPath, "utf8"), readFile(preloadPath, "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "theme.css"), "utf8"), readFile(join(tailwindRoot, "theme.css"), "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "preflight.css"), "utf8"), readFile(join(tailwindRoot, "preflight.css"), "utf8"),
]); ]);
const candidates = new Set( const candidates = new Set(
@@ -37,4 +37,4 @@ const encodedCss = `'${css
.replaceAll("\n", "\\n")}'`; .replaceAll("\n", "\\n")}'`;
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\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);
+12 -19
View File
@@ -1,7 +1,6 @@
import * as NodeChildProcess from "node:child_process"; import { spawn, spawnSync } from "node:child_process";
import * as NodeFS from "node:fs"; import { watch } from "node:fs";
import * as NodeOS from "node:os"; import { join } from "node:path";
import * as NodePath from "node:path";
import { import {
desktopDir, desktopDir,
@@ -34,8 +33,6 @@ const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120; const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200; const childTreeGracePeriodMs = 1_200;
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim(); const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
const hostPlatform = NodeOS.platform();
await waitForResources({ await waitForResources({
baseDir: desktopDir, baseDir: desktopDir,
@@ -60,21 +57,19 @@ const expectedExits = new WeakSet();
const watchers = []; const watchers = [];
function killChildTreeByPid(pid, signal) { function killChildTreeByPid(pid, signal) {
if (hostPlatform === "win32" || typeof pid !== "number") { if (process.platform === "win32" || typeof pid !== "number") {
return; return;
} }
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" }); spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
} }
function cleanupStaleDevApps() { function cleanupStaleDevApps() {
if (hostPlatform === "win32") { if (process.platform === "win32") {
return; return;
} }
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
stdio: "ignore",
});
} }
function startApp() { function startApp() {
@@ -89,7 +84,7 @@ function startApp() {
? electronArgs ? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"]; : [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const electronCommand = resolveElectronLaunchCommand(launchArgs); const electronCommand = resolveElectronLaunchCommand(launchArgs);
const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, { const app = spawn(electronCommand.electronPath, electronCommand.args, {
cwd: desktopDir, cwd: desktopDir,
env: childEnv, env: childEnv,
stdio: "inherit", stdio: "inherit",
@@ -182,8 +177,8 @@ function scheduleRestart() {
function startWatchers() { function startWatchers() {
for (const { directory, files } of watchedDirectories) { for (const { directory, files } of watchedDirectories) {
const watcher = NodeFS.watch( const watcher = watch(
NodePath.join(desktopDir, directory), join(desktopDir, directory),
{ persistent: true }, { persistent: true },
(_eventType, filename) => { (_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) { if (typeof filename !== "string" || !files.has(filename)) {
@@ -199,14 +194,12 @@ function startWatchers() {
} }
function killChildTree(signal) { function killChildTree(signal) {
if (hostPlatform === "win32") { if (process.platform === "win32") {
return; return;
} }
// Kill direct children as a final fallback in case normal shutdown leaves stragglers. // Kill direct children as a final fallback in case normal shutdown leaves stragglers.
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
stdio: "ignore",
});
} }
async function shutdown(exitCode) { async function shutdown(exitCode) {
+112 -137
View File
@@ -1,18 +1,28 @@
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron" // 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 { spawnSync } from "node:child_process";
import * as NodeFS from "node:fs"; import {
import * as NodeModule from "node:module"; copyFileSync,
import * as NodeOS from "node:os"; chmodSync,
import * as NodePath from "node:path"; cpSync,
import * as NodeURL from "node:url"; existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs"; import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = NodePath.resolve(__dirname, ".."); export const desktopDir = resolve(__dirname, "..");
const repoRoot = NodePath.resolve(desktopDir, "..", ".."); const repoRoot = resolve(desktopDir, "..", "..");
const devBundleIdSuffix = NodePath.basename(repoRoot) const devBundleIdSuffix = basename(repoRoot)
.toLowerCase() .toLowerCase()
.replaceAll(/[^a-z0-9]+/g, ""); .replaceAll(/[^a-z0-9]+/g, "");
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
@@ -20,36 +30,29 @@ export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}` ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code"; : "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"]; const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 12; const LAUNCHER_VERSION = 10;
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns"); const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = NodePath.join( const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
repoRoot,
"assets", function resolveDevelopmentProtocolCallbackPort() {
"dev", const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
"blueprint-macos-1024.png", if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
); return configuredPort + 1;
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime. }
const hostPlatform = NodeOS.platform(); return 13774;
}
function setPlistString(plistPath, key, value) { function setPlistString(plistPath, key, value) {
const replaceResult = NodeChildProcess.spawnSync( const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
"plutil", encoding: "utf8",
["-replace", key, "-string", value, plistPath], });
{
encoding: "utf8",
},
);
if (replaceResult.status === 0) { if (replaceResult.status === 0) {
return; return;
} }
const insertResult = NodeChildProcess.spawnSync( const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
"plutil", encoding: "utf8",
["-insert", key, "-string", value, plistPath], });
{
encoding: "utf8",
},
);
if (insertResult.status === 0) { if (insertResult.status === 0) {
return; return;
} }
@@ -60,24 +63,16 @@ function setPlistString(plistPath, key, value) {
function setPlistJson(plistPath, key, value) { function setPlistJson(plistPath, key, value) {
const serialized = JSON.stringify(value); const serialized = JSON.stringify(value);
const replaceResult = NodeChildProcess.spawnSync( const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], {
"plutil", encoding: "utf8",
["-replace", key, "-json", serialized, plistPath], });
{
encoding: "utf8",
},
);
if (replaceResult.status === 0) { if (replaceResult.status === 0) {
return; return;
} }
const insertResult = NodeChildProcess.spawnSync( const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], {
"plutil", encoding: "utf8",
["-insert", key, "-json", serialized, plistPath], });
{
encoding: "utf8",
},
);
if (insertResult.status === 0) { if (insertResult.status === 0) {
return; return;
} }
@@ -87,7 +82,7 @@ function setPlistJson(plistPath, key, value) {
} }
function runChecked(command, args) { function runChecked(command, args) {
const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" }); const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) { if (result.status === 0) {
return; return;
} }
@@ -100,43 +95,39 @@ function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`; return `'${value.replaceAll("'", "'\\''")}'`;
} }
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environment,
}) {
const envEntries = [
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
["T3CODE_PORT", environment.T3CODE_PORT],
["T3CODE_HOME", environment.T3CODE_HOME],
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.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);
return [
"#!/bin/sh",
...envEntries.map(
([name, value]) =>
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n");
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) { function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
NodeFS.writeFileSync( const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`;
const envEntries = [
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
["T3CODE_HOME", process.env.T3CODE_HOME],
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"],
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
writeFileSync(
targetBinaryPath, targetBinaryPath,
makeDevelopmentLauncherScript({ [
electronBinaryPath, "#!/bin/sh",
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"), ...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
desktopRoot: desktopDir, 'for arg in "$@"; do',
environment: process.env, ' case "$arg" in',
}), " t3code-dev://auth/callback*)",
' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then',
' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0',
" fi",
" ;;",
" esac",
"done",
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
); );
NodeFS.chmodSync(targetBinaryPath, 0o755); chmodSync(targetBinaryPath, 0o755);
} }
function registerMacLauncherBundle(appBundlePath) { function registerMacLauncherBundle(appBundlePath) {
@@ -166,24 +157,21 @@ function registerMacLauncherBundle(appBundlePath) {
} }
function ensureDevelopmentIconIcns(runtimeDir) { function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns"); const generatedIconPath = join(runtimeDir, "icon-dev.icns");
NodeFS.mkdirSync(runtimeDir, { recursive: true }); mkdirSync(runtimeDir, { recursive: true });
if (!NodeFS.existsSync(developmentMacIconPngPath)) { if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath; return defaultIconPath;
} }
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs; const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if ( if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
NodeFS.existsSync(generatedIconPath) &&
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
) {
return generatedIconPath; return generatedIconPath;
} }
const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-")); const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset"); const iconsetDir = join(iconsetRoot, "icon.iconset");
NodeFS.mkdirSync(iconsetDir, { recursive: true }); mkdirSync(iconsetDir, { recursive: true });
try { try {
for (const size of [16, 32, 128, 256, 512]) { for (const size of [16, 32, 128, 256, 512]) {
@@ -193,7 +181,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(size), String(size),
developmentMacIconPngPath, developmentMacIconPngPath,
"--out", "--out",
NodePath.join(iconsetDir, `icon_${size}x${size}.png`), join(iconsetDir, `icon_${size}x${size}.png`),
]); ]);
const retinaSize = size * 2; const retinaSize = size * 2;
@@ -203,7 +191,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(retinaSize), String(retinaSize),
developmentMacIconPngPath, developmentMacIconPngPath,
"--out", "--out",
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`), join(iconsetDir, `icon_${size}x${size}@2x.png`),
]); ]);
} }
@@ -216,12 +204,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
); );
return defaultIconPath; return defaultIconPath;
} finally { } finally {
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true }); rmSync(iconsetRoot, { recursive: true, force: true });
} }
} }
function patchMainBundleInfoPlist(appBundlePath, iconPath) { 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, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME); setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID); setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
@@ -233,9 +221,9 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
}, },
]); ]);
const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources"); const resourcesDir = join(appBundlePath, "Contents", "Resources");
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns")); copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns")); copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
} }
function patchHelperBundleInfoPlists(appBundlePath) { function patchHelperBundleInfoPlists(appBundlePath) {
@@ -247,7 +235,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
]; ];
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) { for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
const infoPlistPath = NodePath.join( const infoPlistPath = join(
appBundlePath, appBundlePath,
"Contents", "Contents",
"Frameworks", "Frameworks",
@@ -255,7 +243,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
"Contents", "Contents",
"Info.plist", "Info.plist",
); );
if (!NodeFS.existsSync(infoPlistPath)) { if (!existsSync(infoPlistPath)) {
continue; continue;
} }
@@ -271,75 +259,62 @@ function patchHelperBundleInfoPlists(appBundlePath) {
function readJson(path) { function readJson(path) {
try { try {
return JSON.parse(NodeFS.readFileSync(path, "utf8")); return JSON.parse(readFileSync(path, "utf8"));
} catch { } catch {
return null; return null;
} }
} }
function buildMacLauncher(electronBinaryPath) { function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../.."); const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime"); const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`); const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron"); const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath; 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 = { const expectedMetadata = {
launcherVersion: LAUNCHER_VERSION, launcherVersion: LAUNCHER_VERSION,
sourceAppBundlePath, sourceAppBundlePath,
sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs, sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs, iconMtimeMs: statSync(iconPath).mtimeMs,
appBundleId: APP_BUNDLE_ID, appBundleId: APP_BUNDLE_ID,
appProtocolSchemes: APP_PROTOCOL_SCHEMES, appProtocolSchemes: APP_PROTOCOL_SCHEMES,
}; };
const currentMetadata = readJson(metadataPath); const currentMetadata = readJson(metadataPath);
if ( if (
NodeFS.existsSync(targetBinaryPath) && existsSync(targetBinaryPath) &&
currentMetadata && currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata) JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) { ) {
if (isDevelopment) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
registerMacLauncherBundle(targetAppBundlePath); registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath; return targetBinaryPath;
} }
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true }); rmSync(targetAppBundlePath, { recursive: true, force: true });
// verbatimSymlinks keeps the framework's relative symlinks intact cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
// (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,
});
patchMainBundleInfoPlist(targetAppBundlePath, iconPath); patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath); patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) { if (isDevelopment) {
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath); writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
} }
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`); writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath); registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath; return targetBinaryPath;
} }
function isLinuxSetuidSandboxConfigured(electronBinaryPath) { function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
if (hostPlatform !== "linux") { if (process.platform !== "linux") {
return true; return true;
} }
const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox"); const sandboxPath = join(dirname(electronBinaryPath), "chrome-sandbox");
try { try {
const sandboxStat = NodeFS.statSync(sandboxPath); const sandboxStat = statSync(sandboxPath);
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755; return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
} catch { } catch {
return false; return false;
@@ -360,10 +335,10 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
export function resolveElectronPath() { export function resolveElectronPath() {
ensureElectronRuntime(); ensureElectronRuntime();
const require = NodeModule.createRequire(import.meta.url); const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron"); const electronBinaryPath = require("electron");
if (hostPlatform !== "darwin") { if (process.platform !== "darwin") {
return electronBinaryPath; return electronBinaryPath;
} }
@@ -379,15 +354,15 @@ export function resolveElectronLaunchCommand(args = []) {
} }
export function resolveDevProtocolClient() { export function resolveDevProtocolClient() {
if (hostPlatform !== "darwin" || !isDevelopment) { if (process.platform !== "darwin" || !isDevelopment) {
return null; return null;
} }
const require = NodeModule.createRequire(import.meta.url); const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron"); const electronBinaryPath = require("electron");
const launcherBinaryPath = buildMacLauncher(electronBinaryPath); const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return { return {
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."), appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."),
appBundleId: APP_BUNDLE_ID, appBundleId: APP_BUNDLE_ID,
}; };
} }
@@ -1,28 +0,0 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
const script = makeDevelopmentLauncherScript({
electronBinaryPath: "/repo/node_modules/electron/Electron",
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
T3CODE_PORT: "16566",
T3CODE_HOME: "/tmp/t3",
},
});
assert.include(
script,
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
);
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
assert.include(
script,
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
});
@@ -1,17 +1,13 @@
import * as NodeFS from "node:fs"; import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeModule from "node:module"; import { createRequire } from "node:module";
import * as NodeOS from "node:os"; import { tmpdir } from "node:os";
import * as NodePath from "node:path"; import { dirname, join } from "node:path";
import * as NodeChildProcess from "node:child_process"; 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();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostArch = NodeOS.arch();
function getPlatformPath() { function getPlatformPath() {
switch (hostPlatform) { switch (process.platform) {
case "darwin": case "darwin":
return "Electron.app/Contents/MacOS/Electron"; return "Electron.app/Contents/MacOS/Electron";
case "freebsd": case "freebsd":
@@ -21,34 +17,32 @@ function getPlatformPath() {
case "win32": case "win32":
return "electron.exe"; return "electron.exe";
default: default:
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`); throw new Error(`Electron builds are not available on platform: ${process.platform}`);
} }
} }
function ensureExecutable(filePath) { function ensureExecutable(filePath) {
if (hostPlatform !== "win32") { if (process.platform !== "win32") {
NodeFS.chmodSync(filePath, 0o755); chmodSync(filePath, 0o755);
} }
} }
function repairPathFile(electronDir, platformPath) { function repairPathFile(electronDir, platformPath) {
const pathFile = NodePath.join(electronDir, "path.txt"); const pathFile = join(electronDir, "path.txt");
const currentPath = NodeFS.existsSync(pathFile) const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
? NodeFS.readFileSync(pathFile, "utf8")
: undefined;
if (currentPath !== platformPath) { if (currentPath !== platformPath) {
NodeFS.writeFileSync(pathFile, platformPath); writeFileSync(pathFile, platformPath);
} }
} }
function getRequiredRuntimePaths(electronDir, platformPath) { function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [NodePath.join(electronDir, "dist", platformPath)]; const paths = [join(electronDir, "dist", platformPath)];
if (hostPlatform === "darwin") { if (process.platform === "darwin") {
paths.push( paths.push(
NodePath.join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"), join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
NodePath.join( join(
electronDir, electronDir,
"dist", "dist",
"Electron.app", "Electron.app",
@@ -64,11 +58,11 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
} }
function isMachO(filePath) { function isMachO(filePath) {
if (hostPlatform !== "darwin") { if (process.platform !== "darwin") {
return true; return true;
} }
const result = NodeChildProcess.spawnSync("file", ["-b", filePath], { const result = spawnSync("file", ["-b", filePath], {
encoding: "utf8", encoding: "utf8",
}); });
@@ -77,18 +71,18 @@ function isMachO(filePath) {
function missingRuntimePaths(electronDir, platformPath) { function missingRuntimePaths(electronDir, platformPath) {
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => { return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
return !NodeFS.existsSync(runtimePath); return !existsSync(runtimePath);
}); });
} }
function invalidRuntimePaths(electronDir, platformPath) { function invalidRuntimePaths(electronDir, platformPath) {
if (hostPlatform !== "darwin") { if (process.platform !== "darwin") {
return []; return [];
} }
return [ return [
NodePath.join(electronDir, "dist", platformPath), join(electronDir, "dist", platformPath),
NodePath.join( join(
electronDir, electronDir,
"dist", "dist",
"Electron.app", "Electron.app",
@@ -97,11 +91,11 @@ function invalidRuntimePaths(electronDir, platformPath) {
"Electron Framework.framework", "Electron Framework.framework",
"Electron Framework", "Electron Framework",
), ),
].filter((runtimePath) => NodeFS.existsSync(runtimePath) && !isMachO(runtimePath)); ].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
} }
function runChecked(command, args) { function runChecked(command, args) {
const result = NodeChildProcess.spawnSync(command, args, { const result = spawnSync(command, args, {
encoding: "utf8", encoding: "utf8",
stdio: "inherit", stdio: "inherit",
}); });
@@ -116,45 +110,45 @@ function runChecked(command, args) {
} }
function installElectronRuntime(electronDir, version) { function installElectronRuntime(electronDir, version) {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-")); const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`); const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
try { try {
runChecked("curl", [ runChecked("curl", [
"-fsSL", "-fsSL",
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`, `https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
"-o", "-o",
zipPath, zipPath,
]); ]);
if (hostPlatform === "darwin") { if (process.platform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, NodePath.join(electronDir, "dist")]); runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
} else { } else {
runChecked("python3", [ runChecked("python3", [
"-c", "-c",
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])", "import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
zipPath, zipPath,
NodePath.join(electronDir, "dist"), join(electronDir, "dist"),
]); ]);
} }
} finally { } finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true }); rmSync(tempDir, { recursive: true, force: true });
} }
} }
export function ensureElectronRuntime() { export function ensureElectronRuntime() {
const electronPackageJsonPath = require.resolve("electron/package.json"); const electronPackageJsonPath = require.resolve("electron/package.json");
const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8")); const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = NodePath.dirname(electronPackageJsonPath); const electronDir = dirname(electronPackageJsonPath);
const platformPath = getPlatformPath(); const platformPath = getPlatformPath();
const electronPath = NodePath.join(electronDir, "dist", platformPath); const electronPath = join(electronDir, "dist", platformPath);
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath); const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath); const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) { if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) { if (existsSync(join(electronDir, "dist"))) {
NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true }); 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); installElectronRuntime(electronDir, electronPackageJson.version);
} }
+7 -7
View File
@@ -1,16 +1,16 @@
import * as NodeChildProcess from "node:child_process"; import { spawn } from "node:child_process";
import * as NodePath from "node:path"; import { dirname, resolve } from "node:path";
import * as NodeURL from "node:url"; import { fileURLToPath } from "node:url";
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs"; import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = NodePath.resolve(__dirname, ".."); const desktopDir = resolve(__dirname, "..");
const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs"); const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test..."); console.log("\nLaunching Electron smoke test...");
const electronCommand = resolveElectronLaunchCommand([mainJs]); const electronCommand = resolveElectronLaunchCommand([mainJs]);
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, { const child = spawn(electronCommand.electronPath, electronCommand.args, {
stdio: ["pipe", "pipe", "pipe"], stdio: ["pipe", "pipe", "pipe"],
env: { env: {
...process.env, ...process.env,
+2 -2
View File
@@ -1,4 +1,4 @@
import * as NodeChildProcess from "node:child_process"; import { spawn } from "node:child_process";
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs"; import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
@@ -6,7 +6,7 @@ const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE; delete childEnv.ELECTRON_RUN_AS_NODE;
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]); const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, { const child = spawn(electronCommand.electronPath, electronCommand.args, {
stdio: "inherit", stdio: "inherit",
cwd: desktopDir, cwd: desktopDir,
env: childEnv, env: childEnv,
+8 -8
View File
@@ -1,13 +1,13 @@
import * as NodeFSP from "node:fs/promises"; import * as FileSystem from "node:fs/promises";
import * as NodeNet from "node:net"; import * as Net from "node:net";
import * as NodePath from "node:path"; import * as Path from "node:path";
import * as NodeTimersPromises from "node:timers/promises"; import * as Timers from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"]; const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) { async function fileExists(filePath) {
try { try {
await NodeFSP.access(filePath); await FileSystem.access(filePath);
return true; return true;
} catch { } catch {
return false; return false;
@@ -16,7 +16,7 @@ async function fileExists(filePath) {
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) { function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => { return new Promise((resolveReady) => {
const socket = NodeNet.createConnection({ host, port }); const socket = Net.createConnection({ host, port });
let settled = false; let settled = false;
const finish = (ready) => { const finish = (ready) => {
@@ -47,7 +47,7 @@ async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, conn
const pendingFiles = []; const pendingFiles = [];
for (const relativeFilePath of files) { for (const relativeFilePath of files) {
const ready = await fileExists(NodePath.resolve(baseDir, relativeFilePath)); const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
if (!ready) { if (!ready) {
pendingFiles.push(relativeFilePath); pendingFiles.push(relativeFilePath);
} }
@@ -114,6 +114,6 @@ export async function waitForResources({
); );
} }
await NodeTimersPromises.setTimeout(intervalMs); await Timers.setTimeout(intervalMs);
} }
} }
+19 -30
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause"; import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as NetService from "@t3tools/shared/Net"; import * as NetService from "@t3tools/shared/Net";
import * as Crypto from "effect/Crypto"; import * as Crypto from "effect/Crypto";
@@ -11,13 +11,12 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts"; import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts"; import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopObservability from "./DesktopObservability.ts"; import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts"; import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts"; import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
@@ -33,24 +32,22 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)), Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
); );
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()( class DesktopBackendPortUnavailableError extends Data.TaggedError(
"DesktopBackendPortUnavailableError", "DesktopBackendPortUnavailableError",
{ )<{
startPort: Schema.Int, readonly startPort: number;
maxPort: Schema.Int, readonly maxPort: number;
hosts: Schema.Array(Schema.String), readonly hosts: readonly string[];
}, }> {
) { override get message() {
override get message(): string {
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`; return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
} }
} }
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()( class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
"DesktopDevelopmentBackendPortRequiredError", "DesktopDevelopmentBackendPortRequiredError",
{}, )<{}> {
) { override get message() {
override get message(): string {
return "T3CODE_PORT is required in desktop development."; return "T3CODE_PORT is required in desktop development.";
} }
} }
@@ -103,12 +100,12 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
): Effect.fn.Return< ): Effect.fn.Return<
void, void,
never, never,
| DesktopShutdown.DesktopShutdown | DesktopLifecycle.DesktopShutdown
| DesktopState.DesktopState | DesktopState.DesktopState
| ElectronApp.ElectronApp | ElectronApp.ElectronApp
| ElectronDialog.ElectronDialog | ElectronDialog.ElectronDialog
> { > {
const shutdown = yield* DesktopShutdown.DesktopShutdown; const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const state = yield* DesktopState.DesktopState; const state = yield* DesktopState.DesktopState;
const electronApp = yield* ElectronApp.ElectronApp; const electronApp = yield* ElectronApp.ElectronApp;
const electronDialog = yield* ElectronDialog.ElectronDialog; const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -166,16 +163,6 @@ const bootstrap = Effect.gen(function* () {
} }
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort }); const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
const backendConfig = yield* serverExposure.backendConfig; const backendConfig = yield* serverExposure.backendConfig;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const rendererTarget = environment.isDevelopment
? Option.getOrThrow(environment.devServerUrl)
: backendConfig.httpBaseUrl;
yield* electronProtocol.registerDesktopProtocol({
scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
targetOrigin: rendererTarget,
backendOrigin: backendConfig.httpBaseUrl,
clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
});
yield* logBootstrapInfo("bootstrap resolved backend endpoint", { yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
baseUrl: backendConfig.httpBaseUrl.href, baseUrl: backendConfig.httpBaseUrl.href,
}); });
@@ -202,8 +189,9 @@ const startup = Effect.gen(function* () {
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity; const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu; const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp; const electronApp = yield* ElectronApp.ElectronApp;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const clerk = yield* DesktopClerk.DesktopClerk; const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const updates = yield* DesktopUpdates.DesktopUpdates; const updates = yield* DesktopUpdates.DesktopUpdates;
@@ -221,7 +209,7 @@ const startup = Effect.gen(function* () {
yield* appIdentity.configure; yield* appIdentity.configure;
yield* lifecycle.register; yield* lifecycle.register;
yield* clerk.configure; yield* cloudAuth.configure;
yield* electronApp.whenReady.pipe( yield* electronApp.whenReady.pipe(
Effect.withSpan("desktop.electron.whenReady"), Effect.withSpan("desktop.electron.whenReady"),
@@ -230,6 +218,7 @@ const startup = Effect.gen(function* () {
yield* logStartupInfo("app ready"); yield* logStartupInfo("app ready");
yield* appIdentity.configure; yield* appIdentity.configure;
yield* applicationMenu.configure; yield* applicationMenu.configure;
yield* electronProtocol.registerDesktopFileProtocol;
yield* updates.configure; yield* updates.configure;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause))); yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup")); }).pipe(Effect.withSpan("desktop.startup"));
@@ -240,7 +229,7 @@ const scopedProgram = Effect.scoped(
yield* Effect.annotateLogsScoped({ scope: "desktop", runId }); yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId }); yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopShutdown.DesktopShutdown; const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager; const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
yield* Effect.addFinalizer(() => yield* Effect.addFinalizer(() =>
@@ -1,30 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import {
DesktopBackendPortUnavailableError,
DesktopDevelopmentBackendPortRequiredError,
} from "./DesktopApp.ts";
describe("DesktopApp errors", () => {
it("preserves unavailable backend port context", () => {
const error = new DesktopBackendPortUnavailableError({
startPort: 3_773,
maxPort: 65_535,
hosts: ["127.0.0.1", "0.0.0.0", "::"],
});
assert.equal(error.startPort, 3_773);
assert.equal(error.maxPort, 65_535);
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
assert.equal(
error.message,
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
);
});
it("reports the required development port", () => {
const error = new DesktopDevelopmentBackendPortRequiredError();
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
});
});
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import type * as Electron from "electron"; import type * as Electron from "electron";
@@ -64,7 +63,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}), }),
appendCommandLineSwitch: () => Effect.void, appendCommandLineSwitch: () => Effect.void,
on: () => Effect.void, on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]); } satisfies ElectronApp.ElectronAppShape);
const makeAssetsLayer = (png: Option.Option<string>) => const makeAssetsLayer = (png: Option.Option<string>) =>
Layer.succeed(DesktopAssets.DesktopAssets, { Layer.succeed(DesktopAssets.DesktopAssets, {
@@ -74,7 +73,7 @@ const makeAssetsLayer = (png: Option.Option<string>) =>
png, png,
}), }),
resolveResourcePath: () => Effect.succeed(Option.none()), resolveResourcePath: () => Effect.succeed(Option.none()),
} satisfies DesktopAssets.DesktopAssets["Service"]); } satisfies DesktopAssets.DesktopAssetsShape);
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => { const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
const { env, ...environmentOverrides } = overrides; const { env, ...environmentOverrides } = overrides;
@@ -106,7 +105,6 @@ const withIdentity = <A, E, R>(
readonly calls?: ElectronAppCalls; readonly calls?: ElectronAppCalls;
readonly environment?: TestEnvironmentInput; readonly environment?: TestEnvironmentInput;
readonly legacyPathExists?: boolean; readonly legacyPathExists?: boolean;
readonly legacyPathProbeError?: PlatformError.PlatformError;
readonly packageJson?: string; readonly packageJson?: string;
readonly pngIconPath?: Option.Option<string>; readonly pngIconPath?: Option.Option<string>;
} = {}, } = {},
@@ -123,11 +121,7 @@ const withIdentity = <A, E, R>(
Layer.provideMerge( Layer.provideMerge(
FileSystem.layerNoop({ FileSystem.layerNoop({
exists: (path) => exists: (path) =>
input.legacyPathProbeError Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
? Effect.fail(input.legacyPathProbeError)
: Effect.succeed(
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
),
readFileString: () => readFileString: () =>
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'), Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
}), }),
@@ -153,33 +147,6 @@ describe("DesktopAppIdentity", () => {
), ),
); );
it.effect("preserves failures while inspecting the legacy userData path", () => {
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
description: "permission denied",
pathOrDescriptor: legacyPath,
});
return withIdentity(
Effect.gen(function* () {
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
const error = yield* identity.resolveUserDataPath.pipe(Effect.flip);
assert.instanceOf(error, DesktopAppIdentity.DesktopUserDataPathResolutionError);
assert.equal(error.legacyPath, legacyPath);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to inspect legacy desktop user-data path at "${legacyPath}".`,
);
}),
{ legacyPathProbeError: cause },
);
});
it.effect("configures app identity from the environment commit override", () => { it.effect("configures app identity from the environment commit override", () => {
const calls: ElectronAppCalls = { const calls: ElectronAppCalls = {
setAboutPanelOptions: [], setAboutPanelOptions: [],
+8 -24
View File
@@ -18,24 +18,14 @@ const AppPackageMetadata = Schema.Struct({
}); });
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata)); const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
export class DesktopUserDataPathResolutionError extends Schema.TaggedErrorClass<DesktopUserDataPathResolutionError>()( export interface DesktopAppIdentityShape {
"DesktopUserDataPathResolutionError", readonly resolveUserDataPath: Effect.Effect<string>;
{ readonly configure: Effect.Effect<void>;
legacyPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to inspect legacy desktop user-data path at "${this.legacyPath}".`;
}
} }
export class DesktopAppIdentity extends Context.Service< export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity, DesktopAppIdentity,
{ DesktopAppIdentityShape
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
readonly configure: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopAppIdentity") {} >()("@t3tools/desktop/app/DesktopAppIdentity") {}
const normalizeCommitHash = (value: string): Option.Option<string> => { const normalizeCommitHash = (value: string): Option.Option<string> => {
@@ -45,7 +35,7 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none(); : Option.none();
}; };
export const make = Effect.gen(function* () { const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets; const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp; const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment; const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -95,15 +85,9 @@ export const make = Effect.gen(function* () {
environment.appDataDirectory, environment.appDataDirectory,
environment.legacyUserDataDirName, environment.legacyUserDataDirName,
); );
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe( const legacyPathExists = yield* fileSystem
Effect.mapError( .exists(legacyPath)
(cause) => .pipe(Effect.orElseSucceed(() => false));
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists return legacyPathExists
? legacyPath ? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName); : environment.path.join(environment.appDataDirectory, environment.userDataDirName);
@@ -1,57 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as DesktopAssets from "./DesktopAssets.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
isPackaged: true,
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
runningUnderArm64Translation: false,
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
describe("DesktopAssets", () => {
it.effect("preserves the failed asset candidate and filesystem cause", () =>
Effect.gen(function* () {
const fileName = "custom.bin";
const candidatePath = "/repo/apps/desktop/resources/custom.bin";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
pathOrDescriptor: candidatePath,
description: "private filesystem diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
exists: (path) => (path === candidatePath ? Effect.fail(cause) : Effect.succeed(false)),
});
const assetsLayer = DesktopAssets.layer.pipe(
Layer.provide(Layer.merge(fileSystemLayer, environmentLayer)),
);
const assets = yield* DesktopAssets.DesktopAssets.pipe(Effect.provide(assetsLayer));
const error = yield* assets.resolveResourcePath(fileName).pipe(Effect.flip);
assert.instanceOf(error, DesktopAssets.DesktopAssetProbeError);
assert.equal(error.fileName, fileName);
assert.equal(error.candidatePath, candidatePath);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to probe desktop asset "${fileName}" at ${candidatePath}.`,
);
assert.notInclude(error.message, "private filesystem diagnostic");
}),
);
});
+14 -42
View File
@@ -3,7 +3,6 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts";
@@ -13,47 +12,27 @@ export interface DesktopIconPaths {
readonly png: Option.Option<string>; readonly png: Option.Option<string>;
} }
export class DesktopAssetProbeError extends Schema.TaggedErrorClass<DesktopAssetProbeError>()( export interface DesktopAssetsShape {
"DesktopAssetProbeError", readonly iconPaths: Effect.Effect<DesktopIconPaths>;
{ readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
fileName: Schema.String,
candidatePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to probe desktop asset "${this.fileName}" at ${this.candidatePath}.`;
}
} }
export class DesktopAssets extends Context.Service< export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
DesktopAssets, "@t3tools/desktop/app/DesktopAssets",
{ ) {}
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (
fileName: string,
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
}
>()("@t3tools/desktop/app/DesktopAssets") {}
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* ( const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
fileName: string, fileName: string,
): Effect.fn.Return< ): Effect.fn.Return<
Option.Option<string>, Option.Option<string>,
DesktopAssetProbeError, never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> { > {
const fileSystem = yield* FileSystem.FileSystem; const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment; const environment = yield* DesktopEnvironment.DesktopEnvironment;
const candidates = environment.resolveResourcePathCandidates(fileName); const candidates = environment.resolveResourcePathCandidates(fileName);
for (const candidate of candidates) { for (const candidate of candidates) {
const exists = yield* fileSystem const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
.exists(candidate)
.pipe(
Effect.mapError(
(cause) => new DesktopAssetProbeError({ fileName, candidatePath: candidate, cause }),
),
);
if (exists) { if (exists) {
return Option.some(candidate); return Option.some(candidate);
} }
@@ -65,23 +44,16 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
ext: keyof DesktopIconPaths, ext: keyof DesktopIconPaths,
): Effect.fn.Return< ): Effect.fn.Return<
Option.Option<string>, Option.Option<string>,
DesktopAssetProbeError, never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> { > {
const fileSystem = yield* FileSystem.FileSystem; const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment; const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") { if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = environment.developmentDockIconPath; const developmentDockIconPath = environment.developmentDockIconPath;
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe( const developmentDockIconExists = yield* fileSystem
Effect.mapError( .exists(developmentDockIconPath)
(cause) => .pipe(Effect.orElseSucceed(() => false));
new DesktopAssetProbeError({
fileName: "icon.png",
candidatePath: developmentDockIconPath,
cause,
}),
),
);
if (developmentDockIconExists) { if (developmentDockIconExists) {
return Option.some(developmentDockIconPath); return Option.some(developmentDockIconPath);
} }
@@ -90,7 +62,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
return yield* resolveResourcePath(`icon.${ext}`); return yield* resolveResourcePath(`icon.${ext}`);
}); });
export const make = Effect.gen(function* () { const make = Effect.gen(function* () {
const context = yield* Effect.context< const context = yield* Effect.context<
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
>(); >();
@@ -1,122 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
isPackaged: true,
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
runningUnderArm64Translation: false,
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
const withOutputLog = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
messages: Array<ReadonlyArray<unknown>>,
) => {
const logger = Logger.make(({ message }) => {
messages.push(Array.isArray(message) ? message : [message]);
});
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
);
return effect.pipe(Effect.provide(outputLogLayer));
};
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
?.error;
describe("DesktopBackendOutputLog", () => {
it.effect("logs setup failures with the log path and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
description: "private setup diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.fail(cause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private setup diagnostic");
}),
fileSystemLayer,
messages,
);
});
it.effect("logs record write failures with the operation and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const missingCause = PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "stat",
pathOrDescriptor: LOG_FILE_PATH,
});
const writeCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFile",
pathOrDescriptor: LOG_FILE_PATH,
description: "private write diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.void,
stat: () => Effect.fail(missingCause),
readDirectory: () => Effect.succeed([]),
writeFile: () => Effect.fail(writeCause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
assert.equal(error.operation, "write-record");
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, writeCause);
assert.equal(
error.message,
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private write diagnostic");
}),
fileSystemLayer,
messages,
);
});
});
@@ -1,385 +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 filePath: string;
readonly writeBytes: (
chunk: Uint8Array,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
readonly writeText: (
chunk: string,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
"DesktopLogFileWriterRecoveryError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
recoveryCause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
"DesktopBackendOutputLogSetupError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
"DesktopBackendOutputLogWriteError",
{
operation: Schema.Literals(["encode-record", "write-record"]),
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
}
}
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
"DesktopBackendConsoleWriteError",
{
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to mirror desktop backend output to ${this.streamName}.`;
}
}
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") {}
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, PlatformError.PlatformError> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
}),
);
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 recoverCurrentSize = (
cause: PlatformError.PlatformError,
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.matchEffect({
onFailure: (recoveryCause) =>
Effect.fail(
new DesktopLogFileWriterRecoveryError({
logFilePath: input.filePath,
cause,
recoveryCause,
}),
),
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
}),
);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory);
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 });
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source);
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem.exists(input.filePath);
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
});
const writeBytes = (
chunk: Uint8Array,
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
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.catchTags({
PlatformError: recoverCurrentSize,
}),
),
);
};
yield* pruneOverflowBackups;
return {
filePath: input.filePath,
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
});
const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.try({
try: () => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
},
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
}).pipe(
Effect.catchTags({
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
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,
}).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "encode-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
yield* logFile.writeText(`${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "write-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
}).pipe(
Effect.catchTags({
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
},
);
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
const writer = yield* makeRotatingLogFileWriter({
filePath: logFilePath,
}).pipe(
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
Effect.map(Option.some),
Effect.catchTags({
DesktopBackendOutputLogSetupError: (error) =>
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
}),
);
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);
-149
View File
@@ -1,149 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
createClerkBridgeMock: vi.fn(),
storageAdapter: {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
},
storageMock: vi.fn(),
}));
vi.mock("@clerk/electron", () => ({
createClerkBridge: createClerkBridgeMock,
}));
vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const makeDesktopClerkLayer = (isDevelopment = true) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
return DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
);
};
describe("DesktopClerk", () => {
beforeEach(() => {
createClerkBridgeMock.mockReset();
storageMock.mockReset();
});
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
assert.equal(
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
"clerk.t3.codes",
);
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
});
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
return Effect.gen(function* () {
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme: "t3code-dev", host: "app" },
},
],
]);
assert.equal(cleanup.mock.calls.length, 1);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
it.effect("preserves bridge initialization failures", () => {
const cause = new Error("bridge initialization failed");
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockImplementationOnce(() => {
throw cause;
});
return Effect.gen(function* () {
const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
assert.equal(error.stateDir, "/tmp/t3-state");
assert.equal(error.isDevelopment, true);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
);
});
});
it.effect("preserves bridge cleanup failures", () => {
const cause = new Error("bridge cleanup failed");
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({
cleanup: () => {
throw cause;
},
});
return Effect.gen(function* () {
const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
assert.equal(error.stateDir, "/tmp/t3-state");
assert.equal(error.isDevelopment, false);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
);
}
});
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
const bridge = { cleanup: vi.fn() };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme, host: "app" },
},
],
]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
-135
View File
@@ -1,135 +0,0 @@
import { createClerkBridge } from "@clerk/electron";
import { storage } from "@clerk/electron/storage";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(
"DesktopClerkBridgeInitializationError",
{
stateDir: Schema.String,
isDevelopment: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
}
}
export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(
"DesktopClerkBridgeCleanupError",
{
stateDir: Schema.String,
isDevelopment: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
}
}
export class DesktopClerk extends Context.Service<
DesktopClerk,
{
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
>()("@t3tools/desktop/app/DesktopClerk") {}
export function resolveDesktopClerkFrontendApiHostname(
publishableKey: string | undefined,
): string | undefined {
const normalizedKey = publishableKey?.trim();
if (!normalizedKey) return undefined;
try {
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
} catch {
return undefined;
}
}
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? undefined
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
);
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
return createClerkBridge({
storage: storage({ path: stateDir }),
passkeys: true,
renderer: {
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
host: ElectronProtocol.DESKTOP_HOST,
},
});
}
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
Effect.try({
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
catch: (cause) =>
new DesktopClerkBridgeInitializationError({
stateDir: environment.stateDir,
isDevelopment: environment.isDevelopment,
cause,
}),
}),
(bridge) =>
Effect.try({
try: () => bridge.cleanup(),
catch: (cause) =>
new DesktopClerkBridgeCleanupError({
stateDir: environment.stateDir,
isDevelopment: environment.isDevelopment,
cause,
}),
}).pipe(Effect.orDie),
);
return DesktopClerk.of({
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
if (!(yield* electronApp.requestSingleInstanceLock)) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
yield* electronApp.on("second-instance", () => {
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
});
}).pipe(Effect.withSpan("desktop.clerk.configure")),
});
});
export const layer = Layer.effect(DesktopClerk, make);
@@ -0,0 +1,302 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthHarness {
readonly app: ElectronApp.ElectronAppShape;
readonly window: ElectronWindow.ElectronWindowShape;
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
readonly protocolRegistrations: {
readonly protocol: string;
readonly path?: string;
readonly args?: readonly string[];
}[];
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
readonly reveals: unknown[];
readonly layer: Layer.Layer<
| DesktopCloudAuth.DesktopCloudAuth
| DesktopEnvironment.DesktopEnvironment
| ElectronApp.ElectronApp
| ElectronWindow.ElectronWindow
>;
}
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
const sends: CloudAuthHarness["sends"] = [];
const reveals: unknown[] = [];
const mainWindow = { id: "main-window" };
const app = ElectronApp.ElectronApp.of({
metadata: Effect.succeed({
appVersion: "0.0.0-test",
appPath: "/tmp/t3-code-test",
isPackaged: !input.isDevelopment,
resourcesPath: "/tmp/t3-code-test/resources",
runningUnderArm64Translation: false,
}),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: (protocol, path, args) =>
Effect.sync(() => {
protocolRegistrations.push({
protocol,
...(path === undefined ? {} : { path }),
...(args === undefined ? {} : { args }),
});
return true;
}),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
on: (eventName, listener) =>
Effect.sync(() => {
const erasedListener = listener as (...args: readonly unknown[]) => void;
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
}),
});
const window = ElectronWindow.ElectronWindow.of({
create: () => Effect.die("not used"),
main: Effect.succeed(Option.some(mainWindow as never)),
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
setMain: () => Effect.void,
clearMain: () => Effect.void,
reveal: (target) =>
Effect.sync(() => {
reveals.push(target);
}),
sendAll: (channel, ...args) =>
Effect.sync(() => {
sends.push({ channel, args });
}),
destroyAll: Effect.void,
syncAllAppearance: () => Effect.void,
});
const environment = DesktopEnvironment.DesktopEnvironment.of({
isDevelopment: input.isDevelopment,
} as DesktopEnvironment.DesktopEnvironmentShape);
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
return {
app,
window,
listeners,
protocolRegistrations,
sends,
reveals,
layer: Layer.mergeAll(
DesktopCloudAuth.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provide(NodeServices.layer),
),
Layer.succeed(ElectronApp.ElectronApp, app),
Layer.succeed(ElectronWindow.ElectronWindow, window),
),
};
}
function emitAppEvent(
harness: CloudAuthHarness,
eventName: string,
...args: readonly unknown[]
): void {
for (const listener of harness.listeners.get(eventName) ?? []) {
listener(...args);
}
}
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
describe("DesktopCloudAuth", () => {
it("uses separate callback schemes for packaged and development builds", () => {
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
"t3code",
);
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
"t3code-dev",
);
});
it("builds a native callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code",
state: "state-1",
}),
"t3code://auth/callback?t3_state=state-1",
);
});
it("accepts only the expected scheme, host, path, and state", () => {
assert.isNotNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
});
it("builds a native development callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code-dev",
state: "state-1",
}),
"t3code-dev://auth/callback?t3_state=state-1",
);
});
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
let prevented = false;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => (prevented = true) },
callbackUrl.toString(),
);
yield* flushCloudAuthDispatch;
assert.isTrue(prevented);
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code-dev"],
);
assert.isString(harness.protocolRegistrations[0]?.path);
assert.isArray(harness.protocolRegistrations[0]?.args);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.lengthOf(harness.reveals, 1);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
const harness = makeHarness({ isDevelopment: false });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const validCallback = new URL(redirectUrl);
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
const invalidCallback = new URL(validCallback);
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
invalidCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, []);
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code"],
);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [validCallback.toString()],
},
]);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect(
"routes second-instance callbacks and reveals the window for non-callback launches",
() => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
yield* flushCloudAuthDispatch;
const revealCountAfterCallback = harness.reveals.length;
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.equal(revealCountAfterCallback, 1);
assert.equal(harness.reveals.length, 2);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
},
);
});
+330
View File
@@ -0,0 +1,330 @@
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 Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import type * as Electron from "electron";
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
"DesktopCloudAuthCallbackServerError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to start the desktop cloud auth callback server.";
}
}
interface PendingCloudAuthRequest {
readonly state: string;
readonly redirectUrl: string;
readonly close: () => void;
}
export interface DesktopCloudAuthShape {
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
"@t3tools/desktop/app/DesktopCloudAuth",
) {}
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
}
export function buildCloudAuthCallbackUrl(input: {
readonly scheme: string;
readonly state: string;
}): string {
const url = new URL(
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
);
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
return url.toString();
}
export function parseCloudAuthCallbackUrl(input: {
readonly rawUrl: unknown;
readonly scheme: string;
readonly state: string;
}): URL | null {
if (typeof input.rawUrl !== "string") {
return null;
}
try {
const url = new URL(input.rawUrl);
if (url.protocol !== `${input.scheme}:`) return null;
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
return url;
} catch {
return null;
}
}
export function findCloudAuthCallbackUrl(input: {
readonly values: readonly unknown[];
readonly scheme: string;
readonly state: string;
}): URL | null {
for (const value of input.values) {
const url = parseCloudAuthCallbackUrl({
rawUrl: value,
scheme: input.scheme,
state: input.state,
});
if (url) return url;
}
return null;
}
export function resolveProtocolClientLaunchArgs(input: {
readonly argv: readonly string[];
}): readonly string[] {
return input.argv.slice(1);
}
function resolveConfiguredProtocolClient(): {
readonly path: string;
readonly args: readonly string[];
} | null {
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
if (!path) return null;
return {
path,
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
.split("\n")
.map((arg) => arg.trim())
.filter((arg) => arg.length > 0),
};
}
function isProtocolRegistrationManagedExternally(): boolean {
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
}
function resolveProtocolCallbackForwardUrl(): URL | null {
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
if (!rawUrl) return null;
try {
const url = new URL(rawUrl);
if (url.protocol !== "http:") return null;
if (url.hostname !== "127.0.0.1") return null;
if (url.pathname !== "/auth/callback") return null;
if (!url.port) return null;
return url;
} catch {
return null;
}
}
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
request?.close();
return null;
};
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
}
function ignoreCloudAuthCallback(_rawUrl: string) {}
function startProtocolCallbackForwardServer(
callbackUrl: URL,
dispatch: (rawUrl: string) => void,
): Effect.Effect<void, never, Scope.Scope> {
const port = Number.parseInt(callbackUrl.port, 10);
const routesLayer = HttpRouter.add(
"POST",
"/auth/callback",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const rawUrl = yield* request.text;
yield* Effect.sync(() => {
dispatch(rawUrl);
});
return HttpServerResponse.empty({ status: 204 });
}),
);
return Effect.gen(function* () {
const NodeHttp = yield* Effect.promise(() => import("node:http"));
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
host: callbackUrl.hostname,
port,
});
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
Effect.forkScoped,
);
});
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
const makeCloudAuthRequestState = Effect.gen(function* () {
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
return `${left}${right}`.replaceAll("-", "");
});
return DesktopCloudAuth.of({
createRequest: Effect.gen(function* () {
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
const state = yield* makeCloudAuthRequestState.pipe(
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
);
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
const timeout = createCloudAuthRequestTimeout(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
});
pendingAuthRequest = {
state,
redirectUrl,
close: () => clearTimeout(timeout),
};
return redirectUrl;
}),
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const scope = yield* Scope.Scope;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
yield* Scope.addFinalizer(
scope,
Effect.sync(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
}),
);
if (isProtocolRegistrationManagedExternally()) {
// Development macOS launchers set the default URL handler before the stock Electron
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
} else if (environment.isDevelopment) {
const configuredClient = resolveConfiguredProtocolClient();
if (configuredClient) {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
configuredClient.path,
configuredClient.args,
);
} else {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
process.execPath,
resolveProtocolClientLaunchArgs({ argv: process.argv }),
);
}
} else {
yield* electronApp.setAsDefaultProtocolClient(scheme);
}
dispatchCloudAuthCallback = (rawUrl: string) => {
const pending = pendingAuthRequest;
const callbackUrl = pending
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
: null;
if (!callbackUrl) {
return;
}
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
void runPromise(
Effect.gen(function* () {
yield* electronWindow.sendAll(
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
callbackUrl.toString(),
);
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
};
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
if (environment.isDevelopment && protocolCallbackForwardUrl) {
yield* startProtocolCallbackForwardServer(
protocolCallbackForwardUrl,
dispatchCloudAuthCallback,
);
}
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
if (!hasInstanceLock) {
return yield* electronApp.quit;
}
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
event.preventDefault?.();
dispatchCloudAuthCallback(rawUrl);
});
yield* electronApp.on<[Electron.Event, readonly string[]]>(
"second-instance",
(_event, argv) => {
const values = resolveProtocolClientLaunchArgs({ argv });
const pending = pendingAuthRequest;
const callbackUrl = pending
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
: null;
if (callbackUrl) {
dispatchCloudAuthCallback(callbackUrl.toString());
return;
}
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
},
);
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
});
});
export const layer = Layer.effect(DesktopCloudAuth, make);
@@ -0,0 +1,96 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
function makeSafeStorageLayer(input: { readonly available: boolean }) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(input.available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
decryptString: (value) => {
const decoded = textDecoder.decode(value);
if (!decoded.startsWith("enc:")) {
return Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted token"),
}),
);
}
return Effect.succeed(decoded.slice("enc:".length));
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopCloudAuthTokenStore.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
Layer.provideMerge(NodeServices.layer),
);
}
const withTokenStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
input?: { readonly encryptionAvailable?: boolean },
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-cloud-auth-token-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopCloudAuthTokenStore", () => {
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
yield* tokenStore.clear;
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
),
);
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
{ encryptionAvailable: false },
),
);
});
@@ -0,0 +1,155 @@
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";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthTokenDocument {
readonly version: number;
readonly encryptedClientJwt: string;
}
const CloudAuthTokenDocumentSchema = Schema.Struct({
version: Schema.Number,
encryptedClientJwt: Schema.String,
});
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
}
}
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode desktop cloud auth token.";
}
}
export interface DesktopCloudAuthTokenStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopCloudAuthTokenStoreDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
token: string,
) => Effect.Effect<
boolean,
| DesktopCloudAuthTokenStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopCloudAuthTokenStore extends Context.Service<
DesktopCloudAuthTokenStore,
DesktopCloudAuthTokenStoreShape
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
tokenPath: string,
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
fileSystem.readFileString(tokenPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
}),
),
);
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly tokenPath: string;
readonly document: CloudAuthTokenDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.tokenPath);
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.tokenPath);
});
export const layer = Layer.effect(
DesktopCloudAuthTokenStore,
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 tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
return DesktopCloudAuthTokenStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, tokenPath);
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
tokenPath,
document: { version: 1, encryptedClientJwt },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
return true;
}),
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
Effect.catch(() => Effect.void),
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
),
});
}),
);
@@ -1,415 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
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 Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const textDecoder = new TextDecoder();
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),
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
decryptString: (value) => {
return Effect.gen(function* () {
const decoded = textDecoder.decode(value);
if (
!decoded.startsWith("encrypted:") ||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
) {
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted catalog"),
});
}
return decoded.slice("encrypted:".length);
});
},
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
function makeLayer(
baseDir: string,
encryptionAvailable = true,
failDecrypt: Ref.Ref<boolean> | null = null,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
const dependencies = Layer.mergeAll(
environmentLayer,
safeStorageLayer,
NodeServices.layer,
fileSystemLayer,
);
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
Layer.provideMerge(dependencies),
);
return DesktopConnectionCatalogStore.layer.pipe(
Layer.provideMerge(savedEnvironmentsLayer),
Layer.provideMerge(dependencies),
);
}
const withStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
encryptionAvailable = true,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopConnectionCatalogStore", () => {
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalog = '{"schemaVersion":1,"targets":[]}';
assert.isTrue(yield* store.set(catalog));
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
yield* store.clear;
assert.deepStrictEqual(yield* store.get, Option.none());
}),
),
);
it.effect("does not persist when secure storage is unavailable", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
assert.isFalse(yield* store.set("{}"));
assert.deepStrictEqual(yield* store.get, Option.none());
}),
false,
),
);
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const records: readonly PersistedSavedEnvironmentRecord[] = [
{
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
httpBaseUrl: "https://relay.example.com/",
wsBaseUrl: "wss://relay.example.com/",
createdAt: "2026-06-01T00:00:00.000Z",
lastConnectedAt: null,
relayManaged: { relayUrl: "https://relay-control.example.com/" },
},
{
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
httpBaseUrl: "http://127.0.0.1:41773/",
wsBaseUrl: "ws://127.0.0.1:41773/",
createdAt: "2026-06-02T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
{
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
createdAt: "2026-06-03T00:00:00.000Z",
lastConnectedAt: null,
},
];
yield* savedEnvironments.setRegistry(records);
assert.isTrue(
yield* savedEnvironments.setSecret({
environmentId: EnvironmentId.make("bearer-environment"),
secret: "legacy-token",
}),
);
const migrated = yield* store.get;
assert.isTrue(Option.isSome(migrated));
if (Option.isNone(migrated)) {
return;
}
const catalog = yield* decodeConnectionCatalog(migrated.value);
assert.deepInclude(catalog.targets[0], {
_tag: "RelayConnectionTarget",
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
});
assert.deepInclude(catalog.targets[1], {
_tag: "SshConnectionTarget",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
connectionId: "ssh:ssh-environment",
});
assert.deepInclude(catalog.targets[2], {
_tag: "BearerConnectionTarget",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
connectionId: "bearer:bearer-environment",
});
assert.deepInclude(catalog.profiles[0], {
_tag: "SshConnectionProfile",
connectionId: "ssh:ssh-environment",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
});
assert.deepInclude(catalog.profiles[1], {
_tag: "BearerConnectionProfile",
connectionId: "bearer:bearer-environment",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
});
assert.equal(catalog.credentials.length, 1);
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
}
yield* savedEnvironments.setRegistry([]);
assert.deepEqual(yield* store.get, migrated);
}),
),
);
it.effect("surfaces malformed catalog documents without deleting them", () =>
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, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
);
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
}),
),
);
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
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: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
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);
}).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;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const failDecrypt = yield* Ref.make(false);
const layer = makeLayer(baseDir, true, failDecrypt);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(layer),
);
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
yield* Ref.set(failDecrypt, true);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
);
assert.equal(error.operation, "decrypt-catalog");
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
assert.instanceOf(decryptError.cause, Error);
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
assert.equal(
error.message,
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
);
assert.notEqual(error.message, decryptError.message);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
@@ -1,516 +0,0 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionTarget,
RelayConnectionTarget,
SshConnectionProfile,
SshConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
} from "@t3tools/client-runtime/platform";
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 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 Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const EncryptedConnectionCatalogDocument = Schema.Struct({
version: Schema.Literal(1),
encryptedCatalog: Schema.String,
});
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
RuntimeConnectionCatalogDocument,
);
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"create-temporary-file-name",
"encode-document",
"create-directory",
"write-temporary-file",
"replace-catalog-file",
]);
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"read-legacy-registry",
"read-legacy-secret",
"encode-catalog",
"persist-catalog",
]);
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-catalog",
"decrypt-catalog",
]);
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
"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}.`;
}
}
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
"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}.`;
}
}
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
"DesktopConnectionCatalogStoreReadError",
{
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
}
}
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>()(
"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}.`;
}
}
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
"DesktopConnectionCatalogStoreProtectionError",
{
operation: DesktopConnectionCatalogStoreProtectionOperation,
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
{
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDocumentDecodeError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| DesktopConnectionCatalogStoreProtectionError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
>;
readonly clear: Effect.Effect<void>;
}
>()("@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,
}),
),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
catalogPath: string,
): Effect.Effect<
Option.Option<EncryptedConnectionCatalogDocument>,
DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
> =>
fileSystem.readFileString(catalogPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound"
? Effect.succeed<string | null>(null)
: Effect.fail(
new DesktopConnectionCatalogStoreReadError({
catalogPath,
cause: 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,
}),
),
),
),
);
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly catalogPath: string;
readonly document: EncryptedConnectionCatalogDocument;
readonly suffix: string;
}): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "encode-document",
path: input.catalogPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* Effect.gen(function* () {
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "replace-catalog-file",
path: input.catalogPath,
cause,
}),
),
);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove a temporary connection catalog file.", {
tempPath,
error,
}),
),
),
),
);
});
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
return `${prefix}:${environmentId}`;
}
const migrateSavedEnvironmentRecords = Effect.fn(
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
)(function* (
records: readonly PersistedSavedEnvironmentRecord[],
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
catalogPath: string,
): Effect.fn.Return<
RuntimeConnectionCatalogDocumentType,
DesktopConnectionCatalogStoreMigrationError
> {
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
for (const record of records) {
if (record.relayManaged !== undefined) {
targets.push(
new RelayConnectionTarget({
environmentId: record.environmentId,
label: record.label,
}),
);
continue;
}
if (record.desktopSsh !== undefined) {
const id = connectionId("ssh", record.environmentId);
targets.push(
new SshConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new SshConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
target: record.desktopSsh,
}),
);
continue;
}
const id = connectionId("bearer", record.environmentId);
targets.push(
new BearerConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new BearerConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-secret",
catalogPath,
environmentId: record.environmentId,
cause,
}),
),
);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
credential: new BearerConnectionCredential({ token: token.value }),
});
}
}
return {
schemaVersion: 1,
targets,
profiles,
credentials,
remoteDpopTokens: [],
};
});
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");
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "check-encryption-availability",
catalogPath,
cause,
}),
),
);
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(
yield* safeStorage.encryptString(catalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "encrypt-catalog",
catalogPath,
cause,
}),
),
),
);
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-temporary-file-name",
path: catalogPath,
cause,
}),
),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
});
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* encryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-registry",
catalogPath,
cause,
}),
),
);
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "encode-catalog",
catalogPath,
cause,
}),
),
);
yield* writeCatalog(encoded).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "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;
}
if (!(yield* encryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
Effect.flatMap((encryptedCatalog) =>
safeStorage.decryptString(encryptedCatalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "decrypt-catalog",
catalogPath,
cause,
}),
),
),
),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* encryptionAvailable)) {
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"),
),
});
});
export const layer = Layer.effect(DesktopConnectionCatalogStore, make);
@@ -1,37 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import { DesktopLifecycleRelaunchError } from "./DesktopLifecycle.ts";
import { DesktopApplicationMenuActionError } from "../window/DesktopApplicationMenu.ts";
describe("desktop detached action errors", () => {
it("preserves the complete relaunch failure cause and reason", () => {
const cause = Cause.combine(
Cause.fail(new Error("shutdown failed")),
Cause.die(new Error("relaunch defect")),
);
const error = new DesktopLifecycleRelaunchError({
reason: "apply update",
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.reason, "apply update");
assert.equal(error.message, 'Desktop relaunch failed for reason "apply update".');
});
it("preserves the complete menu action failure cause and action", () => {
const cause = Cause.combine(
Cause.fail(new Error("window unavailable")),
Cause.die(new Error("dispatch defect")),
);
const error = new DesktopApplicationMenuActionError({
action: "open-settings",
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.action, "open-settings");
assert.equal(error.message, 'Desktop menu action "open-settings" failed.');
});
});
+55 -50
View File
@@ -11,7 +11,10 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Path from "effect/Path"; 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 * as DesktopConfig from "./DesktopConfig.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts"; import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
@@ -27,53 +30,55 @@ export interface MakeDesktopEnvironmentInput {
readonly runningUnderArm64Translation: boolean; 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< export class DesktopEnvironment extends Context.Service<
DesktopEnvironment, DesktopEnvironment,
{ 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: DesktopAppSettings.DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
>()("@t3tools/desktop/app/DesktopEnvironment") {} >()("@t3tools/desktop/app/DesktopEnvironment") {}
const APP_BASE_NAME = "T3 Code"; 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, 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 path = yield* Path.Path;
const config = yield* DesktopConfig.DesktopConfig; const config = yield* DesktopConfig.DesktopConfig;
const homeDirectory = input.homeDirectory; const homeDirectory = input.homeDirectory;
@@ -203,7 +208,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code", linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
userDataDirName, userDataDirName,
legacyUserDataDirName, legacyUserDataDirName,
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion), defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
runtimeInfo: resolveDesktopRuntimeInfo({ runtimeInfo: resolveDesktopRuntimeInfo({
platform: input.platform, platform: input.platform,
processArch: input.processArch, processArch: input.processArch,
@@ -245,4 +250,4 @@ const make = Effect.fn("desktop.environment.make")(function* (
}); });
export const layer = (input: MakeDesktopEnvironmentInput) => export const layer = (input: MakeDesktopEnvironmentInput) =>
Layer.effect(DesktopEnvironment, make(input)); Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
+124 -102
View File
@@ -1,55 +1,75 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope"; import * as Scope from "effect/Scope";
import type * as Electron from "electron"; import type * as Electron from "electron";
import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts"; import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as DesktopState from "./DesktopState.ts"; import * as DesktopState from "./DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts";
export class DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()( export interface DesktopShutdownShape {
"DesktopLifecycleRelaunchError", readonly request: Effect.Effect<void>;
{ readonly awaitRequest: Effect.Effect<void>;
reason: Schema.String, readonly markComplete: Effect.Effect<void>;
cause: Schema.Defect(), readonly awaitComplete: Effect.Effect<void>;
}, readonly isComplete: Effect.Effect<boolean>;
) {
override get message(): string {
return `Desktop relaunch failed for reason "${this.reason}".`;
}
} }
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 = export type DesktopLifecycleRuntimeServices =
| DesktopEnvironment.DesktopEnvironment | DesktopEnvironment.DesktopEnvironment
| DesktopShutdown.DesktopShutdown | DesktopShutdown
| DesktopState.DesktopState | DesktopState.DesktopState
| DesktopWindow.DesktopWindow | DesktopWindow.DesktopWindow
| ElectronApp.ElectronApp | ElectronApp.ElectronApp
| ElectronTheme.ElectronTheme; | 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 * @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
*/ */
export class DesktopLifecycle extends Context.Service< export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
DesktopLifecycle, "@t3tools/desktop/app/DesktopLifecycle",
{ ) {}
readonly relaunch: (
reason: string,
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
>()("@t3tools/desktop/app/DesktopLifecycle") {}
const { logInfo: logLifecycleInfo, logError: logLifecycleError } = const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
makeComponentLogger("desktop-lifecycle"); DesktopObservability.makeComponentLogger("desktop-lifecycle");
function addScopedListener<Args extends ReadonlyArray<unknown>>( function addScopedListener<Args extends ReadonlyArray<unknown>>(
target: unknown, target: unknown,
@@ -73,8 +93,8 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
} }
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")( const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> { function* (): Effect.fn.Return<void, never, DesktopShutdown> {
const shutdown = yield* DesktopShutdown.DesktopShutdown; const shutdown = yield* DesktopShutdown;
yield* shutdown.request; yield* shutdown.request;
yield* shutdown.awaitComplete; yield* shutdown.awaitComplete;
}, },
@@ -134,81 +154,83 @@ function quitFromSignal(
); );
} }
export const make = DesktopLifecycle.of({ export const layer = Layer.succeed(
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) { DesktopLifecycle,
const electronApp = yield* ElectronApp.ElectronApp; DesktopLifecycle.of({
const environment = yield* DesktopEnvironment.DesktopEnvironment; relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const state = yield* DesktopState.DesktopState; const electronApp = yield* ElectronApp.ElectronApp;
yield* logLifecycleInfo("desktop relaunch requested", { reason }); const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.gen(function* () { const state = yield* DesktopState.DesktopState;
yield* Effect.yieldNow; yield* logLifecycleInfo("desktop relaunch requested", { reason });
yield* Ref.set(state.quitting, true); yield* Effect.gen(function* () {
yield* requestDesktopShutdownAndWait(); yield* Effect.yieldNow;
if (environment.isDevelopment) { yield* Ref.set(state.quitting, true);
yield* electronApp.exit(75); yield* requestDesktopShutdownAndWait();
return; 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({ }).pipe(Effect.withSpan("desktop.lifecycle.register")),
execPath: process.execPath,
args: process.argv.slice(1),
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) => {
const error = new DesktopLifecycleRelaunchError({ reason, cause });
return logLifecycleError(error.message, { error });
}),
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);
});
}
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
});
export const layer = Layer.succeed(DesktopLifecycle, make);
+282 -8
View File
@@ -1,20 +1,52 @@
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability"; import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; 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 Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger"; import * as Logger from "effect/Logger";
import * as Option from "effect/Option"; 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 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 * as Tracer from "effect/Tracer";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.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; 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>; 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 fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment; const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option); const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
@@ -70,6 +260,90 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
return yield* readPersistedOtlpTracesUrl; 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( const desktopLoggerLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }), Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"), Layer.succeed(References.MinimumLogLevel, "Info"),
@@ -82,8 +356,8 @@ const tracerLayer = Layer.unwrap(
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson"); const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
const sink = yield* makeTraceSink({ const sink = yield* makeTraceSink({
filePath: tracePath, filePath: tracePath,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES, maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES, maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS, batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
}); });
const delegate = Option.isNone(otlpTracesUrl) const delegate = Option.isNone(otlpTracesUrl)
@@ -101,8 +375,8 @@ const tracerLayer = Layer.unwrap(
}); });
const tracer = yield* makeLocalFileTracer({ const tracer = yield* makeLocalFileTracer({
filePath: tracePath, filePath: tracePath,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES, maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES, maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS, batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
sink, sink,
...(delegate ? { delegate } : {}), ...(delegate ? { delegate } : {}),
@@ -113,7 +387,7 @@ const tracerLayer = Layer.unwrap(
).pipe(Layer.provideMerge(OtlpSerialization.layerJson)); ).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll( export const layer = Layer.mergeAll(
DesktopBackendOutputLogModule.layer, backendOutputLogLayer,
desktopLoggerLayer, desktopLoggerLayer,
tracerLayer, tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"), Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
-35
View File
@@ -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);
+15 -13
View File
@@ -3,17 +3,19 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref"; 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, DesktopState,
{ Effect.all({
readonly backendReady: Ref.Ref<boolean>; backendReady: Ref.make(false),
readonly quitting: Ref.Ref<boolean>; quitting: Ref.make(false),
} }),
>()("@t3tools/desktop/app/DesktopState") {} );
const make = Effect.all({
backendReady: Ref.make(false),
quitting: Ref.make(false),
});
export const layer = Layer.effect(DesktopState, make);
@@ -3,8 +3,6 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -23,10 +21,6 @@ const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
Schema.fromJsonString(PersistedServerObservabilitySettingsDocument), Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
); );
const isDesktopBackendObservabilitySettingsReadError = Schema.is(
DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
);
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, { const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"), getState: Effect.die("unexpected getState"),
backendConfig: Effect.succeed({ backendConfig: Effect.succeed({
@@ -40,7 +34,7 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
setMode: () => Effect.die("unexpected setMode"), setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"), setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]), getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]); } satisfies DesktopServerExposure.DesktopServerExposureShape);
function makeEnvironmentLayer( function makeEnvironmentLayer(
baseDir: string, baseDir: string,
@@ -172,62 +166,6 @@ describe("DesktopBackendConfiguration", () => {
), ),
); );
it.effect("logs structured context when persisted observability settings cannot be read", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const settingsPath = `${baseDir}/userdata/settings.json`;
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: settingsPath,
});
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
const failingFileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(cause),
}),
);
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolve;
}).pipe(
Effect.provide(
Layer.mergeAll(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
Layer.provideMerge(failingFileSystemLayer),
),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
const error = messages
.flatMap((message) => (Array.isArray(message) ? message : [message]))
.find(isDesktopBackendObservabilitySettingsReadError);
assert.isDefined(error);
assert.equal(error.settingsPath, settingsPath);
assert.equal(error.cause, cause);
assert.equal(
error.message,
`Failed to read persisted backend observability settings at ${settingsPath}.`,
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("captures backend output in development so child process logs can be persisted", () => it.effect("captures backend output in development so child process logs can be persisted", () =>
Effect.gen(function* () { Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem; const fileSystem = yield* FileSystem.FileSystem;
@@ -8,32 +8,22 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError"; import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as DesktopBackendManager from "./DesktopBackendManager.ts"; import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts"; import * as DesktopServerExposure from "./DesktopServerExposure.ts";
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()( export interface DesktopBackendConfigurationShape {
"DesktopBackendObservabilitySettingsReadError", readonly resolve: Effect.Effect<
{ DesktopBackendManager.DesktopBackendStartConfig,
settingsPath: Schema.String, PlatformError.PlatformError
cause: Schema.Defect(), >;
},
) {
override get message(): string {
return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
}
} }
export class DesktopBackendConfiguration extends Context.Service< export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration, DesktopBackendConfiguration,
{ DesktopBackendConfigurationShape
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
}
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {} >()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
interface BackendObservabilitySettings { interface BackendObservabilitySettings {
@@ -62,34 +52,29 @@ const DESKTOP_BACKEND_ENV_NAMES = [
const backendChildEnvPatch = (): Record<string, string | undefined> => const backendChildEnvPatch = (): Record<string, string | undefined> =>
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined])); Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
const logBackendObservabilitySettingsReadFailure = ( const { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
settingsPath: string, "desktop-backend-configuration",
cause: PlatformError.PlatformError, );
) => {
const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
return Effect.logWarning(error).pipe(
Effect.annotateLogs({
component: "desktop-backend-configuration",
error,
}),
);
};
const readPersistedBackendObservabilitySettings = Effect.gen(function* () { const readPersistedBackendObservabilitySettings: Effect.Effect<
BackendObservabilitySettings,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem; const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment; const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe( const exists = yield* fileSystem
Effect.map(Option.some), .exists(environment.serverSettingsPath)
Effect.catchTags({ .pipe(Effect.orElseSucceed(() => false));
PlatformError: (cause) => if (!exists) {
cause.reason._tag === "NotFound" return emptyBackendObservabilitySettings;
? Effect.succeed(Option.none()) }
: logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
Effect.as(Option.none()), const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
),
}),
);
if (Option.isNone(raw)) { if (Option.isNone(raw)) {
yield* logBackendConfigurationWarning(
"failed to read persisted backend observability settings",
);
return emptyBackendObservabilitySettings; return emptyBackendObservabilitySettings;
} }
@@ -145,39 +130,40 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
}, },
); );
export const make = Effect.gen(function* () { export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment; DesktopBackendConfiguration,
const fileSystem = yield* FileSystem.FileSystem; Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; const environment = yield* DesktopEnvironment.DesktopEnvironment;
const crypto = yield* Crypto.Crypto; const fileSystem = yield* FileSystem.FileSystem;
const tokenRef = yield* Ref.make(Option.none<string>()); const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const getOrCreateBootstrapToken = Effect.gen(function* () { const crypto = yield* Crypto.Crypto;
const existing = yield* Ref.get(tokenRef); const tokenRef = yield* Ref.make(Option.none<string>());
if (Option.isSome(existing)) { const getOrCreateBootstrapToken = Effect.gen(function* () {
return existing.value; const existing = yield* Ref.get(tokenRef);
} if (Option.isSome(existing)) {
return existing.value;
}
const token = Encoding.encodeHex(yield* crypto.randomBytes(24)); const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token)); yield* Ref.set(tokenRef, Option.some(token));
return token; return token;
}); });
return DesktopBackendConfiguration.of({ return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () { resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken; const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe( const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
); );
return yield* resolveBackendStartConfig({ return yield* resolveBackendStartConfig({
bootstrapToken, bootstrapToken,
observabilitySettings, observabilitySettings,
}).pipe( }).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure), Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
); );
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")), }).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
}); });
}); }),
);
export const layer = Layer.effect(DesktopBackendConfiguration, make);
@@ -3,15 +3,12 @@ import {
type DesktopBackendBootstrap as DesktopBackendBootstrapValue, type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest"; import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred"; import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration"; import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue"; import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
@@ -31,7 +28,6 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect( const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap), Schema.fromJsonString(DesktopBackendBootstrap),
); );
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = { const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron", executablePath: "/electron",
@@ -59,9 +55,9 @@ const configWithObservability: DesktopBackendBootstrapValue = {
}; };
function makeProcess(options?: { function makeProcess(options?: {
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>; readonly stdout?: Stream.Stream<Uint8Array>;
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>; readonly stderr?: Stream.Stream<Uint8Array>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>; readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"]; readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
}): ChildProcessSpawner.ChildProcessHandle { }): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({ return ChildProcessSpawner.makeHandle({
@@ -108,9 +104,9 @@ function decodeBootstrap(raw: string) {
function makeManagerLayer(input: { function makeManagerLayer(input: {
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>; readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>; readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>; readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
readonly desktopState?: DesktopState.DesktopState["Service"]; readonly desktopState?: DesktopState.DesktopStateShape;
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>; readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig; readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
}) { }) {
return DesktopBackendManager.layer.pipe( return DesktopBackendManager.layer.pipe(
@@ -131,7 +127,7 @@ function makeManagerLayer(input: {
writeSessionBoundary: () => Effect.void, writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void, writeOutputChunk: () => Effect.void,
...input.backendOutputLog, ...input.backendOutputLog,
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]), } satisfies DesktopObservability.DesktopBackendOutputLogShape),
Layer.succeed(DesktopWindow.DesktopWindow, { Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected createMain"), createMain: Effect.die("unexpected createMain"),
ensureMain: Effect.die("unexpected ensureMain"), ensureMain: Effect.die("unexpected ensureMain"),
@@ -142,30 +138,13 @@ function makeManagerLayer(input: {
dispatchMenuAction: () => Effect.void, dispatchMenuAction: () => Effect.void,
syncAppearance: Effect.void, syncAppearance: Effect.void,
...input.desktopWindow, ...input.desktopWindow,
} satisfies DesktopWindow.DesktopWindow["Service"]), } satisfies DesktopWindow.DesktopWindowShape),
), ),
), ),
); );
} }
describe("DesktopBackendManager", () => { describe("DesktopBackendManager", () => {
it("preserves the complete restart cause and schedule context", () => {
const cause = Cause.combine(
Cause.fail(new Error("start failed")),
Cause.die(new Error("restart defect")),
);
const error = new DesktopBackendManager.DesktopBackendRestartError({
reason: "backend exited with code 1",
delayMs: 500,
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.reason, "backend exited with code 1");
assert.equal(error.delayMs, 500);
assert.equal(error.message, "Desktop backend restart failed after a scheduled 500ms delay.");
});
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () => it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
Effect.gen(function* () { Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined; let spawnedCommand: ChildProcess.Command | undefined;
@@ -239,243 +218,6 @@ describe("DesktopBackendManager", () => {
}), }),
); );
it.effect("preserves the readiness timeout cause and process context", () =>
Effect.gen(function* () {
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
const layer = Layer.merge(
TestClock.layer(),
httpClientLayer((request) =>
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
),
);
yield* Effect.gen(function* () {
const readiness = yield* DesktopBackendManager.waitForHttpReady({
executablePath: baseConfig.executablePath,
entryPath: baseConfig.entryPath,
cwd: baseConfig.cwd,
httpBaseUrl: baseConfig.httpBaseUrl,
timeout: Duration.millis(50),
}).pipe(Effect.flip, Effect.forkChild);
const request = yield* Deferred.await(requested);
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(readiness);
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
assert.equal(error.timeoutMs, 50);
assert.isTrue(Cause.isTimeoutError(error.cause));
assert.equal(
error.message,
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
);
}).pipe(Effect.provide(layer));
}),
);
it.effect("reports bootstrap encoding failures with stable process context", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
bootstrap: {
...baseConfig.bootstrap,
port: 0,
},
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessBootstrapEncodeError") {
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.isDefined(error.cause);
assert.equal(
error.message,
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves spawn failures without deriving their message from the cause", () =>
Effect.gen(function* () {
const spawnCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcessSpawner",
method: "spawn",
pathOrDescriptor: baseConfig.executablePath,
description: "low-level detail that must not become the public message",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessSpawnError") {
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, spawnCause);
assert.equal(
error.message,
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
);
assert.notInclude(error.message, spawnCause.message);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves exit-status failures without copying their detail into the message", () =>
Effect.gen(function* () {
const exitCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "exitCode",
description: "exit-status-secret-sentinel",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Effect.fail(exitCause),
}),
),
),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessExitStatusError") {
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
}
assert.equal(error.pid, 123);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, exitCause);
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
assert.notInclude(error.message, "exit-status-secret-sentinel");
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("reports output stream failures with process and stream context", () =>
Effect.gen(function* () {
const outputCause = PlatformError.systemError({
_tag: "BadResource",
module: "ChildProcess",
method: "stdout",
description: "output-stream-secret-sentinel",
});
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fail(outputCause),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputReadError") {
return assert.fail(`Expected output read error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.strictEqual(error.cause, outputCause);
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
assert.notInclude(error.message, "output-stream-secret-sentinel");
}),
);
it.effect("reports output handler failures separately from stream read failures", () =>
Effect.gen(function* () {
const chunk = new TextEncoder().encode("backend output");
const outputCause = new Error("output-handler-secret-sentinel");
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.make(chunk),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
onOutput: () => Effect.fail(outputCause),
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputHandlingError") {
return assert.fail(`Expected output handling error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.equal(error.chunkByteLength, chunk.byteLength);
assert.strictEqual(error.cause, outputCause);
assert.equal(
error.message,
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
);
assert.notInclude(error.message, "output-handler-secret-sentinel");
}),
);
it.effect("retries HTTP readiness before reporting the backend ready", () => it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.gen(function* () { Effect.gen(function* () {
const requestUrls: Array<string> = []; const requestUrls: Array<string> = [];
+86 -258
View File
@@ -1,5 +1,6 @@
import * as Cause from "effect/Cause"; import * as Cause from "effect/Cause";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration"; import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit"; import * as Exit from "effect/Exit";
@@ -9,14 +10,14 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError"; import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule"; import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore"; import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope"; import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream"; import * as Stream from "effect/Stream";
import * as HttpClient from "effect/unstable/http/HttpClient"; import { HttpClient } from "effect/unstable/http";
import * as ChildProcess from "effect/unstable/process/ChildProcess"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { import {
DesktopBackendBootstrap, DesktopBackendBootstrap,
@@ -42,145 +43,59 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr"; export type BackendProcessOutputStream = "stdout" | "stderr";
export interface BackendProcessContext { export interface DesktopBackendStartConfig {
readonly executablePath: string; readonly executablePath: string;
readonly entryPath: string; readonly entryPath: string;
readonly cwd: string; readonly cwd: string;
readonly httpBaseUrl: URL;
}
export interface DesktopBackendStartConfig extends BackendProcessContext {
readonly env: Record<string, string | undefined>; readonly env: Record<string, string | undefined>;
readonly bootstrap: DesktopBackendBootstrapValue; readonly bootstrap: DesktopBackendBootstrapValue;
readonly httpBaseUrl: URL;
readonly captureOutput: boolean; readonly captureOutput: boolean;
} }
interface BackendProcessExit { interface BackendProcessExit {
readonly code: Option.Option<number>; readonly code: Option.Option<number>;
readonly reason: string; readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
} }
const backendProcessContextSchema = { export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
executablePath: Schema.String, readonly url: URL;
entryPath: Schema.String, }> {
cwd: Schema.String, override get message() {
httpBaseUrl: Schema.URL, return `Timed out waiting for backend readiness at ${this.url.href}.`;
};
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
"BackendReadinessTimeoutError",
{
...backendProcessContextSchema,
readinessUrl: Schema.URL,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
} }
} }
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()( class BackendProcessBootstrapEncodeError extends Data.TaggedError(
"BackendProcessBootstrapEncodeError", "BackendProcessBootstrapEncodeError",
{ )<{
...backendProcessContextSchema, readonly cause: Schema.SchemaError;
cause: Schema.Defect(), }> {
}, override get message() {
) { return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
override get message(): string {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
} }
} }
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()( class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
"BackendProcessSpawnError", readonly cause: PlatformError.PlatformError;
{ }> {
...backendProcessContextSchema, override get message() {
cause: Schema.Defect(), return `Failed to spawn desktop backend process: ${this.cause.message}`;
},
) {
override get message(): string {
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
} }
} }
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()( type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
"BackendProcessOutputReadError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
}
}
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
"BackendProcessOutputHandlingError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
chunkByteLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
}
}
export type BackendProcessOutputError =
| BackendProcessOutputReadError
| BackendProcessOutputHandlingError;
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
"BackendProcessExitStatusError",
{
...backendProcessContextSchema,
pid: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
}
}
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
"DesktopBackendRestartError",
{
reason: Schema.String,
delayMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
}
}
export const BackendProcessError = Schema.Union([
BackendProcessBootstrapEncodeError,
BackendProcessSpawnError,
BackendProcessExitStatusError,
]);
export type BackendProcessError = typeof BackendProcessError.Type;
interface RunBackendProcessOptions extends DesktopBackendStartConfig { interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly readinessTimeout?: Duration.Duration; readonly readinessTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>; readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>; readonly onReady?: () => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>; readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onOutput?: ( readonly onOutput?: (
streamName: BackendProcessOutputStream, streamName: BackendProcessOutputStream,
chunk: Uint8Array, chunk: Uint8Array,
) => Effect.Effect<void, Error>; ) => Effect.Effect<void>;
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
} }
export interface DesktopBackendSnapshot { export interface DesktopBackendSnapshot {
@@ -191,14 +106,16 @@ export interface DesktopBackendSnapshot {
readonly restartScheduled: boolean; 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< export class DesktopBackendManager extends Context.Service<
DesktopBackendManager, DesktopBackendManager,
{ 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>;
}
>()("@t3tools/desktop/backend/DesktopBackendManager") {} >()("@t3tools/desktop/backend/DesktopBackendManager") {}
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } = const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
@@ -259,10 +176,11 @@ const closeRun = (
).pipe(Effect.ignore); ).pipe(Effect.ignore);
}; };
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* ( const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
options: BackendProcessContext & { readonly timeout: Duration.Duration }, baseUrl: URL,
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> { timeout: Duration.Duration,
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl); ): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
const client = (yield* HttpClient.HttpClient).pipe( const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.filterStatusOk, HttpClient.filterStatusOk,
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)), HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
@@ -271,78 +189,48 @@ export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpRea
yield* client.get(readinessUrl).pipe( yield* client.get(readinessUrl).pipe(
Effect.asVoid, Effect.asVoid,
Effect.timeout(options.timeout), Effect.timeout(timeout),
Effect.mapError( Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
(cause) =>
new BackendReadinessTimeoutError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
readinessUrl,
timeoutMs: Duration.toMillis(options.timeout),
cause,
}),
),
); );
}); });
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
): BackendProcessExit {
if (Result.isSuccess(result)) {
return {
code: Option.some(result.success),
reason: `code=${result.success}`,
result,
};
}
return {
code: Option.none(),
reason: result.failure.message,
result,
};
}
function drainBackendOutput( function drainBackendOutput(
context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream, streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>, stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: ( onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>,
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
): Effect.Effect<void> { ): Effect.Effect<void> {
return stream.pipe( return stream.pipe(
Stream.mapError( Stream.runForEach((chunk) => onOutput(streamName, chunk)),
(cause) => Effect.ignore,
new BackendProcessOutputReadError({
...context,
streamName,
cause,
}),
),
Stream.runForEach((chunk) =>
onOutput(streamName, chunk).pipe(
Effect.mapError(
(cause) =>
new BackendProcessOutputHandlingError({
...context,
streamName,
chunkByteLength: chunk.byteLength,
cause,
}),
),
),
),
Effect.catchTags({
BackendProcessOutputReadError: onOutputFailure,
BackendProcessOutputHandlingError: onOutputFailure,
}),
); );
} }
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap)); const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions, options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> { ): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe( const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError( Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
(cause) =>
new BackendProcessBootstrapEncodeError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
); );
const onOutput = options.onOutput ?? (() => Effect.void); const onOutput = options.onOutput ?? (() => Effect.void);
const command = ChildProcess.make( const command = ChildProcess.make(
@@ -368,78 +256,28 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
}, },
); );
const handle = yield* spawner.spawn(command).pipe( const handle = yield* spawner
Effect.mapError( .spawn(command)
(cause) => .pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
new BackendProcessSpawnError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
);
yield* options.onStarted?.(handle.pid) ?? Effect.void; yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) { if (options.captureOutput) {
const outputContext = { yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
executablePath: options.executablePath, yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
} }
yield* waitForHttpReady({ yield* waitForHttpReady(
executablePath: options.executablePath, options.httpBaseUrl,
entryPath: options.entryPath, options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
cwd: options.cwd, ).pipe(
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void), Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catchTags({ Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.forkScoped, Effect.forkScoped,
); );
const exitCode = yield* handle.exitCode.pipe( return describeProcessExit(yield* Effect.result(handle.exitCode));
Effect.mapError(
(cause) =>
new BackendProcessExitStatusError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
cause,
}),
),
);
return {
code: Option.some(exitCode),
reason: `code=${exitCode}`,
} satisfies BackendProcessExit;
}); });
export const make = Effect.gen(function* () { const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
const parentScope = yield* Scope.Scope; const parentScope = yield* Scope.Scope;
const fileSystem = yield* FileSystem.FileSystem; const fileSystem = yield* FileSystem.FileSystem;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
@@ -494,7 +332,7 @@ export const make = Effect.gen(function* () {
const config = yield* configuration.resolve.pipe( const config = yield* configuration.resolve.pipe(
Effect.tapError((error) => Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", { logBackendManagerError("failed to generate desktop backend configuration", {
cause: error, cause: error.message,
}), }),
), ),
Effect.option, Effect.option,
@@ -632,26 +470,22 @@ export const make = Effect.gen(function* () {
yield* desktopWindow.handleBackendReady.pipe( yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) => Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", { logBackendManagerError("failed to open main window after backend readiness", {
cause: error, message: error.message,
}), }),
), ),
); );
}), }),
onReadinessFailure: (error) => onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", { logBackendManagerWarning("backend readiness check failed during bootstrap", {
error, error: error.message,
}), }),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk), onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
}).pipe( }).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(HttpClient.HttpClient, httpClient), Effect.provideService(HttpClient.HttpClient, httpClient),
Scope.provide(runScope), Scope.provide(runScope),
Effect.matchEffect({ Effect.matchEffect({
onFailure: (error) => onFailure: (error) => finalizeRun(error.message),
logBackendManagerError(error.message, { error }).pipe(
Effect.andThen(finalizeRun(error.message)),
),
onSuccess: (exit) => finalizeRun(exit.reason), onSuccess: (exit) => finalizeRun(exit.reason),
}), }),
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)), Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
@@ -706,17 +540,11 @@ export const make = Effect.gen(function* () {
}), }),
), ),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)), Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
Effect.catchCause((cause) => { Effect.catchCause((cause) =>
if (Cause.hasInterruptsOnly(cause)) { logBackendManagerError("desktop backend restart fiber failed", {
return Effect.void; cause: Cause.pretty(cause),
} }),
const error = new DesktopBackendRestartError({ ),
reason,
delayMs: Duration.toMillis(delay),
cause,
});
return logBackendManagerError(error.message, { error });
}),
), ),
parentScope, parentScope,
); );
@@ -775,4 +603,4 @@ export const make = Effect.gen(function* () {
}); });
}); });
export const layer = Layer.effect(DesktopBackendManager, make); export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());
@@ -1,83 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
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 * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
const config: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
env: {},
bootstrap: {
mode: "desktop",
noBrowser: true,
port: 3773,
t3Home: "/tmp/t3",
host: "127.0.0.1",
desktopBootstrapToken: "desktop-bootstrap-token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
};
describe("DesktopLocalEnvironmentAuth", () => {
it.effect("exchanges the desktop bootstrap credential only once", () =>
Effect.gen(function* () {
const requestCount = yield* Ref.make(0);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Ref.update(requestCount, (count) => count + 1).pipe(
Effect.as(
HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
access_token: "desktop-bearer-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "Bearer",
expires_in: 3600,
scope: "orchestration:read",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
),
),
),
),
);
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(config)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
}),
});
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
}).pipe(Effect.provide(testLayer));
assert.strictEqual(first, "desktop-bearer-token");
assert.strictEqual(second, "desktop-bearer-token");
assert.strictEqual(yield* Ref.get(requestCount), 1);
}),
);
});
@@ -1,88 +0,0 @@
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
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 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 * as DesktopBackendManager from "./DesktopBackendManager.ts";
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
{},
) {
override get message(): string {
return "Local backend is not configured.";
}
}
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 DesktopLocalEnvironmentAuth extends Context.Service<
DesktopLocalEnvironmentAuth,
{
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
}
>()("@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);
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"));
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
});
export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);
@@ -1,65 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { networkInterfacesMock } = vi.hoisted(() => ({
networkInterfacesMock: vi.fn(),
}));
vi.mock("node:os", () => ({
networkInterfaces: networkInterfacesMock,
}));
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
const TestLayer = DesktopNetworkInterfaces.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
describe("DesktopNetworkInterfaces", () => {
beforeEach(() => {
networkInterfacesMock.mockReset();
});
it.effect("reads network interfaces through the service", () => {
const interfaces = {
en0: [
{
address: "192.168.1.10",
family: "IPv4",
internal: false,
},
],
};
networkInterfacesMock.mockReturnValueOnce(interfaces);
return Effect.gen(function* () {
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
assert.strictEqual(yield* service.read, interfaces);
}).pipe(Effect.provide(TestLayer));
});
it.effect("preserves network interface read failures as structured defects", () => {
const cause = new Error("network interface probe failed");
networkInterfacesMock.mockImplementationOnce(() => {
throw cause;
});
return Effect.gen(function* () {
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
const exit = yield* Effect.exit(service.read);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopNetworkInterfaces.DesktopNetworkInterfacesReadError);
assert.equal(error.platform, "linux");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Failed to read desktop network interfaces on linux.");
}
}).pipe(Effect.provide(TestLayer));
});
});
@@ -1,52 +0,0 @@
import * as NodeOS from "node:os";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
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 DesktopNetworkInterfacesReadError extends Schema.TaggedErrorClass<DesktopNetworkInterfacesReadError>()(
"DesktopNetworkInterfacesReadError",
{
platform: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read desktop network interfaces on ${this.platform}.`;
}
}
export class DesktopNetworkInterfaces extends Context.Service<
DesktopNetworkInterfaces,
{
readonly read: Effect.Effect<NetworkInterfaces>;
}
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return DesktopNetworkInterfaces.of({
read: Effect.try({
try: () => NodeOS.networkInterfaces(),
catch: (cause) => new DesktopNetworkInterfacesReadError({ platform, cause }),
}).pipe(Effect.orDie),
});
});
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
@@ -7,18 +7,21 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink"; import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream"; 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 DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts"; import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
const encoder = new TextEncoder(); const encoder = new TextEncoder();
const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {}; const emptyNetworkInterfaces: DesktopNetworkInterfaces = {};
const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = { const lanNetworkInterfaces: DesktopNetworkInterfaces = {
en0: [ en0: [
{ {
address: "192.168.1.20", address: "192.168.1.20",
@@ -28,7 +31,7 @@ const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
], ],
}; };
const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = { const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
tailscale0: [ tailscale0: [
{ {
address: "100.90.1.2", address: "100.90.1.2",
@@ -69,7 +72,7 @@ function dieOnSpawnLayer() {
} }
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) { function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
return DesktopEnvironment.layer({ return makeDesktopEnvironmentLayer({
dirname: "/repo/apps/desktop/src", dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir, homeDirectory: baseDir,
platform: "darwin", platform: "darwin",
@@ -88,19 +91,18 @@ function makeEnvironmentLayer(baseDir: string, env: Record<string, string | unde
function makeLayer(input: { function makeLayer(input: {
readonly baseDir: string; readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces; readonly networkInterfaces?: DesktopNetworkInterfaces;
readonly env?: Record<string, string | undefined>; readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>; readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
}) { }) {
const env = { T3CODE_HOME: input.baseDir, ...input.env }; const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, 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), read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
}); });
return DesktopServerExposure.layer.pipe( return DesktopServerExposure.layer.pipe(
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer), Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer), Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici), Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()), Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
@@ -111,19 +113,18 @@ function makeLayer(input: {
} }
const withHarness = <A, E, R>( const withHarness = <A, E, R>(
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces, networkInterfaces: DesktopNetworkInterfaces,
effect: Effect.Effect< effect: Effect.Effect<
A, A,
E, E,
| R | R
| DesktopEnvironment.DesktopEnvironment | DesktopEnvironment
| FileSystem.FileSystem | FileSystem.FileSystem
| DesktopServerExposure.DesktopServerExposure | DesktopServerExposure.DesktopServerExposure
| DesktopAppSettings.DesktopAppSettings | DesktopAppSettings.DesktopAppSettings
>, >,
env: Record<string, string | undefined> = {}, env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>, spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
) => ) =>
Effect.gen(function* () { Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem; const fileSystem = yield* FileSystem.FileSystem;
@@ -137,7 +138,6 @@ const withHarness = <A, E, R>(
networkInterfaces, networkInterfaces,
env, env,
...(spawnerLayer ? { spawnerLayer } : {}), ...(spawnerLayer ? { spawnerLayer } : {}),
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
}), }),
), ),
); );
@@ -240,67 +240,6 @@ describe("DesktopServerExposure", () => {
), ),
); );
it.effect("preserves persistence request context and the settings failure chain", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
operation: "replace-settings-file",
path: "/tmp/desktop-settings.json",
cause: diskFailure,
});
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setServerExposureMode: () => Effect.fail(settingsFailure),
setTailscaleServe: () => Effect.fail(settingsFailure),
setUpdateChannel: () => Effect.die("unexpected update channel change"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
return withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
assert.instanceOf(
modeError,
DesktopServerExposure.DesktopServerExposureModePersistenceError,
);
assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
assert.equal(modeError.mode, "network-accessible");
assert.strictEqual(modeError.cause, settingsFailure);
assert.strictEqual(modeError.cause.cause, diskFailure);
assert.equal(
modeError.message,
"Failed to persist desktop server exposure mode network-accessible.",
);
assert.notInclude(modeError.message, diskFailure.message);
const tailscaleError = yield* serverExposure
.setTailscaleServeEnabled({ enabled: true, port: 8443 })
.pipe(Effect.flip);
assert.instanceOf(
tailscaleError,
DesktopServerExposure.DesktopTailscaleServePersistenceError,
);
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
assert.equal(tailscaleError.enabled, true);
assert.equal(tailscaleError.port, 8443);
assert.strictEqual(tailscaleError.cause, settingsFailure);
assert.strictEqual(tailscaleError.cause.cause, diskFailure);
assert.equal(
tailscaleError.message,
"Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).",
);
assert.notInclude(tailscaleError.message, diskFailure.message);
}),
{},
undefined,
settingsLayer,
);
});
it.effect("resolves advertised endpoints from the scoped runtime state", () => it.effect("resolves advertised endpoints from the scoped runtime state", () =>
withHarness( withHarness(
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces }, { ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
@@ -1,35 +1,50 @@
import * as NodeOS from "node:os";
import { import {
createAdvertisedEndpoint, createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput, type CreateAdvertisedEndpointInput,
} from "@t3tools/shared/advertisedEndpoint"; } from "@t3tools/shared/advertisedEndpoint";
import { import type {
DesktopServerExposureModeSchema, AdvertisedEndpoint,
type AdvertisedEndpoint, AdvertisedEndpointProvider,
type AdvertisedEndpointProvider, DesktopServerExposureMode,
type DesktopServerExposureMode, DesktopServerExposureState,
type DesktopServerExposureState,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration"; import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema"; import { HttpClient } from "effect/unstable/http";
import * as HttpClient from "effect/unstable/http/HttpClient"; import { ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
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 DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.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); const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1"; export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0"; 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 { interface ResolvedDesktopServerExposure {
readonly mode: DesktopServerExposureMode; readonly mode: DesktopServerExposureMode;
readonly bindHost: string; readonly bindHost: string;
@@ -76,7 +91,7 @@ const isHttpsEndpointUrl = (value: string): boolean => {
}; };
const resolveLanAdvertisedHost = ( const resolveLanAdvertisedHost = (
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces, networkInterfaces: DesktopNetworkInterfaces,
explicitHost: string | undefined, explicitHost: string | undefined,
): string | null => { ): string | null => {
const normalizedExplicitHost = normalizeOptionalHost(explicitHost); const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
@@ -101,7 +116,7 @@ const resolveLanAdvertisedHost = (
const resolveDesktopServerExposure = (input: { const resolveDesktopServerExposure = (input: {
readonly mode: DesktopServerExposureMode; readonly mode: DesktopServerExposureMode;
readonly port: number; readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces; readonly networkInterfaces: DesktopNetworkInterfaces;
readonly advertisedHostOverride?: string; readonly advertisedHostOverride?: string;
}): ResolvedDesktopServerExposure => { }): ResolvedDesktopServerExposure => {
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`; const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
@@ -203,56 +218,34 @@ const resolveDesktopCoreAdvertisedEndpoints = (
return endpoints; return endpoints;
}; };
export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErrorClass<DesktopServerExposureNoNetworkAddressError>()( type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
"DesktopServerExposureNoNetworkAddressError", "DesktopServerExposureNoNetworkAddressError",
{ )<{
port: Schema.Number, readonly port: number;
}, }> {
) { override get message() {
override get message(): string {
return `No reachable network address is available for desktop network access on port ${this.port}.`; return `No reachable network address is available for desktop network access on port ${this.port}.`;
} }
} }
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()( export class DesktopServerExposurePersistenceError extends Data.TaggedError(
"DesktopServerExposureModePersistenceError", "DesktopServerExposurePersistenceError",
{ )<{
mode: DesktopServerExposureModeSchema, readonly operation: DesktopServerExposurePersistenceOperation;
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError), readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
}, }> {
) { override get message() {
override get message(): string { return `Failed to persist desktop ${this.operation} settings.`;
return `Failed to persist desktop server exposure mode ${this.mode}.`;
} }
} }
export class DesktopTailscaleServePersistenceError extends Schema.TaggedErrorClass<DesktopTailscaleServePersistenceError>()( export type DesktopServerExposureSetModeError =
"DesktopTailscaleServePersistenceError", | DesktopServerExposureNoNetworkAddressError
{ | DesktopServerExposurePersistenceError;
enabled: Schema.Boolean,
port: Schema.NullOr(Schema.Number),
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop Tailscale Serve settings (enabled: ${this.enabled}, port: ${this.port ?? "unchanged"}).`;
}
}
export const DesktopServerExposureSetModeError = Schema.Union([ export type DesktopServerExposureError = DesktopServerExposureSetModeError;
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
]);
export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
export const isDesktopServerExposureSetModeError = Schema.is(DesktopServerExposureSetModeError);
export const DesktopServerExposureError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
DesktopTailscaleServePersistenceError,
]);
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
export const isDesktopServerExposureError = Schema.is(DesktopServerExposureError);
export interface DesktopServerExposureBackendConfig { export interface DesktopServerExposureBackendConfig {
readonly port: number; readonly port: number;
@@ -267,25 +260,36 @@ export interface DesktopServerExposureChange {
readonly requiresRelaunch: boolean; 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< export class DesktopServerExposure extends Context.Service<
DesktopServerExposure, DesktopServerExposure,
{ 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, DesktopTailscaleServePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
>()("@t3tools/desktop/backend/DesktopServerExposure") {} >()("@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 { interface RuntimeState {
readonly requestedMode: DesktopServerExposureMode; readonly requestedMode: DesktopServerExposureMode;
readonly mode: DesktopServerExposureMode; readonly mode: DesktopServerExposureMode;
@@ -307,10 +311,10 @@ interface ResolvedRuntimeState {
const initialRuntimeState = (): RuntimeState => const initialRuntimeState = (): RuntimeState =>
runtimeStateFromResolvedExposure({ runtimeStateFromResolvedExposure({
requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode, requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, settings: DEFAULT_DESKTOP_SETTINGS,
exposure: resolveDesktopServerExposure({ exposure: resolveDesktopServerExposure({
mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode, mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
port: 0, port: 0,
networkInterfaces: {}, networkInterfaces: {},
}), }),
@@ -344,7 +348,7 @@ const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure
function runtimeStateFromResolvedExposure(input: { function runtimeStateFromResolvedExposure(input: {
readonly requestedMode: DesktopServerExposureMode; readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopAppSettings.DesktopSettings; readonly settings: DesktopSettings;
readonly exposure: ResolvedDesktopServerExposure; readonly exposure: ResolvedDesktopServerExposure;
readonly port: number; readonly port: number;
}): RuntimeState { }): RuntimeState {
@@ -365,9 +369,9 @@ function runtimeStateFromResolvedExposure(input: {
function resolveRuntimeState(input: { function resolveRuntimeState(input: {
readonly requestedMode: DesktopServerExposureMode; readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopAppSettings.DesktopSettings; readonly settings: DesktopSettings;
readonly port: number; readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces; readonly networkInterfaces: DesktopNetworkInterfaces;
readonly advertisedHostOverride: Option.Option<string>; readonly advertisedHostOverride: Option.Option<string>;
}): ResolvedRuntimeState { }): ResolvedRuntimeState {
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride); const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
@@ -404,12 +408,12 @@ const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): bo
previous.bindHost !== next.bindHost || previous.bindHost !== next.bindHost ||
previous.localHttpUrl !== next.localHttpUrl; previous.localHttpUrl !== next.localHttpUrl;
export const make = Effect.gen(function* () { const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig; const config = yield* DesktopConfig.DesktopConfig;
const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces; const networkInterfaces = yield* DesktopNetworkInterfacesService;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient; const httpClient = yield* HttpClient.HttpClient;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
const stateRef = yield* Ref.make(initialRuntimeState()); const stateRef = yield* Ref.make(initialRuntimeState());
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App // Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
@@ -472,8 +476,8 @@ export const make = Effect.gen(function* () {
const change = yield* desktopSettings.setServerExposureMode(mode).pipe( const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
Effect.mapError( Effect.mapError(
(cause) => (cause) =>
new DesktopServerExposureModePersistenceError({ new DesktopServerExposurePersistenceError({
mode, operation: "server-exposure-mode",
cause, cause,
}), }),
), ),
@@ -500,9 +504,8 @@ export const make = Effect.gen(function* () {
.pipe( .pipe(
Effect.mapError( Effect.mapError(
(cause) => (cause) =>
new DesktopTailscaleServePersistenceError({ new DesktopServerExposurePersistenceError({
enabled: input.enabled, operation: "tailscale-serve",
port: input.port ?? null,
cause, cause,
}), }),
), ),
@@ -561,3 +564,10 @@ export const make = Effect.gen(function* () {
}); });
export const layer = Layer.effect(DesktopServerExposure, make); 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"; } from "@t3tools/tailscale";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as HttpClient from "effect/unstable/http/HttpClient"; import { HttpClient } from "effect/unstable/http";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; import { ChildProcessSpawner } from "effect/unstable/process";
import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts"; import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale"; export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
@@ -25,7 +25,7 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
function resolveTailscaleIpAdvertisedEndpoints(input: { function resolveTailscaleIpAdvertisedEndpoints(input: {
readonly port: number; readonly port: number;
readonly networkInterfaces: NetworkInterfaces; readonly networkInterfaces: DesktopNetworkInterfaces;
}): readonly AdvertisedEndpoint[] { }): readonly AdvertisedEndpoint[] {
const seen = new Set<string>(); const seen = new Set<string>();
const endpoints: AdvertisedEndpoint[] = []; const endpoints: AdvertisedEndpoint[] = [];
@@ -103,7 +103,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
readonly port: number; readonly port: number;
readonly serveEnabled?: boolean; readonly serveEnabled?: boolean;
readonly servePort?: number; readonly servePort?: number;
readonly networkInterfaces: NetworkInterfaces; readonly networkInterfaces: DesktopNetworkInterfaces;
readonly statusJson?: string | null; readonly statusJson?: string | null;
readonly readMagicDnsName?: Effect.Effect< readonly readMagicDnsName?: Effect.Effect<
string | null, string | null,
@@ -100,44 +100,6 @@ describe("ElectronApp", () => {
}).pipe(Effect.provide(ElectronApp.layer)), }).pipe(Effect.provide(ElectronApp.layer)),
); );
it.effect("reports which app metadata property failed", () =>
Effect.gen(function* () {
const cause = new Error("version unavailable");
getVersionMock.mockImplementationOnce(() => {
throw cause;
});
const electronApp = yield* ElectronApp.ElectronApp;
const error = yield* electronApp.metadata.pipe(Effect.flip);
assert.instanceOf(error, ElectronApp.ElectronAppMetadataReadError);
assert.strictEqual(error.property, "app-version");
assert.strictEqual(error.cause, cause);
assert.strictEqual(
error.message,
'Failed to read Electron app metadata property "app-version".',
);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("preserves Electron readiness failures", () =>
Effect.gen(function* () {
const cause = new Error("ready failed");
whenReadyMock.mockRejectedValueOnce(cause);
const electronApp = yield* ElectronApp.ElectronApp;
const error = yield* electronApp.whenReady.pipe(Effect.flip);
assert.instanceOf(error, ElectronApp.ElectronAppWhenReadyError);
assert.strictEqual(error.isPackaged, true);
assert.strictEqual(error.cause, cause);
assert.strictEqual(
error.message,
"Failed to wait for the Electron app to become ready (packaged: true).",
);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("scopes app event listeners", () => it.effect("scopes app event listeners", () =>
Effect.gen(function* () { Effect.gen(function* () {
const listener = vi.fn(); const listener = vi.fn();
+42 -91
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope"; import * as Scope from "effect/Scope";
import * as Electron from "electron"; import * as Electron from "electron";
@@ -14,64 +13,41 @@ export interface ElectronAppMetadata {
readonly runningUnderArm64Translation: boolean; readonly runningUnderArm64Translation: boolean;
} }
export class ElectronAppMetadataReadError extends Schema.TaggedErrorClass<ElectronAppMetadataReadError>()( export interface ElectronAppShape {
"ElectronAppMetadataReadError", readonly metadata: Effect.Effect<ElectronAppMetadata>;
{ readonly name: Effect.Effect<string>;
property: Schema.Literals(["app-version", "app-path"]), readonly whenReady: Effect.Effect<void>;
cause: Schema.Defect(), readonly quit: Effect.Effect<void>;
}, readonly exit: (code: number) => Effect.Effect<void>;
) { readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
override get message(): string { readonly setPath: (
return `Failed to read Electron app metadata property "${this.property}".`; 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 ElectronAppWhenReadyError extends Schema.TaggedErrorClass<ElectronAppWhenReadyError>()( export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
"ElectronAppWhenReadyError", "@t3tools/desktop/electron/ElectronApp",
{ ) {}
isPackaged: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to wait for the Electron app to become ready (packaged: ${this.isPackaged}).`;
}
}
export class ElectronApp extends Context.Service<
ElectronApp,
{
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
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") {}
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>( const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
eventName: string, eventName: string,
@@ -87,41 +63,16 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
}), }),
).pipe(Effect.asVoid); ).pipe(Effect.asVoid);
export const make = ElectronApp.of({ const make = ElectronApp.of({
metadata: Effect.gen(function* () { metadata: Effect.sync(() => ({
const appVersion = yield* Effect.try({ appVersion: Electron.app.getVersion(),
try: () => Electron.app.getVersion(), appPath: Electron.app.getAppPath(),
catch: (cause) => isPackaged: Electron.app.isPackaged,
new ElectronAppMetadataReadError({ resourcesPath: process.resourcesPath,
property: "app-version", runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
cause, })),
}),
});
const appPath = yield* Effect.try({
try: () => Electron.app.getAppPath(),
catch: (cause) =>
new ElectronAppMetadataReadError({
property: "app-path",
cause,
}),
});
return {
appVersion,
appPath,
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
};
}),
name: Effect.sync(() => Electron.app.name), name: Effect.sync(() => Electron.app.name),
whenReady: Effect.gen(function* () { whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
const isPackaged = Electron.app.isPackaged;
yield* Effect.tryPromise({
try: () => Electron.app.whenReady(),
catch: (cause) => new ElectronAppWhenReadyError({ isPackaged, cause }),
});
}),
quit: Effect.sync(() => { quit: Effect.sync(() => {
Electron.app.quit(); Electron.app.quit();
}), }),
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest"; import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import type { BrowserWindow } from "electron"; import type { BrowserWindow } from "electron";
@@ -91,116 +90,4 @@ describe("ElectronDialog", () => {
]); ]);
}).pipe(Effect.provide(ElectronDialog.layer)), }).pipe(Effect.provide(ElectronDialog.layer)),
); );
it.effect("preserves folder picker request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("folder picker failed");
const owner = { id: 7 } as BrowserWindow;
showOpenDialogMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.pickFolder({
owner: Option.some(owner),
defaultPath: Option.some("/workspace"),
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError);
assert.isTrue(ElectronDialog.isElectronDialogError(error));
assert.strictEqual(error.ownerWindowId, 7);
assert.strictEqual(error.defaultPath, "/workspace");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 7");
assert.include(error.message, "/workspace");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves confirmation request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("confirmation failed");
const owner = { id: 9 } as BrowserWindow;
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.confirm({
owner: Option.some(owner),
message: " Confirm removal? ",
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
assert.strictEqual(error.ownerWindowId, 9);
assert.strictEqual(error.promptLength, "Confirm removal?".length);
assert.notProperty(error, "promptMessage");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 9");
assert.notInclude(error.message, "Confirm removal?");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves message box request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("message box failed");
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.showMessageBox({
type: "warning",
title: "Unsaved changes",
message: "Discard changes?",
detail: "This cannot be undone.",
buttons: ["Cancel", "Discard"],
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogShowMessageBoxError);
assert.strictEqual(error.type, "warning");
assert.strictEqual(error.titleLength, "Unsaved changes".length);
assert.strictEqual(error.messageLength, "Discard changes?".length);
assert.strictEqual(error.detailLength, "This cannot be undone.".length);
assert.strictEqual(error.buttonCount, 2);
assert.notProperty(error, "title");
assert.notProperty(error, "dialogMessage");
assert.notProperty(error, "dialogDetail");
assert.notProperty(error, "buttons");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "warning");
assert.notInclude(error.message, "Unsaved changes");
assert.notInclude(error.message, "Discard changes?");
assert.notInclude(error.message, "This cannot be undone.");
assert.notInclude(error.message, "Cancel");
assert.notInclude(error.message, "Discard");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves error box request context and cause in the defect", () =>
Effect.gen(function* () {
const cause = new Error("error box failed");
showErrorBoxMock.mockImplementation(() => {
throw cause;
});
const dialog = yield* ElectronDialog.ElectronDialog;
const exit = yield* Effect.exit(dialog.showErrorBox("Startup failed", "Could not start."));
assert.isTrue(exit._tag === "Failure");
if (exit._tag === "Success") return;
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronDialog.ElectronDialogShowErrorBoxError);
assert.strictEqual(error.titleLength, "Startup failed".length);
assert.strictEqual(error.contentLength, "Could not start.".length);
assert.notProperty(error, "title");
assert.notProperty(error, "content");
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, "Startup failed");
assert.notInclude(error.message, "Could not start.");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
}); });
+26 -140
View File
@@ -2,80 +2,11 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Electron from "electron"; import * as Electron from "electron";
const CONFIRM_BUTTON_INDEX = 1; const CONFIRM_BUTTON_INDEX = 1;
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
"ElectronDialogPickFolderError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
defaultPath: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
return `Failed to open the Electron folder picker for ${owner} with ${defaultPath}.`;
}
}
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
promptLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
}
}
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
"ElectronDialogShowMessageBoxError",
{
type: Schema.NullOr(Schema.Literals(["none", "info", "error", "question", "warning"])),
titleLength: Schema.NullOr(Schema.Number),
messageLength: Schema.Number,
detailLength: Schema.NullOr(Schema.Number),
buttonCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const type = this.type === null ? "untyped" : this.type;
return `Failed to show the Electron ${type} message box with ${this.buttonCount} buttons.`;
}
}
export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<ElectronDialogShowErrorBoxError>()(
"ElectronDialogShowErrorBoxError",
{
titleLength: Schema.Number,
contentLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to show the Electron error box with a ${this.titleLength}-character title and ${this.contentLength}-character content.`;
}
}
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
ElectronDialogConfirmError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
]);
export type ElectronDialogError = typeof ElectronDialogError.Type;
export const isElectronDialogError = Schema.is(ElectronDialogError);
export interface ElectronDialogPickFolderInput { export interface ElectronDialogPickFolderInput {
readonly owner: Option.Option<Electron.BrowserWindow>; readonly owner: Option.Option<Electron.BrowserWindow>;
readonly defaultPath: Option.Option<string>; readonly defaultPath: Option.Option<string>;
@@ -86,29 +17,23 @@ export interface ElectronDialogConfirmInput {
readonly message: string; readonly message: string;
} }
export class ElectronDialog extends Context.Service< export interface ElectronDialogShape {
ElectronDialog, readonly pickFolder: (
{ input: ElectronDialogPickFolderInput,
readonly pickFolder: ( ) => Effect.Effect<Option.Option<string>>;
input: ElectronDialogPickFolderInput, readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>; readonly showMessageBox: (
readonly confirm: ( options: Electron.MessageBoxOptions,
input: ElectronDialogConfirmInput, ) => Effect.Effect<Electron.MessageBoxReturnValue>;
) => Effect.Effect<boolean, ElectronDialogConfirmError>; readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
readonly showMessageBox: ( }
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronDialog") {}
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) { pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const defaultPath = Option.getOrNull(input.defaultPath);
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, { const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
onNone: () => ({ onNone: () => ({
properties: ["openDirectory", "createDirectory"], properties: ["openDirectory", "createDirectory"],
@@ -118,18 +43,10 @@ export const make = ElectronDialog.of({
defaultPath, defaultPath,
}), }),
}); });
const result = yield* Effect.tryPromise({ const result = yield* Option.match(input.owner, {
try: () => onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
Option.match(input.owner, { onSome: (owner) =>
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions), Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
}),
catch: (cause) =>
new ElectronDialogPickFolderError({
ownerWindowId,
defaultPath,
cause,
}),
}); });
if (result.canceled) { if (result.canceled) {
@@ -151,48 +68,17 @@ export const make = ElectronDialog.of({
noLink: true, noLink: true,
message: normalizedMessage, message: normalizedMessage,
}; };
const ownerWindowId = Option.match(input.owner, { const result = yield* Option.match(input.owner, {
onNone: () => null, onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
onSome: (owner) => owner.id, onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
});
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showMessageBox(options),
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
}),
catch: (cause) =>
new ElectronDialogConfirmError({
ownerWindowId,
promptLength: normalizedMessage.length,
cause,
}),
}); });
return result.response === CONFIRM_BUTTON_INDEX; return result.response === CONFIRM_BUTTON_INDEX;
}), }),
showMessageBox: (options) => showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
Effect.tryPromise({
try: () => Electron.dialog.showMessageBox(options),
catch: (cause) =>
new ElectronDialogShowMessageBoxError({
type: options.type ?? null,
titleLength: options.title?.length ?? null,
messageLength: options.message.length,
detailLength: options.detail?.length ?? null,
buttonCount: options.buttons?.length ?? 0,
cause,
}),
}),
showErrorBox: (title, content) => showErrorBox: (title, content) =>
Effect.try({ Effect.sync(() => {
try: () => Electron.dialog.showErrorBox(title, content), Electron.dialog.showErrorBox(title, content);
catch: (cause) => }),
new ElectronDialogShowErrorBoxError({
titleLength: title.length,
contentLength: content.length,
cause,
}),
}).pipe(Effect.orDie),
}); });
export const layer = Layer.succeed(ElectronDialog, make); export const layer = Layer.succeed(ElectronDialog, make);
+4 -94
View File
@@ -1,8 +1,5 @@
import { assert, describe, it } from "@effect/vitest"; import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import type * as Electron from "electron"; import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test"; import { beforeEach, vi } from "vite-plus/test";
@@ -27,10 +24,6 @@ vi.mock("electron", () => ({
import * as ElectronMenu from "./ElectronMenu.ts"; import * as ElectronMenu from "./ElectronMenu.ts";
const TestLayer = ElectronMenu.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
describe("ElectronMenu", () => { describe("ElectronMenu", () => {
beforeEach(() => { beforeEach(() => {
buildFromTemplateMock.mockReset(); buildFromTemplateMock.mockReset();
@@ -49,7 +42,7 @@ describe("ElectronMenu", () => {
assert.isTrue(Option.isNone(selectedItemId)); assert.isTrue(Option.isNone(selectedItemId));
assert.equal(buildFromTemplateMock.mock.calls.length, 0); assert.equal(buildFromTemplateMock.mock.calls.length, 0);
}).pipe(Effect.provide(TestLayer)), }).pipe(Effect.provide(ElectronMenu.layer)),
); );
it.effect("resolves with the clicked leaf item id", () => it.effect("resolves with the clicked leaf item id", () =>
@@ -76,7 +69,7 @@ describe("ElectronMenu", () => {
}); });
assert.equal(Option.getOrNull(selectedItemId), "copy"); assert.equal(Option.getOrNull(selectedItemId), "copy");
}).pipe(Effect.provide(TestLayer)), }).pipe(Effect.provide(ElectronMenu.layer)),
); );
it.effect("resolves with none when the menu closes without a click", () => it.effect("resolves with none when the menu closes without a click", () =>
@@ -100,7 +93,7 @@ describe("ElectronMenu", () => {
enabled: true, enabled: true,
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click, click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
}); });
}).pipe(Effect.provide(TestLayer)), }).pipe(Effect.provide(ElectronMenu.layer)),
); );
it.effect("defers popupTemplate side effects until the returned Effect runs", () => it.effect("defers popupTemplate side effects until the returned Effect runs", () =>
@@ -121,89 +114,6 @@ describe("ElectronMenu", () => {
assert.equal(buildFromTemplateMock.mock.calls.length, 1); assert.equal(buildFromTemplateMock.mock.calls.length, 1);
assert.equal(popupMock.mock.calls.length, 1); assert.equal(popupMock.mock.calls.length, 1);
}).pipe(Effect.provide(TestLayer)), }).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("preserves application-menu failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("application menu build failed");
buildFromTemplateMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.setApplicationMenu([{ label: "File" }, { label: "Edit" }]),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "set-application-menu");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.equal(error.itemCount, 2);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves popup-template failures with window context", () =>
Effect.gen(function* () {
const cause = new Error("popup failed");
buildFromTemplateMock.mockReturnValueOnce({
popup: () => {
throw cause;
},
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.popupTemplate({
window: { id: 41 } as Electron.BrowserWindow,
template: [{ label: "Copy" }],
}),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "popup-template");
assert.equal(error.windowId, 41);
assert.equal(error.itemCount, 1);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves context-menu failures with normalized item context", () =>
Effect.gen(function* () {
const cause = new Error("context menu build failed");
buildFromTemplateMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.showContextMenu({
window: { id: 42 } as Electron.BrowserWindow,
items: [{ id: "copy", label: "Copy" }],
position: Option.none(),
}),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "show-context-menu");
assert.equal(error.windowId, 42);
assert.equal(error.itemCount, 1);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
); );
}); });
+37 -102
View File
@@ -1,10 +1,8 @@
import type { ContextMenuItem } from "@t3tools/contracts"; import type { ContextMenuItem } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Electron from "electron"; import * as Electron from "electron";
@@ -24,40 +22,19 @@ export interface ElectronMenuTemplateInput {
readonly template: readonly Electron.MenuItemConstructorOptions[]; readonly template: readonly Electron.MenuItemConstructorOptions[];
} }
const ElectronMenuOperation = Schema.Literals([ export interface ElectronMenuShape {
"set-application-menu", readonly setApplicationMenu: (
"popup-template", template: readonly Electron.MenuItemConstructorOptions[],
"show-context-menu", ) => Effect.Effect<void>;
]); readonly showContextMenu: (
input: ElectronMenuContextInput,
export class ElectronMenuOperationError extends Schema.TaggedErrorClass<ElectronMenuOperationError>()( ) => Effect.Effect<Option.Option<string>>;
"ElectronMenuOperationError", readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
{
operation: ElectronMenuOperation,
platform: Schema.String,
windowId: Schema.NullOr(Schema.Number),
itemCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
}
} }
export class ElectronMenu extends Context.Service< export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
ElectronMenu, "@t3tools/desktop/electron/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") {}
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] { function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = []; const normalizedItems: ContextMenuItem[] = [];
@@ -102,12 +79,11 @@ const normalizePosition = (
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0, ({ 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) }))); ).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
export const make = Effect.gen(function* () { export const layer = Layer.sync(ElectronMenu, () => {
const platform = yield* HostProcessPlatform;
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined; let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => { const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (platform !== "darwin") { if (process.platform !== "darwin") {
return Option.none(); return Option.none();
} }
if (destructiveMenuIconCache !== undefined) { if (destructiveMenuIconCache !== undefined) {
@@ -119,7 +95,6 @@ export const make = Effect.gen(function* () {
width: 12, width: 12,
height: 12, height: 12,
}); });
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon); destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch { } catch {
destructiveMenuIconCache = Option.none(); destructiveMenuIconCache = Option.none();
@@ -165,36 +140,16 @@ export const make = Effect.gen(function* () {
return ElectronMenu.of({ return ElectronMenu.of({
setApplicationMenu: (template) => setApplicationMenu: (template) =>
Effect.try({ Effect.sync(() => {
try: () => { Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template])); }),
},
catch: (cause) =>
new ElectronMenuOperationError({
operation: "set-application-menu",
platform,
windowId: null,
itemCount: template.length,
cause,
}),
}).pipe(Effect.orDie),
popupTemplate: (input) => popupTemplate: (input) =>
input.template.length === 0 Effect.sync(() => {
? Effect.void if (input.template.length === 0) {
: Effect.try({ return;
try: () => }
Electron.Menu.buildFromTemplate([...input.template]).popup({ Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
window: input.window, }),
}),
catch: (cause) =>
new ElectronMenuOperationError({
operation: "popup-template",
platform,
windowId: input.window.id,
itemCount: input.template.length,
cause,
}),
}).pipe(Effect.orDie),
showContextMenu: (input) => showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => { Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items); const normalizedItems = normalizeContextMenuItems(input.items);
@@ -212,41 +167,21 @@ export const make = Effect.gen(function* () {
resume(Effect.succeed(selectedItemId)); resume(Effect.succeed(selectedItemId));
}; };
try { const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete)); const popupPosition = normalizePosition(input.position);
const popupPosition = normalizePosition(input.position); const popupOptions = Option.match(popupPosition, {
const popupOptions = Option.match(popupPosition, { onNone: (): Electron.PopupOptions => ({
onNone: (): Electron.PopupOptions => ({ window: input.window,
window: input.window, callback: () => complete(Option.none()),
callback: () => complete(Option.none()), }),
}), onSome: (position): Electron.PopupOptions => ({
onSome: (position): Electron.PopupOptions => ({ window: input.window,
window: input.window, x: position.x,
x: position.x, y: position.y,
y: position.y, callback: () => complete(Option.none()),
callback: () => complete(Option.none()), }),
}), });
}); menu.popup(popupOptions);
menu.popup(popupOptions);
} catch (cause) {
if (completed) {
return;
}
completed = true;
resume(
Effect.die(
new ElectronMenuOperationError({
operation: "show-context-menu",
platform,
windowId: input.window.id,
itemCount: normalizedItems.length,
cause,
}),
),
);
}
}), }),
}); });
}); });
export const layer = Layer.effect(ElectronMenu, make);
@@ -1,229 +1,105 @@
import { assert, describe, it } from "@effect/vitest"; import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test"; import { beforeEach, vi } from "vite-plus/test";
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({ const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
handleMock: vi.fn(), vi.hoisted(() => ({
netFetchMock: vi.fn(), registerFileProtocolMock: vi.fn(),
unhandleMock: vi.fn(), registerSchemesAsPrivilegedMock: vi.fn(),
})); unregisterProtocolMock: vi.fn(),
}));
vi.mock("electron", () => ({ vi.mock("electron", () => ({
net: { fetch: netFetchMock }, protocol: {
protocol: { handle: handleMock, unhandle: unhandleMock }, registerFileProtocol: registerFileProtocolMock,
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
unregisterProtocol: unregisterProtocolMock,
},
})); }));
import * as ElectronProtocol from "./ElectronProtocol.ts"; import * as ElectronProtocol from "./ElectronProtocol.ts";
describe("ElectronProtocol", () => { describe("ElectronProtocol", () => {
beforeEach(() => { beforeEach(() => {
handleMock.mockReset(); registerFileProtocolMock.mockReset();
netFetchMock.mockReset(); registerSchemesAsPrivilegedMock.mockReset();
unhandleMock.mockReset(); unregisterProtocolMock.mockReset();
}); });
it.effect("proxies the stable renderer origin to the current app server", () => it("normalizes safe desktop protocol pathnames", () => {
Effect.gen(function* () { assert.equal(
let handler: ((request: Request) => Promise<Response>) | undefined; Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
handleMock.mockImplementation((_scheme, nextHandler) => { "settings/general",
handler = nextHandler; );
}); assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
netFetchMock.mockResolvedValue(new Response("ok")); });
yield* Effect.scoped( it.effect("registers desktop scheme privileges through a layer", () =>
Effect.gen(function* () { Effect.scoped(
const protocol = yield* ElectronProtocol.ElectronProtocol; Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
yield* protocol.registerDesktopProtocol({ Effect.andThen(
scheme: "t3code-dev", Effect.sync(() => {
targetOrigin: new URL("http://127.0.0.1:3773/"), assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
backendOrigin: new URL("http://127.0.0.1:3774/"), [
clerkFrontendApiHostname: "clerk.t3.codes", [
}); {
assert.isDefined(handler); scheme: "t3",
privileges: {
const response = yield* Effect.promise(() => standard: true,
handler!( secure: true,
new Request("t3code-dev://app/api/health?verbose=1", { supportFetchAPI: true,
headers: { corsEnabled: true,
accept: "application/json", },
origin: "t3code-dev://app", },
referer: "t3code-dev://app/", ],
"sec-fetch-site": "same-origin", ],
}, ]);
}),
),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"connect-src 'self' http: https: ws: wss:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"img-src 'self' t3code-dev: blob: data: http: https:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"font-src 'self' t3code-dev: data:",
);
}),
);
assert.deepEqual(
handleMock.mock.calls.map((call) => call[0]),
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
assert.equal(forwardedHeaders.get("accept"), "application/json");
assert.isNull(forwardedHeaders.get("origin"));
assert.isNull(forwardedHeaders.get("referer"));
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("rejects custom protocol requests for another host", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
}),
);
assert.equal(response.status, 404);
assert.equal(netFetchMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("retries transient renderer target failures", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
.mockResolvedValueOnce(new Response("ready"));
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:5733/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
}),
);
assert.equal(yield* Effect.promise(() => response.text()), "ready");
assert.equal(netFetchMock.mock.calls.length, 2);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
handleMock.mockImplementationOnce(() => {
throw cause;
});
const protocol = yield* ElectronProtocol.ElectronProtocol;
const error = yield* Effect.scoped(
protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: undefined,
}),
).pipe(Effect.flip);
assert.instanceOf(error, ElectronProtocol.ElectronProtocolRegistrationError);
assert.equal(error.scheme, "t3code-dev");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to register Electron protocol scheme "t3code-dev".');
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol unregistration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol unregistration failed");
unhandleMock.mockImplementationOnce(() => {
throw cause;
});
const protocol = yield* ElectronProtocol.ElectronProtocol;
const exit = yield* Effect.exit(
Effect.scoped(
protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
}), }),
), ),
); ),
),
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronProtocol.ElectronProtocolUnregistrationError);
assert.equal(error.scheme, "t3code");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to unregister Electron protocol scheme "t3code".');
}
}).pipe(Effect.provide(ElectronProtocol.layer)),
); );
it("keeps executable sources host-restricted while allowing runtime network resources", () => { it.effect("scopes registered file protocols", () =>
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({ Effect.gen(function* () {
scheme: "t3code", let capturedHandler:
targetOrigin: new URL("http://127.0.0.1:3773/"), | ((
backendOrigin: new URL("http://127.0.0.1:3773/"), request: Electron.ProtocolRequest,
clerkFrontendApiHostname: "clerk.t3.codes", callback: (response: Electron.ProtocolResponse) => void,
}); ) => void)
const directives = Object.fromEntries( | undefined;
policy.split("; ").map((directive) => {
const [name, ...sources] = directive.split(" ");
return [name, sources];
}),
);
assert.deepEqual(directives["script-src"], [ registerFileProtocolMock.mockImplementation((_scheme, handler) => {
"'self'", capturedHandler = handler;
"'unsafe-inline'", return true;
"https://clerk.t3.codes", });
"https://challenges.cloudflare.com",
]); const response = yield* Effect.scoped(
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]); Effect.gen(function* () {
assert.deepEqual(directives["img-src"], [ const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
"'self'", yield* electronProtocol.registerFileProtocol({
"t3code:", scheme: "t3",
"blob:", handler: () => Effect.succeed({ path: "/app/index.html" }),
"data:", });
"http:",
"https:", assert.isDefined(capturedHandler);
]); return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]); capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
}); resume(Effect.succeed(response)),
);
});
}),
);
assert.deepEqual(response, { path: "/app/index.html" });
assert.deepEqual(
registerFileProtocolMock.mock.calls.map((call) => call[0]),
["t3"],
);
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
}); });
+230 -164
View File
@@ -1,206 +1,272 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as NodeTimersPromises from "node:timers/promises"; import * as Option from "effect/Option";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope"; import * as Scope from "effect/Scope";
import * as Electron from "electron"; import * as Electron from "electron";
export const DESKTOP_HOST = "app"; import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
export function getDesktopScheme(isDevelopment: boolean): string { export const DESKTOP_SCHEME = "t3";
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
}
export function getDesktopOrigin(isDevelopment: boolean): string { export class ElectronProtocolRegistrationError extends Data.TaggedError(
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
}
export function getDesktopUrl(isDevelopment: boolean): string {
return `${getDesktopOrigin(isDevelopment)}/`;
}
export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<ElectronProtocolRegistrationError>()(
"ElectronProtocolRegistrationError", "ElectronProtocolRegistrationError",
{ )<{
scheme: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to register Electron protocol scheme "${this.scheme}".`;
}
}
export class ElectronProtocolUnregistrationError extends Schema.TaggedErrorClass<ElectronProtocolUnregistrationError>()(
"ElectronProtocolUnregistrationError",
{
scheme: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
}
}
export interface DesktopProtocolRegistrationInput {
readonly scheme: string; readonly scheme: string;
readonly targetOrigin: URL; readonly cause: unknown;
readonly backendOrigin: URL; }> {
readonly clerkFrontendApiHostname: string | undefined; override get message() {
return `Failed to register ${this.scheme}: file protocol.`;
}
} }
export class ElectronProtocol extends Context.Service< export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
ElectronProtocol, "ElectronProtocolStaticBundleMissingError",
{ )<{}> {
readonly registerDesktopProtocol: ( override get message() {
input: DesktopProtocolRegistrationInput, return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
} }
>()("@t3tools/desktop/electron/ElectronProtocol") {} }
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string { export interface ElectronProtocolShape {
const clerkOrigin = input.clerkFrontendApiHostname readonly registerFileProtocol: <E, R>(input: {
? `https://${input.clerkFrontendApiHostname}` readonly scheme: string;
: undefined; readonly handler: (
const scriptSources = [ request: Electron.ProtocolRequest,
"'self'", ) => Effect.Effect<Electron.ProtocolResponse, E, R>;
"'unsafe-inline'", readonly onFailure?: (
...(clerkOrigin ? [clerkOrigin] : []), request: Electron.ProtocolRequest,
"https://challenges.cloudflare.com", cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
readonly registerDesktopFileProtocol: Effect.Effect<
void,
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
>;
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"@t3tools/desktop/electron/ElectronProtocol",
) {}
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
const segments: string[] = [];
for (const segment of rawPath.split("/")) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
return Option.none();
}
segments.push(segment);
}
return Option.some(segments.join("/"));
}
const registerDesktopSchemePrivileges = Effect.sync(() => {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
const resolveDesktopStaticDir: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidates = [
environment.path.join(environment.appRoot, "apps/server/dist/client"),
environment.path.join(environment.appRoot, "apps/web/dist"),
]; ];
for (const candidate of candidates) {
// The renderer connects directly to user-configured environments in addition to const hasIndex = yield* fileSystem
// the build-configured Clerk, relay, and OTLP endpoints. Those environment .exists(environment.path.join(candidate, "index.html"))
// origins are not known when this response policy is created, so restrict .pipe(Effect.orElseSucceed(() => false));
// connections by the network schemes the client supports instead of by host. if (hasIndex) {
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"]; return Option.some(candidate);
return [
"default-src 'self'",
`script-src ${scriptSources.join(" ")}`,
`connect-src ${connectSources.join(" ")}`,
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
"style-src 'self' 'unsafe-inline'",
`font-src 'self' ${input.scheme}: data:`,
"worker-src 'self' blob:",
"frame-src 'self' https://challenges.cloudflare.com",
"form-action 'self'",
].join("; ");
}
function withContentSecurityPolicy(response: Response, policy: string): Response {
const headers = new Headers(response.headers);
headers.set("Content-Security-Policy", policy);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
async function proxyRequest(
request: Request,
targetOrigin: URL,
contentSecurityPolicy: string,
): Promise<Response> {
const requestUrl = new URL(request.url);
if (requestUrl.host !== DESKTOP_HOST) {
return new Response(null, { status: 404 });
}
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const headers = new Headers(request.headers);
const headersToRemove: string[] = [];
for (const name of headers.keys()) {
if (
name === "host" ||
name === "origin" ||
name === "referer" ||
name === "connection" ||
name === "content-length" ||
name === "accept-encoding" ||
name === "upgrade-insecure-requests" ||
name.startsWith("sec-fetch-")
) {
headersToRemove.push(name);
} }
} }
for (const name of headersToRemove) { return Option.none<string>();
headers.delete(name); });
}
const init: RequestInit = {
method: request.method,
headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
const response =
request.method === "GET" || request.method === "HEAD"
? await fetchWithTransientRetry(targetUrl.toString(), init)
: await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const; const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
function* (
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> { staticRoot: string,
let lastError: unknown; requestUrl: string,
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) { const fileSystem = yield* FileSystem.FileSystem;
if (delayMs > 0) { const environment = yield* DesktopEnvironment;
await NodeTimersPromises.setTimeout(delayMs); const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
if (Option.isNone(normalizedPath)) {
return environment.path.join(staticRoot, "index.html");
} }
try { const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
return await Electron.net.fetch(url, init); const resolvedPath = environment.path.join(staticRoot, requestedPath);
} catch (error) {
lastError = error;
}
}
throw lastError; if (environment.path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = environment.path.join(resolvedPath, "index.html");
const nestedIndexExists = yield* fileSystem
.exists(nestedIndex)
.pipe(Effect.orElseSucceed(() => false));
if (nestedIndexExists) {
return nestedIndex;
}
return environment.path.join(staticRoot, "index.html");
},
);
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
try {
const url = new URL(requestUrl);
return environment.path.extname(url.pathname).length > 0;
} catch {
return false;
}
} }
export const make = Effect.gen(function* () { const make = Effect.gen(function* () {
const registered = yield* Ref.make(false); const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")( const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
function* (input: DesktopProtocolRegistrationInput) { function* <E, R>({
if (yield* Ref.get(registered)) return; scheme,
handler,
onFailure,
}: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
yield* Effect.annotateCurrentSpan({ scheme });
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
Effect.map((protocols) => protocols.has(scheme)),
);
if (alreadyRegistered) {
return;
}
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input); const context = yield* Effect.context<R>();
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease( yield* Effect.acquireRelease(
Effect.try({ Effect.try({
try: () => { try: () => {
Electron.protocol.handle(input.scheme, (request) => const registered = Electron.protocol.registerFileProtocol(
proxyRequest(request, input.targetOrigin, contentSecurityPolicy), scheme,
(request, callback) => {
const response = handler(request).pipe(
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
Effect.catchCause((cause) =>
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
),
);
void runPromise(response).then(callback, () => callback({ error: -2 }));
},
); );
if (!registered) {
throw new ElectronProtocolRegistrationError({
scheme,
cause: "registerFileProtocol returned false",
});
}
}, },
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }), catch: (cause) =>
}).pipe(Effect.andThen(Ref.set(registered, true))), cause instanceof ElectronProtocolRegistrationError
? cause
: new ElectronProtocolRegistrationError({ scheme, cause }),
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
),
),
() => () =>
Effect.try({ Effect.sync(() => {
try: () => Electron.protocol.unhandle(input.scheme), Electron.protocol.unregisterProtocol(scheme);
catch: (cause) => }).pipe(
new ElectronProtocolUnregistrationError({ Effect.andThen(
scheme: input.scheme, Ref.update(registeredProtocols, (protocols) => {
cause, const next = new Set(protocols);
next.delete(scheme);
return next;
}), }),
}).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie), ),
),
); );
}, },
); );
return ElectronProtocol.of({ registerDesktopProtocol }); const registerDesktopFileProtocol = Effect.gen(function* () {
const environment = yield* DesktopEnvironment;
if (environment.isDevelopment) return;
const staticRoot = yield* resolveDesktopStaticDir;
if (Option.isNone(staticRoot)) {
return yield* new ElectronProtocolStaticBundleMissingError();
}
const staticRootResolved = environment.path.resolve(staticRoot.value);
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
yield* registerFileProtocol({
scheme: DESKTOP_SCHEME,
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = environment.path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url, environment);
const exists = yield* fileSystem
.exists(resolvedCandidate)
.pipe(Effect.orElseSucceed(() => false));
if (!isInRoot || !exists) {
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
}
return { path: resolvedCandidate } as const;
}),
onFailure: () => ({ path: fallbackIndex }),
});
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
return ElectronProtocol.of({
registerFileProtocol,
registerDesktopFileProtocol,
});
}); });
export const layer = Layer.effect(ElectronProtocol, make); export const layer = Layer.effect(ElectronProtocol, make);
@@ -1,69 +1,56 @@
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Electron from "electron"; import * as Electron from "electron";
const electronSafeStorageErrorFields = { export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
cause: Schema.Defect(),
};
export class ElectronSafeStorageAvailabilityError extends Schema.TaggedErrorClass<ElectronSafeStorageAvailabilityError>()(
"ElectronSafeStorageAvailabilityError", "ElectronSafeStorageAvailabilityError",
{ )<{
...electronSafeStorageErrorFields, readonly cause: unknown;
}, }> {
) { override get message() {
override get message(): string {
return "Electron safe storage failed to check encryption availability."; return "Electron safe storage failed to check encryption availability.";
} }
} }
export class ElectronSafeStorageEncryptError extends Schema.TaggedErrorClass<ElectronSafeStorageEncryptError>()( export class ElectronSafeStorageEncryptError extends Data.TaggedError(
"ElectronSafeStorageEncryptError", "ElectronSafeStorageEncryptError",
{ )<{
...electronSafeStorageErrorFields, readonly cause: unknown;
}, }> {
) { override get message() {
override get message(): string {
return "Electron safe storage failed to encrypt a string."; return "Electron safe storage failed to encrypt a string.";
} }
} }
export class ElectronSafeStorageDecryptError extends Schema.TaggedErrorClass<ElectronSafeStorageDecryptError>()( export class ElectronSafeStorageDecryptError extends Data.TaggedError(
"ElectronSafeStorageDecryptError", "ElectronSafeStorageDecryptError",
{ )<{
...electronSafeStorageErrorFields, readonly cause: unknown;
}, }> {
) { override get message() {
override get message(): string {
return "Electron safe storage failed to decrypt a string."; return "Electron safe storage failed to decrypt a string.";
} }
} }
export const ElectronSafeStorageError = Schema.Union([ export interface ElectronSafeStorageShape {
ElectronSafeStorageAvailabilityError, readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
ElectronSafeStorageEncryptError, readonly encryptString: (
ElectronSafeStorageDecryptError, value: string,
]); ) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
export type ElectronSafeStorageError = typeof ElectronSafeStorageError.Type; readonly decryptString: (
export const isElectronSafeStorageError = Schema.is(ElectronSafeStorageError); value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
export class ElectronSafeStorage extends Context.Service< export class ElectronSafeStorage extends Context.Service<
ElectronSafeStorage, ElectronSafeStorage,
{ ElectronSafeStorageShape
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
>()("@t3tools/desktop/electron/ElectronSafeStorage") {} >()("@t3tools/desktop/electron/ElectronSafeStorage") {}
export const make = ElectronSafeStorage.of({ const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({ isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(), try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }), catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
+9 -8
View File
@@ -20,15 +20,16 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
} }
} }
export class ElectronShell extends Context.Service< export interface ElectronShellShape {
ElectronShell, readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
{ readonly copyText: (text: string) => Effect.Effect<void>;
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>; }
readonly copyText: (text: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronShell") {}
export const make = ElectronShell.of({ export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
"@t3tools/desktop/electron/ElectronShell",
) {}
const make = ElectronShell.of({
openExternal: (rawUrl) => openExternal: (rawUrl) =>
Option.match(parseSafeExternalUrl(rawUrl), { Option.match(parseSafeExternalUrl(rawUrl), {
onNone: () => Effect.succeed(false), onNone: () => Effect.succeed(false),
@@ -8,7 +8,6 @@ const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
themeState: { themeState: {
shouldUseDarkColors: true, shouldUseDarkColors: true,
themeSource: "system", themeSource: "system",
setSourceError: null as unknown,
}, },
})); }));
@@ -18,9 +17,6 @@ vi.mock("electron", () => ({
return themeState.shouldUseDarkColors; return themeState.shouldUseDarkColors;
}, },
set themeSource(value: string) { set themeSource(value: string) {
if (themeState.setSourceError !== null) {
throw themeState.setSourceError;
}
themeState.themeSource = value; themeState.themeSource = value;
}, },
on: onMock, on: onMock,
@@ -36,7 +32,6 @@ describe("ElectronTheme", () => {
removeListenerMock.mockClear(); removeListenerMock.mockClear();
themeState.shouldUseDarkColors = true; themeState.shouldUseDarkColors = true;
themeState.themeSource = "system"; themeState.themeSource = "system";
themeState.setSourceError = null;
}); });
it.effect("scopes native theme update listeners", () => it.effect("scopes native theme update listeners", () =>
@@ -54,21 +49,4 @@ describe("ElectronTheme", () => {
assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]); assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]);
}).pipe(Effect.provide(ElectronTheme.layer)), }).pipe(Effect.provide(ElectronTheme.layer)),
); );
it.effect("preserves the requested source and cause when setting the theme fails", () =>
Effect.gen(function* () {
const cause = new Error("theme source failed");
themeState.setSourceError = cause;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const error = yield* Effect.flip(electronTheme.setSource("dark"));
assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError);
assert.isTrue(ElectronTheme.isElectronThemeSetSourceError(error));
assert.strictEqual(error.source, "dark");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "dark");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronTheme.layer)),
);
}); });
+12 -28
View File
@@ -1,43 +1,27 @@
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts"; import type { DesktopTheme } from "@t3tools/contracts";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope"; import * as Scope from "effect/Scope";
import * as Electron from "electron"; import * as Electron from "electron";
export class ElectronThemeSetSourceError extends Schema.TaggedErrorClass<ElectronThemeSetSourceError>()( export interface ElectronThemeShape {
"ElectronThemeSetSourceError", readonly shouldUseDarkColors: Effect.Effect<boolean>;
{ readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
source: DesktopThemeSchema, readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to set the Electron theme source to ${this.source}.`;
}
} }
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError); export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
"@t3tools/desktop/electron/ElectronTheme",
) {}
export class ElectronTheme extends Context.Service< const make = ElectronTheme.of({
ElectronTheme,
{
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronTheme") {}
export const make = ElectronTheme.of({
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors), shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
setSource: (theme) => setSource: (theme) =>
Effect.try({ Effect.suspend(() => {
try: () => { Electron.nativeTheme.themeSource = theme;
Electron.nativeTheme.themeSource = theme; return Effect.void;
},
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
}), }),
onUpdated: (listener) => onUpdated: (listener) =>
Effect.acquireRelease( Effect.acquireRelease(
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest"; import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test"; import { beforeEach, vi } from "vite-plus/test";
@@ -64,65 +65,15 @@ describe("ElectronUpdater", () => {
const cause = new Error("network unavailable"); const cause = new Error("network unavailable");
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause)); autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater; const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "beta";
const error = yield* updater.checkForUpdates.pipe(Effect.flip); const exit = yield* Effect.exit(updater.checkForUpdates);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError); assert.equal(exit._tag, "Failure");
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error)); if (exit._tag === "Failure") {
assert.equal(error.channel, "beta"); const error = Cause.squash(exit.cause);
assert.strictEqual(error.cause, cause); assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.equal(error.message, "Electron updater failed to check for updates on channel beta."); assert.equal(error.cause, cause);
assert.notInclude(error.message, cause.message); }
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves the execution-time channel on download failures", () =>
Effect.gen(function* () {
const cause = new Error("download unavailable");
autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "nightly";
const error = yield* updater.downloadUpdate.pipe(Effect.flip);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "nightly");
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Electron updater failed to download the update on channel nightly.",
);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
Effect.gen(function* () {
const cause = new Error("quit and install failed");
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
throw cause;
});
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "alpha";
const error = yield* updater
.quitAndInstall({ isSilent: true, isForceRunAfter: false })
.pipe(Effect.flip);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "alpha");
assert.equal(error.isSilent, true);
assert.equal(error.isForceRunAfter, false);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Electron updater failed to quit and install the update on channel alpha (silent: true, force run after: false).",
);
assert.notInclude(error.message, cause.message);
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
}).pipe(Effect.provide(ElectronUpdater.layer)), }).pipe(Effect.provide(ElectronUpdater.layer)),
); );
}); });
+60 -87
View File
@@ -1,7 +1,7 @@
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope"; import * as Scope from "effect/Scope";
import { autoUpdater } from "electron-updater"; import { autoUpdater } from "electron-updater";
@@ -10,77 +10,67 @@ type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0]; export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()( export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
"ElectronUpdaterCheckForUpdatesError", "ElectronUpdaterCheckForUpdatesError",
{ )<{
channel: Schema.NullOr(Schema.String), readonly cause: unknown;
cause: Schema.Defect(), }> {
}, override get message() {
) { return "Electron updater failed to check for updates.";
override get message(): string {
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
} }
} }
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()( export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
"ElectronUpdaterDownloadUpdateError", "ElectronUpdaterDownloadUpdateError",
{ )<{
channel: Schema.NullOr(Schema.String), readonly cause: unknown;
cause: Schema.Defect(), }> {
}, override get message() {
) { return "Electron updater failed to download the update.";
override get message(): string {
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
} }
} }
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()( export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
"ElectronUpdaterQuitAndInstallError", "ElectronUpdaterQuitAndInstallError",
{ )<{
channel: Schema.NullOr(Schema.String), readonly cause: unknown;
isSilent: Schema.Boolean, }> {
isForceRunAfter: Schema.Boolean, override get message() {
cause: Schema.Defect(), return "Electron updater failed to quit and install the update.";
},
) {
override get message(): string {
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
} }
} }
export const ElectronUpdaterError = Schema.Union([ export type ElectronUpdaterError =
ElectronUpdaterCheckForUpdatesError, | ElectronUpdaterCheckForUpdatesError
ElectronUpdaterDownloadUpdateError, | ElectronUpdaterDownloadUpdateError
ElectronUpdaterQuitAndInstallError, | ElectronUpdaterQuitAndInstallError;
]);
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
export class ElectronUpdater extends Context.Service< export interface ElectronUpdaterShape {
ElectronUpdater, readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
{ readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>; readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>; readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>; readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>; readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>; readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>; readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>; readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>; readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>; readonly quitAndInstall: (options: {
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>; readonly isSilent: boolean;
readonly quitAndInstall: (options: { readonly isForceRunAfter: boolean;
readonly isSilent: boolean; }) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly isForceRunAfter: boolean; readonly on: <Args extends ReadonlyArray<unknown>>(
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>; eventName: string,
readonly on: <Args extends ReadonlyArray<unknown>>( listener: (...args: Args) => void,
eventName: string, ) => Effect.Effect<void, never, Scope.Scope>;
listener: (...args: Args) => void, }
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronUpdater") {}
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) => setFeedURL: (options) =>
Effect.suspend(() => { Effect.suspend(() => {
autoUpdater.setFeedURL(options); autoUpdater.setFeedURL(options);
@@ -117,33 +107,18 @@ export const make = ElectronUpdater.of({
autoUpdater.disableDifferentialDownload = value; autoUpdater.disableDifferentialDownload = value;
return Effect.void; return Effect.void;
}), }),
checkForUpdates: Effect.suspend(() => { checkForUpdates: Effect.tryPromise({
const channel = autoUpdater.channel; try: () => autoUpdater.checkForUpdates(),
return Effect.tryPromise({ catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ cause }),
try: () => autoUpdater.checkForUpdates(), }).pipe(Effect.asVoid),
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ channel, cause }), downloadUpdate: Effect.tryPromise({
}).pipe(Effect.asVoid); try: () => autoUpdater.downloadUpdate(),
}), catch: (cause) => new ElectronUpdaterDownloadUpdateError({ cause }),
downloadUpdate: Effect.suspend(() => { }).pipe(Effect.asVoid),
const channel = autoUpdater.channel;
return Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
}).pipe(Effect.asVoid);
}),
quitAndInstall: ({ isSilent, isForceRunAfter }) => quitAndInstall: ({ isSilent, isForceRunAfter }) =>
Effect.suspend(() => { Effect.try({
const channel = autoUpdater.channel; try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
return Effect.try({ catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) =>
new ElectronUpdaterQuitAndInstallError({
channel,
isSilent,
isForceRunAfter,
cause,
}),
});
}), }),
on: (eventName, listener) => { on: (eventName, listener) => {
const eventTarget = autoUpdater as unknown as { const eventTarget = autoUpdater as unknown as {
@@ -161,6 +136,4 @@ export const make = ElectronUpdater.of({
}), }),
).pipe(Effect.asVoid); ).pipe(Effect.asVoid);
}, },
}); } satisfies ElectronUpdaterShape);
export const layer = Layer.succeed(ElectronUpdater, make);
+10 -194
View File
@@ -1,39 +1,26 @@
import { assert, describe, it } from "@effect/vitest"; import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type * as Electron from "electron"; import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test"; import { beforeEach, vi } from "vite-plus/test";
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted( const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
() => ({ appFocusMock: vi.fn(),
appFocusMock: vi.fn(), getAllWindowsMock: vi.fn(),
browserWindowMock: vi.fn(function BrowserWindowMock() {}), }));
getAllWindowsMock: vi.fn(),
getFocusedWindowMock: vi.fn(),
}),
);
vi.mock("electron", () => ({ vi.mock("electron", () => ({
app: { app: {
focus: appFocusMock, focus: appFocusMock,
}, },
BrowserWindow: Object.assign(browserWindowMock, { BrowserWindow: {
getAllWindows: getAllWindowsMock, getAllWindows: getAllWindowsMock,
getFocusedWindow: getFocusedWindowMock, },
}),
})); }));
import * as ElectronWindow from "./ElectronWindow.ts"; import * as ElectronWindow from "./ElectronWindow.ts";
const TestLayer = ElectronWindow.layer.pipe( function makeBrowserWindow(input: { readonly destroyed: boolean }) {
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
return { return {
id: input.id,
isDestroyed: vi.fn(() => input.destroyed), isDestroyed: vi.fn(() => input.destroyed),
} as unknown as Electron.BrowserWindow; } as unknown as Electron.BrowserWindow;
} }
@@ -41,78 +28,13 @@ function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boo
describe("ElectronWindow", () => { describe("ElectronWindow", () => {
beforeEach(() => { beforeEach(() => {
appFocusMock.mockReset(); appFocusMock.mockReset();
browserWindowMock.mockReset();
getAllWindowsMock.mockReset(); getAllWindowsMock.mockReset();
getFocusedWindowMock.mockReset();
}); });
it.effect("preserves schema-safe creation context and the Electron cause", () =>
Effect.gen(function* () {
const cause = new Error("native BrowserWindow construction failed");
browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() {
throw cause;
});
const options = {
title: "T3 Code",
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
modal: false,
frame: true,
transparent: false,
backgroundColor: "#101010",
icon: {} as Electron.NativeImage,
webPreferences: {
preload: "/tmp/preload.js",
partition: "persist:t3code-preview-test",
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
spellcheck: true,
},
} satisfies Electron.BrowserWindowConstructorOptions;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const error = yield* electronWindow.create(options).pipe(Effect.flip);
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
assert.deepEqual(error.options, {
title: "T3 Code",
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
modal: false,
frame: true,
transparent: false,
backgroundColor: "#101010",
webPreferences: {
preload: "/tmp/preload.js",
partition: "persist:t3code-preview-test",
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
},
});
assert.isFalse("icon" in error.options);
assert.isFalse("spellcheck" in error.options.webPreferences);
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).');
assert.notInclude(error.message, cause.message);
assert.deepEqual(browserWindowMock.mock.calls, [[options]]);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("skips windows destroyed before appearance sync runs", () => it.effect("skips windows destroyed before appearance sync runs", () =>
Effect.gen(function* () { Effect.gen(function* () {
const liveWindow = makeBrowserWindow({ id: 1, destroyed: false }); const liveWindow = makeBrowserWindow({ destroyed: false });
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true }); const destroyedWindow = makeBrowserWindow({ destroyed: true });
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]); getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
const syncedWindows: Electron.BrowserWindow[] = []; const syncedWindows: Electron.BrowserWindow[] = [];
@@ -124,112 +46,6 @@ describe("ElectronWindow", () => {
); );
assert.deepEqual(syncedWindows, [liveWindow]); assert.deepEqual(syncedWindows, [liveWindow]);
}).pipe(Effect.provide(TestLayer)), }).pipe(Effect.provide(ElectronWindow.layer)),
);
it.effect("preserves window enumeration failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("window enumeration failed");
getAllWindowsMock.mockImplementationOnce(() => {
throw cause;
});
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.currentMainOrFirst);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "list-windows");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves reveal failures with the target window", () =>
Effect.gen(function* () {
const cause = new Error("window restore failed");
const window = {
id: 41,
isDestroyed: vi.fn(() => false),
isMinimized: vi.fn(() => true),
restore: vi.fn(() => {
throw cause;
}),
} as unknown as Electron.BrowserWindow;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.reveal(window));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "reveal-window");
assert.equal(error.windowId, 41);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves message delivery failures with window and channel context", () =>
Effect.gen(function* () {
const cause = new Error("renderer send failed");
const window = {
id: 42,
isDestroyed: vi.fn(() => false),
webContents: {
send: vi.fn(() => {
throw cause;
}),
},
} as unknown as Electron.BrowserWindow;
getAllWindowsMock.mockReturnValueOnce([window]);
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true }));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "send-window-message");
assert.equal(error.windowId, 42);
assert.equal(error.channel, "desktop:update");
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves destroy failures with the target window", () =>
Effect.gen(function* () {
const cause = new Error("window destroy failed");
const window = {
id: 43,
destroy: vi.fn(() => {
throw cause;
}),
} as unknown as Electron.BrowserWindow;
getAllWindowsMock.mockReturnValueOnce([window]);
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.destroyAll);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "destroy-window");
assert.equal(error.windowId, 43);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
); );
}); });
+68 -219
View File
@@ -1,135 +1,47 @@
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Electron from "electron"; import * as Electron from "electron";
const ElectronWindowCreateOptions = Schema.Struct({ export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
title: Schema.NullOr(Schema.String), readonly cause: unknown;
width: Schema.NullOr(Schema.Number), }> {
height: Schema.NullOr(Schema.Number), override get message() {
minWidth: Schema.NullOr(Schema.Number), return "Failed to create Electron BrowserWindow.";
minHeight: Schema.NullOr(Schema.Number),
show: Schema.NullOr(Schema.Boolean),
modal: Schema.NullOr(Schema.Boolean),
frame: Schema.NullOr(Schema.Boolean),
transparent: Schema.NullOr(Schema.Boolean),
backgroundColor: Schema.NullOr(Schema.String),
webPreferences: Schema.Struct({
preload: Schema.NullOr(Schema.String),
partition: Schema.NullOr(Schema.String),
sandbox: Schema.NullOr(Schema.Boolean),
contextIsolation: Schema.NullOr(Schema.Boolean),
nodeIntegration: Schema.NullOr(Schema.Boolean),
webviewTag: Schema.NullOr(Schema.Boolean),
}),
});
const ElectronWindowOperation = Schema.Literals([
"list-windows",
"get-focused-window",
"inspect-window",
"reveal-window",
"send-window-message",
"destroy-window",
]);
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
"ElectronWindowCreateError",
{
options: ElectronWindowCreateOptions,
cause: Schema.Defect(),
},
) {
override get message(): string {
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
const dimensions =
this.options.width === null || this.options.height === null
? ""
: ` (${this.options.width}x${this.options.height})`;
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
} }
} }
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError); export interface ElectronWindowShape {
readonly create: (
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()( options: Electron.BrowserWindowConstructorOptions,
"ElectronWindowOperationError", ) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
{ readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
operation: ElectronWindowOperation, readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
platform: Schema.String, readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
windowId: Schema.NullOr(Schema.Number), readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
channel: Schema.NullOr(Schema.String), readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
cause: Schema.Defect(), readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
}, readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
) { readonly destroyAll: Effect.Effect<void>;
override get message(): string { readonly syncAllAppearance: <E, R>(
const window = this.windowId === null ? "" : ` for window ${this.windowId}`; sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`; ) => Effect.Effect<void, E, R>;
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
}
} }
export class ElectronWindow extends Context.Service< export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
ElectronWindow, "@t3tools/desktop/electron/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 const make = Effect.gen(function* () { const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none()); const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const listWindows = Effect.try({ const liveMain = Ref.get(mainWindowRef).pipe(
try: () => Electron.BrowserWindow.getAllWindows(), Effect.map(Option.filter((value) => !value.isDestroyed())),
catch: (cause) => );
new ElectronWindowOperationError({
operation: "list-windows",
platform,
windowId: null,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
Effect.try({
try: () => window.isDestroyed(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "inspect-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
const liveMain = Effect.gen(function* () {
const main = yield* Ref.get(mainWindowRef);
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
return Option.none<Electron.BrowserWindow>();
}
return main;
});
const currentMainOrFirst = Effect.gen(function* () { const currentMainOrFirst = Effect.gen(function* () {
const main = yield* liveMain; const main = yield* liveMain;
@@ -137,60 +49,27 @@ export const make = Effect.gen(function* () {
return main; return main;
} }
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null); return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) { Option.filter((window) => !window.isDestroyed()),
return Option.none<Electron.BrowserWindow>(); );
}
return first;
}); });
const focusedMainOrFirst = Effect.gen(function* () { const focusedMainOrFirst = Effect.sync(() =>
const focused = yield* Effect.try({ Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null), Option.filter((window) => !window.isDestroyed()),
catch: (cause) => ),
new ElectronWindowOperationError({ ).pipe(
operation: "get-focused-window", Effect.flatMap((focused) =>
platform, Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
windowId: null, ),
channel: null, );
cause,
}),
}).pipe(Effect.orDie);
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
return focused;
}
return yield* currentMainOrFirst;
});
return ElectronWindow.of({ return ElectronWindow.of({
create: (options) => { create: (options) =>
const webPreferences = options.webPreferences; Effect.try({
const diagnosticOptions = {
title: options.title ?? null,
width: options.width ?? null,
height: options.height ?? null,
minWidth: options.minWidth ?? null,
minHeight: options.minHeight ?? null,
show: options.show ?? null,
modal: options.modal ?? null,
frame: options.frame ?? null,
transparent: options.transparent ?? null,
backgroundColor: options.backgroundColor ?? null,
webPreferences: {
preload: webPreferences?.preload ?? null,
partition: webPreferences?.partition ?? null,
sandbox: webPreferences?.sandbox ?? null,
contextIsolation: webPreferences?.contextIsolation ?? null,
nodeIntegration: webPreferences?.nodeIntegration ?? null,
webviewTag: webPreferences?.webviewTag ?? null,
},
} satisfies typeof ElectronWindowCreateOptions.Type;
return Effect.try({
try: () => new Electron.BrowserWindow(options), try: () => new Electron.BrowserWindow(options),
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }), catch: (cause) => new ElectronWindowCreateError({ cause }),
}); }),
},
main: liveMain, main: liveMain,
currentMainOrFirst, currentMainOrFirst,
focusedMainOrFirst, focusedMainOrFirst,
@@ -206,75 +85,45 @@ export const make = Effect.gen(function* () {
return Option.none(); return Option.none();
}), }),
reveal: (window) => reveal: (window) =>
Effect.try({ Effect.sync(() => {
try: () => { if (window.isDestroyed()) {
if (window.isDestroyed()) { return;
return; }
}
if (window.isMinimized()) { if (window.isMinimized()) {
window.restore(); window.restore();
} }
if (!window.isVisible()) { if (!window.isVisible()) {
window.show(); window.show();
} }
if (platform === "darwin") { if (process.platform === "darwin") {
Electron.app.focus({ steal: true }); Electron.app.focus({ steal: true });
} }
window.focus(); window.focus();
}, }),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "reveal-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie),
sendAll: (channel, ...args) => sendAll: (channel, ...args) =>
Effect.gen(function* () { Effect.sync(() => {
for (const window of yield* listWindows) { for (const window of Electron.BrowserWindow.getAllWindows()) {
if (yield* isWindowDestroyed(window)) { if (window.isDestroyed()) {
continue; continue;
} }
yield* Effect.try({ window.webContents.send(channel, ...args);
try: () => window.webContents.send(channel, ...args),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "send-window-message",
platform,
windowId: window.id,
channel,
cause,
}),
}).pipe(Effect.orDie);
} }
}), }),
destroyAll: Effect.gen(function* () { destroyAll: Effect.sync(() => {
for (const window of yield* listWindows) { for (const window of Electron.BrowserWindow.getAllWindows()) {
yield* Effect.try({ window.destroy();
try: () => window.destroy(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "destroy-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
} }
}), }),
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>( syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>, sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) { ) {
const windows = yield* listWindows; const windows = Electron.BrowserWindow.getAllWindows();
for (const window of windows) { for (const window of windows) {
if (yield* isWindowDestroyed(window)) { if (window.isDestroyed()) {
continue; continue;
} }
yield* sync(window); yield* sync(window);
-79
View File
@@ -1,79 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { vi } from "vite-plus/test";
import * as DesktopIpc from "./DesktopIpc.ts";
const invokeMethod: DesktopIpc.DesktopIpcMethod<never, never> = {
channel: "desktop.test.invoke",
handler: () => Effect.void,
};
const syncMethod: DesktopIpc.DesktopSyncIpcMethod<never, never> = {
channel: "desktop.test.sync",
handler: () => Effect.void,
};
function makeIpcMain(
overrides: Partial<DesktopIpc.DesktopIpcMain> = {},
): DesktopIpc.DesktopIpcMain {
return {
removeHandler: vi.fn(),
handle: vi.fn(),
removeAllListeners: vi.fn(),
on: vi.fn(),
...overrides,
};
}
describe("DesktopIpc", () => {
it.effect("preserves invoke registration context and cause", () =>
Effect.gen(function* () {
const cause = new Error("invoke registration failed");
const ipcMain = makeIpcMain({
handle: () => {
throw cause;
},
});
const ipc = DesktopIpc.make(ipcMain);
const error = yield* Effect.flip(Effect.scoped(ipc.handle(invokeMethod)));
assert.instanceOf(error, DesktopIpc.DesktopIpcRegistrationError);
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
assert.strictEqual(error.handlerKind, "invoke");
assert.strictEqual(error.channel, invokeMethod.channel);
assert.strictEqual(error.cause, cause);
assert.include(error.message, "invoke");
assert.include(error.message, invokeMethod.channel);
assert.notInclude(error.message, cause.message);
}),
);
it.effect("preserves sync unregistration context and cause in the finalizer defect", () =>
Effect.gen(function* () {
const cause = new Error("sync unregistration failed");
let removeCount = 0;
const ipcMain = makeIpcMain({
removeAllListeners: () => {
removeCount += 1;
if (removeCount === 2) throw cause;
},
});
const ipc = DesktopIpc.make(ipcMain);
const exit = yield* Effect.exit(Effect.scoped(ipc.handleSync(syncMethod)));
assert.isTrue(exit._tag === "Failure");
if (exit._tag === "Success") return;
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopIpc.DesktopIpcUnregistrationError);
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
assert.strictEqual(error.handlerKind, "sync");
assert.strictEqual(error.channel, syncMethod.channel);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}),
);
});
+35 -91
View File
@@ -1,6 +1,5 @@
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope"; import * as Scope from "effect/Scope";
@@ -24,39 +23,6 @@ export interface DesktopIpcMain {
on(channel: string, listener: DesktopIpcSyncListener): void; on(channel: string, listener: DesktopIpcSyncListener): void;
} }
export class DesktopIpcRegistrationError extends Schema.TaggedErrorClass<DesktopIpcRegistrationError>()(
"DesktopIpcRegistrationError",
{
handlerKind: Schema.Literals(["invoke", "sync"]),
channel: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to register the ${this.handlerKind} IPC handler for ${this.channel}.`;
}
}
export class DesktopIpcUnregistrationError extends Schema.TaggedErrorClass<DesktopIpcUnregistrationError>()(
"DesktopIpcUnregistrationError",
{
handlerKind: Schema.Literals(["invoke", "sync"]),
channel: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to unregister the ${this.handlerKind} IPC handler for ${this.channel}.`;
}
}
export const DesktopIpcError = Schema.Union([
DesktopIpcRegistrationError,
DesktopIpcUnregistrationError,
]);
export type DesktopIpcError = typeof DesktopIpcError.Type;
export const isDesktopIpcError = Schema.is(DesktopIpcError);
export interface DesktopIpcMethod<E, R> { export interface DesktopIpcMethod<E, R> {
readonly channel: string; readonly channel: string;
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>; readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
@@ -67,19 +33,20 @@ export interface DesktopSyncIpcMethod<E, R> {
readonly handler: () => Effect.Effect<unknown, E, R>; readonly handler: () => Effect.Effect<unknown, E, R>;
} }
export class DesktopIpc extends Context.Service< export interface DesktopIpcShape {
DesktopIpc, readonly handle: <E, R>(
{ input: DesktopIpcMethod<E, R>,
readonly handle: <E, R>( ) => Effect.Effect<void, never, R | Scope.Scope>;
input: DesktopIpcMethod<E, R>, readonly handleSync: <E, R>(
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>; input: DesktopSyncIpcMethod<E, R>,
readonly handleSync: <E, R>( ) => Effect.Effect<void, never, R | Scope.Scope>;
input: DesktopSyncIpcMethod<E, R>, }
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
}
>()("@t3tools/desktop/ipc/DesktopIpc") {}
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({ DesktopIpc.of({
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({ handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
channel, channel,
@@ -90,27 +57,18 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
const runPromise = Effect.runPromiseWith(context); const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease( yield* Effect.acquireRelease(
Effect.try({ Effect.sync(() => {
try: () => { ipcMain.removeHandler(channel);
ipcMain.removeHandler(channel); ipcMain.handle(channel, (_event, raw) =>
ipcMain.handle(channel, (_event, raw) => runPromise(
runPromise( Effect.gen(function* () {
Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel });
yield* Effect.annotateCurrentSpan({ channel }); return yield* handler(raw);
return yield* handler(raw); }).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")), ),
), );
);
},
catch: (cause) =>
new DesktopIpcRegistrationError({ handlerKind: "invoke", channel, cause }),
}), }),
() => () => Effect.sync(() => ipcMain.removeHandler(channel)),
Effect.try({
try: () => ipcMain.removeHandler(channel),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
}).pipe(Effect.orDie),
); );
}), }),
@@ -123,36 +81,22 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
const runSync = Effect.runSyncWith(context); const runSync = Effect.runSyncWith(context);
yield* Effect.acquireRelease( yield* Effect.acquireRelease(
Effect.try({ Effect.sync(() => {
try: () => { ipcMain.removeAllListeners(channel);
ipcMain.removeAllListeners(channel); ipcMain.on(channel, (event) => {
ipcMain.on(channel, (event) => { event.returnValue = runSync(
event.returnValue = runSync( Effect.gen(function* () {
Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel });
yield* Effect.annotateCurrentSpan({ channel }); return yield* handler();
return yield* handler(); }).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync")),
}).pipe( );
Effect.annotateLogs({ channel }), });
Effect.withSpan("desktop.ipc.invokeSync"),
),
);
});
},
catch: (cause) =>
new DesktopIpcRegistrationError({ handlerKind: "sync", channel, cause }),
}), }),
() => () => Effect.sync(() => ipcMain.removeAllListeners(channel)),
Effect.try({
try: () => ipcMain.removeAllListeners(channel),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
}).pipe(Effect.orDie),
); );
}), }),
}); });
export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
/** /**
* Convenience helpers for creating IPC methods * Convenience helpers for creating IPC methods
*/ */
+23 -9
View File
@@ -1,12 +1,21 @@
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as DesktopIpc from "./DesktopIpc.ts"; import * as DesktopIpc from "./DesktopIpc.ts";
import {
clearCloudAuthToken,
createCloudAuthRequest,
fetchCloudAuth,
getCloudAuthToken,
setCloudAuthToken,
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts"; import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import { import {
clearConnectionCatalog, getSavedEnvironmentRegistry,
getConnectionCatalog, getSavedEnvironmentSecret,
setConnectionCatalog, removeSavedEnvironmentSecret,
} from "./methods/connectionCatalog.ts"; setSavedEnvironmentRegistry,
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
import { import {
getAdvertisedEndpoints, getAdvertisedEndpoints,
getServerExposureState, getServerExposureState,
@@ -33,7 +42,6 @@ import {
import { import {
confirm, confirm,
getAppBranding, getAppBranding,
getLocalEnvironmentBearerToken,
getLocalEnvironmentBootstrap, getLocalEnvironmentBootstrap,
openExternal, openExternal,
pickFolder, pickFolder,
@@ -48,13 +56,14 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handleSync(getAppBranding); yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap); yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(getClientSettings); yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings); yield* ipc.handle(setClientSettings);
yield* ipc.handle(getConnectionCatalog); yield* ipc.handle(getSavedEnvironmentRegistry);
yield* ipc.handle(setConnectionCatalog); yield* ipc.handle(setSavedEnvironmentRegistry);
yield* ipc.handle(clearConnectionCatalog); yield* ipc.handle(getSavedEnvironmentSecret);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(discoverSshHosts); yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment); yield* ipc.handle(ensureSshEnvironment);
@@ -75,6 +84,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTheme); yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu); yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal); yield* ipc.handle(openExternal);
yield* ipc.handle(createCloudAuthRequest);
yield* ipc.handle(getCloudAuthToken);
yield* ipc.handle(setCloudAuthToken);
yield* ipc.handle(clearCloudAuthToken);
yield* ipc.handle(fetchCloudAuth);
yield* ipc.handle(getUpdateState); yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel); yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate); yield* ipc.handle(downloadUpdate);
+11 -5
View File
@@ -3,6 +3,12 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme"; export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
export const MENU_ACTION_CHANNEL = "desktop:menu-action"; export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const UPDATE_STATE_CHANNEL = "desktop:update-state"; export const UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
@@ -12,13 +18,13 @@ export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
export const UPDATE_CHECK_CHANNEL = "desktop:update-check"; export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding"; export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap"; export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings"; export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings"; export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog"; export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog"; export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog"; export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts"; export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment"; export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment"; export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
@@ -5,9 +5,9 @@ import * as Schema from "effect/Schema";
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts"; import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
import * as IpcChannels from "../channels.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, channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: Schema.NullOr(ClientSettingsSchema), 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, channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
payload: ClientSettingsSchema, payload: ClientSettingsSchema,
result: Schema.Void, result: Schema.Void,
@@ -0,0 +1,97 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { afterEach } from "vite-plus/test";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const originalFetch = globalThis.fetch;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
const calls: Array<FetchCall> = [];
let responseIndex = 0;
const fetchFn = ((input, init) => {
calls.push([input, init ?? {}]);
const response = responses[responseIndex++];
if (!response) {
return Promise.reject(new Error("Unexpected fetch call"));
}
return Promise.resolve(response);
}) satisfies typeof fetch;
return { fetchFn, calls };
};
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
}
});
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"x-mobile": "1",
},
body,
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert.equal(
new Headers(init.headers).get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://clerk.t3.codes/v1/client",
method: "GET",
headers: {},
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
},
);
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
assert.throws(
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
/restricted to Clerk Frontend API HTTPS hosts/u,
);
});
});
+177
View File
@@ -0,0 +1,177 @@
import {
DesktopCloudAuthFetchInputSchema,
DesktopCloudAuthFetchResultSchema,
} from "@t3tools/contracts";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
readonly reason: string;
readonly cause?: unknown;
}> {
override get message() {
return this.reason;
}
}
function configuredClerkFrontendApiHostname(): string | null {
const publishableKey =
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? ""
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
if (!publishableKey) return null;
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
}
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
throw new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
});
}
return url;
}
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
return Effect.gen(function* () {
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(headers),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
HttpClient.execute,
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed to execute.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
});
}
const electronNetFetchLayer = Layer.unwrap(
Effect.gen(function* () {
const electronFetch = yield* Effect.promise(async () => {
const electron = (await import("electron")) as {
readonly net?: { readonly fetch?: typeof globalThis.fetch };
};
return typeof electron.net?.fetch === "function"
? electron.net.fetch.bind(electron.net)
: null;
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
if (!electronFetch) {
yield* Effect.logWarning(
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
);
}
return FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
);
}),
);
export const createCloudAuthRequest = makeIpcMethod({
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
payload: Schema.Void,
result: Schema.String,
handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
return yield* cloudAuth.createRequest;
}),
});
export const getCloudAuthToken = makeIpcMethod({
channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return Option.getOrNull(yield* tokenStore.get);
}),
});
export const setCloudAuthToken = makeIpcMethod({
channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return yield* tokenStore.set(token);
}),
});
export const clearCloudAuthToken = makeIpcMethod({
channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
yield* tokenStore.clear;
}),
});
export const fetchCloudAuth = makeIpcMethod({
channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
payload: DesktopCloudAuthFetchInputSchema,
result: DesktopCloudAuthFetchResultSchema,
handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
const url = yield* Effect.try({
try: () => validateClerkFrontendApiUrl(input.url),
catch: (cause) =>
cause instanceof DesktopCloudAuthFetchError
? cause
: new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch received an invalid URL.",
cause,
}),
});
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
}),
});
@@ -1,37 +0,0 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
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";
export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return Option.getOrNull(yield* store.get);
}),
});
export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return yield* store.set(catalog);
}),
});
export const clearConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* store.clear;
}),
});
+44 -37
View File
@@ -19,33 +19,40 @@ import {
PreviewAutomationSnapshot, PreviewAutomationSnapshot,
PreviewAutomationStatus, PreviewAutomationStatus,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as NodeURL from "node:url"; import { pathToFileURL } from "node:url";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as PreviewManager from "../../preview/Manager.ts"; import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts"; import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.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()) {
if (!window.isDestroyed()) {
window.webContents.send(channel, ...args);
}
}
};
export const installPreviewEventForwarding = Effect.fn( export const installPreviewEventForwarding = Effect.fn(
"desktop.ipc.preview.installEventForwarding", "desktop.ipc.preview.installEventForwarding",
)(function* () { )(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const manager = yield* PreviewManager.PreviewManager; const manager = yield* PreviewManager.PreviewManager;
yield* manager.subscribeStateChanges((tabId, state) => yield* manager.subscribeStateChanges((tabId, state) => {
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state), broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
); });
yield* manager.subscribeRecordingFrames((frame) => yield* manager.subscribeRecordingFrames((frame) => {
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame), broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
); });
yield* manager.subscribePointerEvents((event) => yield* manager.subscribePointerEvents((event) => {
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event), broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
); });
}); });
export const createTab = DesktopIpc.makeIpcMethod({ export const createTab = makeIpcMethod({
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema, payload: DesktopPreviewTabInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -55,7 +62,7 @@ export const createTab = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const closeTab = DesktopIpc.makeIpcMethod({ export const closeTab = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema, payload: DesktopPreviewTabInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -65,7 +72,7 @@ export const closeTab = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const registerWebview = DesktopIpc.makeIpcMethod({ export const registerWebview = makeIpcMethod({
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
payload: DesktopPreviewRegisterWebviewInputSchema, payload: DesktopPreviewRegisterWebviewInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -75,7 +82,7 @@ export const registerWebview = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const navigate = DesktopIpc.makeIpcMethod({ export const navigate = makeIpcMethod({
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL, channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
payload: DesktopPreviewNavigateInputSchema, payload: DesktopPreviewNavigateInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -89,11 +96,11 @@ const tabMethod = (
channel: string, channel: string,
name: string, name: string,
invoke: ( invoke: (
manager: PreviewManager.PreviewManager["Service"], manager: PreviewManager.PreviewManagerShape,
tabId: string, tabId: string,
) => Effect.Effect<void, PreviewManager.PreviewManagerError>, ) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
) => ) =>
DesktopIpc.makeIpcMethod({ makeIpcMethod({
channel, channel,
payload: DesktopPreviewTabInputSchema, payload: DesktopPreviewTabInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -159,7 +166,7 @@ export const stopRecording = tabMethod(
(manager, tabId) => manager.stopRecording(tabId), (manager, tabId) => manager.stopRecording(tabId),
); );
export const clearCookies = DesktopIpc.makeIpcMethod({ export const clearCookies = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL, channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: Schema.Void, result: Schema.Void,
@@ -169,7 +176,7 @@ export const clearCookies = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const clearCache = DesktopIpc.makeIpcMethod({ export const clearCache = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL, channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: Schema.Void, result: Schema.Void,
@@ -179,7 +186,7 @@ export const clearCache = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const getPreviewConfig = DesktopIpc.makeIpcMethod({ export const getPreviewConfig = makeIpcMethod({
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
payload: DesktopPreviewConfigInputSchema, payload: DesktopPreviewConfigInputSchema,
result: DesktopPreviewWebviewConfigSchema, result: DesktopPreviewWebviewConfigSchema,
@@ -189,12 +196,12 @@ export const getPreviewConfig = DesktopIpc.makeIpcMethod({
return { return {
partition: yield* manager.getBrowserPartition(environmentId), partition: yield* manager.getBrowserPartition(environmentId),
webPreferences: PREVIEW_WEBVIEW_PREFERENCES, 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, channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
payload: DesktopPreviewAnnotationThemeInputSchema, payload: DesktopPreviewAnnotationThemeInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -204,7 +211,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const pickElement = DesktopIpc.makeIpcMethod({ export const pickElement = makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema, payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationPayloadSchema), result: Schema.NullOr(PreviewAnnotationPayloadSchema),
@@ -214,7 +221,7 @@ export const pickElement = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const captureScreenshot = DesktopIpc.makeIpcMethod({ export const captureScreenshot = makeIpcMethod({
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema, payload: DesktopPreviewTabInputSchema,
result: DesktopPreviewScreenshotArtifactSchema, result: DesktopPreviewScreenshotArtifactSchema,
@@ -224,7 +231,7 @@ export const captureScreenshot = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const revealArtifact = DesktopIpc.makeIpcMethod({ export const revealArtifact = makeIpcMethod({
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema, payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -234,7 +241,7 @@ export const revealArtifact = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({ export const copyArtifactToClipboard = makeIpcMethod({
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema, payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -244,7 +251,7 @@ export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const automationStatus = DesktopIpc.makeIpcMethod({ export const automationStatus = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL, channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
payload: DesktopPreviewTabInputSchema, payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationStatus, result: PreviewAutomationStatus,
@@ -254,7 +261,7 @@ export const automationStatus = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const automationSnapshot = DesktopIpc.makeIpcMethod({ export const automationSnapshot = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL, channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema, payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationSnapshot, result: PreviewAutomationSnapshot,
@@ -264,7 +271,7 @@ export const automationSnapshot = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const automationClick = DesktopIpc.makeIpcMethod({ export const automationClick = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL, channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
payload: DesktopPreviewAutomationClickInputSchema, payload: DesktopPreviewAutomationClickInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -274,7 +281,7 @@ export const automationClick = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const automationType = DesktopIpc.makeIpcMethod({ export const automationType = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL, channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
payload: DesktopPreviewAutomationTypeInputSchema, payload: DesktopPreviewAutomationTypeInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -284,7 +291,7 @@ export const automationType = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const automationPress = DesktopIpc.makeIpcMethod({ export const automationPress = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL, channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
payload: DesktopPreviewAutomationPressInputSchema, payload: DesktopPreviewAutomationPressInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -294,7 +301,7 @@ export const automationPress = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const automationScroll = DesktopIpc.makeIpcMethod({ export const automationScroll = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL, channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
payload: DesktopPreviewAutomationScrollInputSchema, payload: DesktopPreviewAutomationScrollInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -304,7 +311,7 @@ export const automationScroll = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const automationEvaluate = DesktopIpc.makeIpcMethod({ export const automationEvaluate = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL, channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
payload: DesktopPreviewAutomationEvaluateInputSchema, payload: DesktopPreviewAutomationEvaluateInputSchema,
result: Schema.Unknown, result: Schema.Unknown,
@@ -314,7 +321,7 @@ export const automationEvaluate = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const automationWaitFor = DesktopIpc.makeIpcMethod({ export const automationWaitFor = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL, channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
payload: DesktopPreviewAutomationWaitForInputSchema, payload: DesktopPreviewAutomationWaitForInputSchema,
result: Schema.Void, result: Schema.Void,
@@ -324,7 +331,7 @@ export const automationWaitFor = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const saveRecording = DesktopIpc.makeIpcMethod({ export const saveRecording = makeIpcMethod({
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL, channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
payload: DesktopPreviewRecordingSaveInputSchema, payload: DesktopPreviewRecordingSaveInputSchema,
result: DesktopPreviewRecordingArtifactSchema, result: DesktopPreviewRecordingArtifactSchema,
@@ -0,0 +1,76 @@
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
const NonBlankString = Schema.String.check(
Schema.makeFilter((value) =>
value.trim().length > 0 ? undefined : "Expected a non-empty string",
),
);
const SetSavedEnvironmentSecretInput = Schema.Struct({
environmentId: EnvironmentId,
secret: NonBlankString,
});
export const getSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: Schema.Void,
result: SavedEnvironmentRegistryPayload,
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.getRegistry;
}),
});
export const setSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: SavedEnvironmentRegistryPayload,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry(records);
}),
});
export const getSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
}),
});
export const setSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: SetSavedEnvironmentSecretInput,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
environmentId,
secret,
}) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.setSecret({
environmentId,
secret,
});
}),
});
export const removeSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.removeSecret(environmentId);
}),
});
@@ -9,14 +9,14 @@ import * as Schema from "effect/Schema";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts"; import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts"; import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts";
import * as IpcChannels from "../channels.ts"; import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts"; import { makeIpcMethod } from "../DesktopIpc.ts";
const SetTailscaleServeEnabledInput = Schema.Struct({ const SetTailscaleServeEnabledInput = Schema.Struct({
enabled: Schema.Boolean, enabled: Schema.Boolean,
port: Schema.optionalKey(Schema.Number), port: Schema.optionalKey(Schema.Number),
}); });
export const getServerExposureState = DesktopIpc.makeIpcMethod({ export const getServerExposureState = makeIpcMethod({
channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL, channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: DesktopServerExposureStateSchema, 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, channel: IpcChannels.SET_SERVER_EXPOSURE_MODE_CHANNEL,
payload: DesktopServerExposureModeSchema, payload: DesktopServerExposureModeSchema,
result: DesktopServerExposureStateSchema, 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, channel: IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL,
payload: SetTailscaleServeEnabledInput, payload: SetTailscaleServeEnabledInput,
result: DesktopServerExposureStateSchema, 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, channel: IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: Schema.Array(AdvertisedEndpoint), result: Schema.Array(AdvertisedEndpoint),
+11 -11
View File
@@ -1,11 +1,11 @@
import { import {
bootstrapRemoteBearerSession, bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState, fetchRemoteSessionState,
issueRemoteWebSocketTicket, issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError, RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError, type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime/authorization"; } from "@t3tools/client-runtime";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import { import {
EnvironmentAuthInvalidError, EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema, DesktopDiscoveredSshHostSchema,
@@ -33,7 +33,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as IpcChannels from "../channels.ts"; 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 DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.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, channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: Schema.Array(DesktopDiscoveredSshHostSchema), 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, channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentEnsureInputSchema, payload: DesktopSshEnvironmentEnsureInputSchema,
result: DesktopSshEnvironmentEnsureResultSchema, 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, channel: IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentTargetSchema, payload: DesktopSshEnvironmentTargetSchema,
result: Schema.Void, 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, channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
payload: DesktopSshHttpBaseUrlInputSchema, payload: DesktopSshHttpBaseUrlInputSchema,
result: ExecutionEnvironmentDescriptor, 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, channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
payload: DesktopSshBearerBootstrapInputSchema, payload: DesktopSshBearerBootstrapInputSchema,
result: AuthAccessTokenResult, 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, channel: IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL,
payload: DesktopSshBearerRequestInputSchema, payload: DesktopSshBearerRequestInputSchema,
result: AuthSessionState, 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, channel: IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
payload: DesktopSshBearerRequestInputSchema, payload: DesktopSshBearerRequestInputSchema,
result: AuthWebSocketTicketResult, 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, channel: IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
payload: DesktopSshPasswordPromptResolutionInputSchema, payload: DesktopSshPasswordPromptResolutionInputSchema,
result: Schema.Void, result: Schema.Void,
+6 -6
View File
@@ -9,9 +9,9 @@ import * as Schema from "effect/Schema";
import * as DesktopUpdates from "../../updates/DesktopUpdates.ts"; import * as DesktopUpdates from "../../updates/DesktopUpdates.ts";
import * as IpcChannels from "../channels.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, channel: IpcChannels.UPDATE_GET_STATE_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: DesktopUpdateStateSchema, 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, channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
payload: DesktopUpdateChannelSchema, payload: DesktopUpdateChannelSchema,
result: DesktopUpdateStateSchema, 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, channel: IpcChannels.UPDATE_DOWNLOAD_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: DesktopUpdateActionResultSchema, 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, channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: DesktopUpdateActionResultSchema, 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, channel: IpcChannels.UPDATE_CHECK_CHANNEL,
payload: Schema.Void, payload: Schema.Void,
result: DesktopUpdateCheckResultSchema, result: DesktopUpdateCheckResultSchema,
+8 -19
View File
@@ -10,7 +10,6 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts"; import * as ElectronMenu from "../../electron/ElectronMenu.ts";
@@ -18,7 +17,7 @@ import * as ElectronShell from "../../electron/ElectronShell.ts";
import * as ElectronTheme from "../../electron/ElectronTheme.ts"; import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as IpcChannels from "../channels.ts"; import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts"; import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
const ContextMenuPosition = Schema.Struct({ const ContextMenuPosition = Schema.Struct({
x: Schema.Number, x: Schema.Number,
@@ -36,7 +35,7 @@ function toWebSocketBaseUrl(httpBaseUrl: URL): string {
return url.href; return url.href;
} }
export const getAppBranding = DesktopIpc.makeSyncIpcMethod({ export const getAppBranding = makeSyncIpcMethod({
channel: IpcChannels.GET_APP_BRANDING_CHANNEL, channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
result: Schema.NullOr(DesktopAppBrandingSchema), result: Schema.NullOr(DesktopAppBrandingSchema),
handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () { handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
@@ -45,7 +44,7 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}), }),
}); });
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({ export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema), result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () { handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
@@ -65,17 +64,7 @@ export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
}), }),
}); });
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({ export const pickFolder = makeIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.String,
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* localAuth.getBearerToken;
}),
});
export const pickFolder = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PICK_FOLDER_CHANNEL, channel: IpcChannels.PICK_FOLDER_CHANNEL,
payload: Schema.UndefinedOr(PickFolderOptionsSchema), payload: Schema.UndefinedOr(PickFolderOptionsSchema),
result: Schema.NullOr(Schema.String), result: Schema.NullOr(Schema.String),
@@ -91,7 +80,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const confirm = DesktopIpc.makeIpcMethod({ export const confirm = makeIpcMethod({
channel: IpcChannels.CONFIRM_CHANNEL, channel: IpcChannels.CONFIRM_CHANNEL,
payload: Schema.String, payload: Schema.String,
result: Schema.Boolean, result: Schema.Boolean,
@@ -104,7 +93,7 @@ export const confirm = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const setTheme = DesktopIpc.makeIpcMethod({ export const setTheme = makeIpcMethod({
channel: IpcChannels.SET_THEME_CHANNEL, channel: IpcChannels.SET_THEME_CHANNEL,
payload: DesktopThemeSchema, payload: DesktopThemeSchema,
result: Schema.Void, result: Schema.Void,
@@ -114,7 +103,7 @@ export const setTheme = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const showContextMenu = DesktopIpc.makeIpcMethod({ export const showContextMenu = makeIpcMethod({
channel: IpcChannels.CONTEXT_MENU_CHANNEL, channel: IpcChannels.CONTEXT_MENU_CHANNEL,
payload: ContextMenuInput, payload: ContextMenuInput,
result: Schema.NullOr(Schema.String), result: Schema.NullOr(Schema.String),
@@ -135,7 +124,7 @@ export const showContextMenu = DesktopIpc.makeIpcMethod({
}), }),
}); });
export const openExternal = DesktopIpc.makeIpcMethod({ export const openExternal = makeIpcMethod({
channel: IpcChannels.OPEN_EXTERNAL_CHANNEL, channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
payload: Schema.String, payload: Schema.String,
result: Schema.Boolean, result: Schema.Boolean,
+20 -37
View File
@@ -9,34 +9,31 @@ import * as Option from "effect/Option";
import * as Electron from "electron"; import * as Electron from "electron";
import * as NetService from "@t3tools/shared/Net"; import * as NetService from "@t3tools/shared/Net";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command"; import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel"; import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import serverPackageJson from "../../server/package.json" with { type: "json" }; 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 DesktopIpc from "./ipc/DesktopIpc.ts";
import * as ElectronApp from "./electron/ElectronApp.ts"; import * as ElectronApp from "./electron/ElectronApp.ts";
import * as ElectronDialog from "./electron/ElectronDialog.ts"; import * as ElectronDialog from "./electron/ElectronDialog.ts";
import * as ElectronMenu from "./electron/ElectronMenu.ts"; import * as ElectronMenu from "./electron/ElectronMenu.ts";
import * as ElectronProtocol from "./electron/ElectronProtocol.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 ElectronShell from "./electron/ElectronShell.ts";
import * as ElectronTheme from "./electron/ElectronTheme.ts"; import * as ElectronTheme from "./electron/ElectronTheme.ts";
import * as ElectronUpdater from "./electron/ElectronUpdater.ts"; import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
import * as ElectronWindow from "./electron/ElectronWindow.ts"; import * as ElectronWindow from "./electron/ElectronWindow.ts";
import * as DesktopApp from "./app/DesktopApp.ts"; import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts"; import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts"; import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopClerk from "./app/DesktopClerk.ts"; import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts"; import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts"; import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts"; import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendManager from "./backend/DesktopBackendManager.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 DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts"; import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
import * as DesktopObservability from "./app/DesktopObservability.ts"; import * as DesktopObservability from "./app/DesktopObservability.ts";
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts"; import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts"; import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
@@ -47,7 +44,7 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts"; import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts"; import * as DesktopState from "./app/DesktopState.ts";
import * as DesktopUpdates from "./updates/DesktopUpdates.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 PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts"; import * as DesktopWindow from "./window/DesktopWindow.ts";
@@ -56,21 +53,19 @@ const desktopEnvironmentLayer = Layer.unwrap(
const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe( const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe(
Effect.flatMap((app) => app.metadata), Effect.flatMap((app) => app.metadata),
); );
const platform = yield* HostProcessPlatform;
const processArch = yield* HostProcessArchitecture;
return DesktopEnvironment.layer({ return DesktopEnvironment.layer({
dirname: __dirname, dirname: __dirname,
homeDirectory: NodeOS.homedir(), homeDirectory: NodeOS.homedir(),
platform, platform: process.platform,
processArch, processArch: process.arch,
...metadata, ...metadata,
}); });
}), }),
); );
const resolveDesktopSshCliRunner = ( const resolveDesktopSshCliRunner = (
environment: DesktopEnvironment.DesktopEnvironment["Service"], environment: DesktopEnvironment.DesktopEnvironmentShape,
settings: DesktopAppSettings.DesktopSettings, settings: DesktopSettingsValue,
): RemoteT3RunnerOptions => { ): RemoteT3RunnerOptions => {
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath); const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
if (environment.isDevelopment && devRemoteEntryPath !== undefined) { if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
@@ -106,20 +101,21 @@ const electronLayer = Layer.mergeAll(
ElectronDialog.layer, ElectronDialog.layer,
ElectronMenu.layer, ElectronMenu.layer,
ElectronProtocol.layer, ElectronProtocol.layer,
ElectronSafeStorage.layer, DesktopSecretStorage.layer,
ElectronShell.layer, ElectronShell.layer,
ElectronTheme.layer, ElectronTheme.layer,
ElectronUpdater.layer, ElectronUpdater.layer,
ElectronWindow.layer, ElectronWindow.layer,
DesktopIpc.layer(Electron.ipcMain), Layer.succeed(DesktopIpc.DesktopIpc, DesktopIpc.make(Electron.ipcMain)),
); );
const desktopFoundationLayer = Layer.mergeAll( const desktopFoundationLayer = Layer.mergeAll(
DesktopState.layer, DesktopState.layer,
DesktopShutdown.layer, DesktopLifecycle.layerShutdown,
DesktopAppSettings.layer, DesktopAppSettings.layer,
DesktopClientSettings.layer, DesktopClientSettings.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)), DesktopSavedEnvironments.layer,
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer, DesktopAssets.layer,
DesktopObservability.layer, DesktopObservability.layer,
).pipe(Layer.provideMerge(desktopEnvironmentLayer)); ).pipe(Layer.provideMerge(desktopEnvironmentLayer));
@@ -129,12 +125,12 @@ const desktopSshLayer = desktopSshEnvironmentLayer.pipe(
); );
const desktopServerExposureLayer = DesktopServerExposure.layer.pipe( const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
Layer.provideMerge(DesktopNetworkInterfaces.layer), Layer.provideMerge(DesktopServerExposure.networkInterfacesLayer),
Layer.provideMerge(desktopFoundationLayer), Layer.provideMerge(desktopFoundationLayer),
); );
const desktopPreviewLayer = PreviewManager.layer.pipe( const desktopPreviewLayer = PreviewManager.layer.pipe(
Layer.provideMerge(BrowserSession.layer), Layer.provideMerge(PreviewBrowserSession.layer),
Layer.provideMerge(desktopFoundationLayer), Layer.provideMerge(desktopFoundationLayer),
); );
@@ -149,30 +145,17 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(desktopWindowLayer), Layer.provideMerge(desktopWindowLayer),
); );
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
const desktopApplicationLayer = Layer.mergeAll( const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer, DesktopLifecycle.layer,
DesktopApplicationMenu.layer, DesktopApplicationMenu.layer,
DesktopCloudAuth.layer,
DesktopShellEnvironment.layer, DesktopShellEnvironment.layer,
desktopSshLayer, desktopSshLayer,
).pipe( ).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
const desktopClerkLayer = DesktopClerk.layer.pipe( const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
Layer.provideMerge(desktopEnvironmentLayer), Layer.flatMap(() =>
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ElectronApp.layer),
);
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
desktopApplicationLayer.pipe( desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer), Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici), Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer), Layer.provideMerge(NetService.layer),
+27 -9
View File
@@ -4,13 +4,10 @@ import type {
DesktopPreviewRecordingFrame, DesktopPreviewRecordingFrame,
DesktopPreviewTabState, DesktopPreviewTabState,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron"; import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts"; import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
function unwrapEnsureSshEnvironmentResult(result: unknown) { function unwrapEnsureSshEnvironmentResult(result: unknown) {
if ( if (
typeof result === "object" && typeof result === "object" &&
@@ -42,15 +39,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
} }
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>; return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
}, },
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL), getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) => setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings), ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL), getSavedEnvironmentRegistry: () =>
setConnectionCatalog: (catalog) => ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog), setSavedEnvironmentRegistry: (records) =>
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL), ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL), discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) => ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult( unwrapEnsureSshEnvironmentResult(
@@ -100,6 +101,23 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }), ...(position === undefined ? {} : { position }),
}), }),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
createCloudAuthRequest: () => ipcRenderer.invoke(IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL),
getCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL),
setCloudAuthToken: (token: string) =>
ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token),
clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL),
fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input),
onCloudAuthCallback: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => {
if (typeof rawUrl !== "string") return;
listener(rawUrl);
};
ipcRenderer.on(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
};
},
onMenuAction: (listener) => { onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => { const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return; if (typeof action !== "string") return;
@@ -1,9 +1,7 @@
import { assert, describe, it } from "@effect/vitest"; import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { beforeEach, vi } from "vite-plus/test"; import { beforeEach, vi } from "vite-plus/test";
const { fromPartition, sessions } = vi.hoisted(() => ({ const { fromPartition, sessions } = vi.hoisted(() => ({
@@ -61,64 +59,6 @@ describe("BrowserSession", () => {
}).pipe(Effect.provide(layer)), }).pipe(Effect.provide(layer)),
); );
it.effect("preserves partition scope and the platform failure chain", () => {
const nativeCause = new Error("native digest failed");
const platformCause = PlatformError.systemError({
_tag: "Unknown",
module: "Crypto",
method: "digest",
cause: nativeCause,
});
const failingCryptoLayer = Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: (size) => new Uint8Array(size),
digest: () => Effect.fail(platformCause),
}),
);
return Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
assert.isTrue(BrowserSession.isBrowserSessionError(error));
assert.equal(error.scope, "environment-a");
assert.strictEqual(error.cause, platformCause);
assert.strictEqual(error.cause.reason.cause, nativeCause);
assert.equal(
error.message,
"Failed to derive a desktop preview browser partition for scope environment-a.",
);
assert.notInclude(error.message, nativeCause.message);
}).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
});
it.effect("preserves session scope, partition, and the Electron failure", () =>
Effect.gen(function* () {
const cause = new Error("Electron session failed");
fromPartition.mockImplementationOnce(() => {
throw cause;
});
const browserSessions = yield* BrowserSession.BrowserSession;
const partition = yield* browserSessions.getPartition("environment-b");
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
assert.isTrue(BrowserSession.isBrowserSessionError(error));
assert.equal(error.scope, "environment-b");
assert.equal(error.partition, partition);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(layer)),
);
it.effect("clears storage and cache for every created session", () => it.effect("clears storage and cache for every created session", () =>
Effect.gen(function* () { Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession; const browserSessions = yield* BrowserSession.BrowserSession;
@@ -140,52 +80,4 @@ describe("BrowserSession", () => {
} }
}).pipe(Effect.provide(layer)), }).pipe(Effect.provide(layer)),
); );
it.effect("correlates clear failures while still attempting every session", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
yield* browserSessions.getSession("scope-a");
yield* browserSessions.getSession("scope-b");
const firstPartition = yield* browserSessions.getPartition("scope-a");
const secondPartition = yield* browserSessions.getPartition("scope-b");
const firstSession = sessions.get(firstPartition);
const secondSession = sessions.get(secondPartition);
assert.isDefined(firstSession);
assert.isDefined(secondSession);
const storageCause = new Error("storage clear failed");
secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
assert.equal(storageError.partition, secondPartition);
assert.strictEqual(storageError.cause, storageCause);
assert.equal(
storageError.message,
`Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
);
assert.notInclude(storageError.message, storageCause.message);
for (const browserSession of sessions.values()) {
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
}
const cacheCause = new Error("cache clear failed");
firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
assert.equal(cacheError.partition, firstPartition);
assert.strictEqual(cacheError.cause, cacheCause);
assert.equal(
cacheError.message,
`Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
);
assert.notInclude(cacheError.message, cacheCause.message);
for (const browserSession of sessions.values()) {
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
}
}).pipe(Effect.provide(layer)),
);
}); });
+27 -102
View File
@@ -2,107 +2,45 @@ import type { Session } from "electron";
import { session } from "electron"; import { session } from "electron";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto"; import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding"; import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef"; import * as SynchronizedRef from "effect/SynchronizedRef";
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-"; const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()( export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
"BrowserSessionPartitionDerivationError", readonly operation: string;
{ readonly cause: unknown;
scope: Schema.String, }> {
cause: Schema.instanceOf(PlatformError.PlatformError), override get message() {
}, return `Desktop preview browser session operation failed: ${this.operation}`;
) {
override get message(): string {
return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
} }
} }
export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()( export interface BrowserSessionShape {
"BrowserSessionCreationError", readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
{ readonly isPartition: (partition: string) => boolean;
scope: Schema.String, readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
partition: Schema.String, readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
cause: Schema.Defect(), readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
},
) {
override get message(): string {
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
}
} }
export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()( export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
"BrowserSessionStorageClearError", "@t3tools/desktop/preview/BrowserSession",
{ ) {}
partition: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
}
}
export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()( const make = Effect.gen(function* BrowserSessionMake() {
"BrowserSessionCacheClearError",
{
partition: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
}
}
export const BrowserSessionGetSessionError = Schema.Union([
BrowserSessionPartitionDerivationError,
BrowserSessionCreationError,
]);
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
export const BrowserSessionError = Schema.Union([
BrowserSessionPartitionDerivationError,
BrowserSessionCreationError,
BrowserSessionStorageClearError,
BrowserSessionCacheClearError,
]);
export type BrowserSessionError = typeof BrowserSessionError.Type;
export const isBrowserSessionError = Schema.is(BrowserSessionError);
export class BrowserSession extends Context.Service<
BrowserSession,
{
readonly getPartition: (
scope?: string,
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
readonly isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
}
>()("@t3tools/desktop/preview/BrowserSession") {}
export const make = Effect.gen(function* BrowserSessionMake() {
const crypto = yield* Crypto.Crypto; const crypto = yield* Crypto.Crypto;
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map()); const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") { const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe( const digest = yield* crypto
Effect.mapError( .digest("SHA-256", new TextEncoder().encode(scope))
(cause) => .pipe(
new BrowserSessionPartitionDerivationError({ Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
scope, );
cause,
}),
),
);
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`; return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
}); });
@@ -127,12 +65,7 @@ export const make = Effect.gen(function* BrowserSessionMake() {
next.set(partition, browserSession); next.set(partition, browserSession);
return [browserSession, next] as const; return [browserSession, next] as const;
}, },
catch: (cause) => catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
new BrowserSessionCreationError({
scope,
partition,
cause,
}),
}); });
}); });
}); });
@@ -144,17 +77,13 @@ export const make = Effect.gen(function* BrowserSessionMake() {
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () { clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef); const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all( yield* Effect.all(
[...sessions.entries()].map(([partition, browserSession]) => [...sessions.values()].map((browserSession) =>
Effect.tryPromise({ Effect.tryPromise({
try: () => try: () =>
browserSession.clearStorageData({ browserSession.clearStorageData({
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"], storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
}), }),
catch: (cause) => catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
new BrowserSessionStorageClearError({
partition,
cause,
}),
}), }),
), ),
{ concurrency: "unbounded", discard: true }, { concurrency: "unbounded", discard: true },
@@ -163,14 +92,10 @@ export const make = Effect.gen(function* BrowserSessionMake() {
clearCache: Effect.fn("BrowserSession.clearCache")(function* () { clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef); const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all( yield* Effect.all(
[...sessions.entries()].map(([partition, browserSession]) => [...sessions.values()].map((browserSession) =>
Effect.tryPromise({ Effect.tryPromise({
try: () => browserSession.clearCache(), try: () => browserSession.clearCache(),
catch: (cause) => catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
new BrowserSessionCacheClearError({
partition,
cause,
}),
}), }),
), ),
{ concurrency: "unbounded", discard: true }, { concurrency: "unbounded", discard: true },
+20 -765
View File
@@ -1,43 +1,30 @@
import { it as effectIt } from "@effect/vitest"; import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause"; import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit"; import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber"; import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Path from "effect/Path"; import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope"; import type * as Scope from "effect/Scope";
import { TestClock } from "effect/testing"; import { TestClock } from "effect/testing";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { beforeEach, describe, expect, vi } from "vite-plus/test";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as BrowserSession from "./BrowserSession.ts"; import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts"; import * as PreviewManager from "./Manager.ts";
const { const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
createFromPath, vi.hoisted(() => ({
fromId, createFromPath: vi.fn(() => ({ isEmpty: () => false })),
getFocusedWebContents, fromId: vi.fn(() => null),
mkdir, mkdir: vi.fn((_path: string) => undefined),
showItemInFolder, showItemInFolder: vi.fn(),
webviewSend, webviewSend: vi.fn(),
writeFile, writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage, writeImage: vi.fn(),
} = vi.hoisted(() => ({ }));
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
getFocusedWebContents: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
vi.mock("electron", () => ({ vi.mock("electron", () => ({
clipboard: { clipboard: {
@@ -54,7 +41,6 @@ vi.mock("electron", () => ({
}, },
webContents: { webContents: {
fromId, fromId,
getFocusedWebContents,
}, },
})); }));
@@ -73,7 +59,7 @@ const environmentLayer = Layer.succeed(
DesktopEnvironment.DesktopEnvironment, DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of({ DesktopEnvironment.DesktopEnvironment.of({
browserArtifactsDir: "/tmp/t3/dev/browser-artifacts", browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
} as DesktopEnvironment.DesktopEnvironment["Service"]), } as DesktopEnvironment.DesktopEnvironmentShape),
); );
const fileSystemLayer = FileSystem.layerNoop({ const fileSystemLayer = FileSystem.layerNoop({
@@ -92,13 +78,11 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(environmentLayer), Layer.provideMerge(environmentLayer),
Layer.provideMerge(fileSystemLayer), Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer), Layer.provideMerge(Path.layer),
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
); );
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
const withManager = <A>( const withManager = <A>(
use: ( use: (
manager: PreviewManager.PreviewManager["Service"], manager: PreviewManager.PreviewManagerShape,
) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>, ) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
) => ) =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -109,8 +93,6 @@ const withManager = <A>(
describe("PreviewManager", () => { describe("PreviewManager", () => {
beforeEach(() => { beforeEach(() => {
fromId.mockClear(); fromId.mockClear();
getFocusedWebContents.mockReset();
getFocusedWebContents.mockReturnValue(null);
mkdir.mockClear(); mkdir.mockClear();
writeFile.mockClear(); writeFile.mockClear();
showItemInFolder.mockClear(); showItemInFolder.mockClear();
@@ -146,315 +128,6 @@ describe("PreviewManager", () => {
), ),
); );
effectIt.effect("isolates failed state listeners and continues delivery", () => {
const loggedErrors: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
for (const value of Array.isArray(message) ? message : [message]) {
if (typeof value === "object" && value !== null && "cause" in value) {
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
}
}
});
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
operation: "send-window-message",
platform: "darwin",
windowId: 42,
channel: "preview:state-change",
cause: new Error("renderer unavailable"),
});
const delivered = vi.fn();
return withManager((manager) =>
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
yield* manager.subscribeStateChanges((tabId, state) =>
Effect.sync(() => {
delivered(tabId, state);
}),
);
const state = yield* manager.createTab("tab_listener_failure");
expect(delivered).toHaveBeenCalledOnce();
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
expect(loggedErrors).toHaveLength(1);
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
expect(loggedErrors[0]).toMatchObject({
operation: "send-window-message",
windowId: 42,
channel: "preview:state-change",
});
}),
).pipe(
Effect.provide(
Logger.layer([logger], {
mergeWithExisting: false,
}),
),
);
});
effectIt.effect("does not swallow state listener interruption", () =>
withManager((manager) =>
Effect.gen(function* () {
const exit = yield* Effect.scoped(
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.interrupt);
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
}),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
}
}),
),
);
effectIt.effect("queues navigation until the webview registers", () =>
withManager((manager) =>
Effect.gen(function* () {
const loadURL = vi.fn(async () => undefined);
const listeners = new Map<string, (...args: never[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "about:blank",
getTitle: () => "",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
loadURL,
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.navigate("tab_pending", "localhost:3200");
expect(yield* manager.automationStatus("tab_pending")).toEqual({
available: false,
visible: true,
tabId: "tab_pending",
url: "http://localhost:3200/",
title: "",
loading: true,
});
yield* manager.registerWebview("tab_pending", 42);
yield* Effect.yieldNow;
expect(loadURL).toHaveBeenCalledOnce();
expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
}),
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
let effectiveZoom = 0.9;
let zoomReadable = true;
let url = "https://example.com";
const listeners = new Map<string, (...args: unknown[]) => void>();
const setZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => {
if (!zoomReadable) throw new Error("zoom unavailable");
return effectiveZoom;
},
setZoomFactor,
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_zoom");
yield* manager.registerWebview("tab_zoom", 42);
expect(states.at(-1)?.zoomFactor).toBe(0.9);
expect(setZoomFactor).not.toHaveBeenCalled();
effectiveZoom = 1.25;
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.zoomFactor).toBe(1.25);
expect(setZoomFactor).not.toHaveBeenCalled();
zoomReadable = false;
url = "https://example.com/after-zoom-read-failed";
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.navStatus).toEqual({
kind: "Success",
url,
title: "Example",
});
expect(states.at(-1)?.zoomFactor).toBe(1.25);
const replacementSetZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 43,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: replacementSetZoomFactor,
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.registerWebview("tab_zoom", 43);
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
expect(states.at(-1)?.zoomFactor).toBe(1.25);
}),
),
);
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
withManager((manager) =>
Effect.gen(function* () {
const url = "http://localhost:5733/";
let loading = false;
const listeners = new Map<string, (...args: unknown[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "localhost:5733",
isLoading: () => loading,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const statuses: PreviewManager.PreviewNavStatus[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
statuses.push(state.navStatus);
}),
);
yield* manager.createTab("tab_failed");
yield* manager.registerWebview("tab_failed", 42);
listeners.get("did-fail-load")?.(
{},
-105,
"ERR_NAME_NOT_RESOLVED",
"https://missing-frame.example/",
false,
);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
listeners.get("did-stop-loading")?.();
listeners.get("page-title-updated")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)).toEqual({
kind: "LoadFailed",
url,
title: "localhost:5733",
code: -102,
description: "ERR_CONNECTION_REFUSED",
});
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-stop-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () => effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) => withManager((manager) =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -512,69 +185,6 @@ describe("PreviewManager", () => {
expect(artifact.path).toMatch( expect(artifact.path).toMatch(
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/, /\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
); );
const captureCause = new Error("capture failed");
capturePage.mockRejectedValueOnce(captureCause);
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewOperationError",
operation: "captureScreenshot.capturePage",
tabId: "tab_1",
webContentsId: 42,
cause: captureCause,
});
}),
),
);
effectIt.effect("keeps element picking active during subframe navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
const listeners = new Map<string, (...args: unknown[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isFocused: () => true,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
yield* Effect.yieldNow;
listeners.get("did-start-navigation")?.({}, "about:blank", false, false);
yield* Effect.yieldNow;
expect(pick.pollUnsafe()).toBeUndefined();
listeners.get("did-start-navigation")?.({}, "https://example.com/next", false, true);
expect(yield* Fiber.join(pick)).toBeNull();
}), }),
), ),
); );
@@ -591,12 +201,9 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true); expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return; if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause)); const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({ expect(error.cause).toMatchObject({
_tag: "PreviewArtifactPathOutsideDirectoryError", message: "Preview artifact path is outside the configured artifact directory.",
artifactPath: "/tmp/t3/dev/settings.json",
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
}); });
expect("cause" in error).toBe(false);
}), }),
), ),
); );
@@ -616,20 +223,8 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true); expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return; if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause)); const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({ expect(error.cause).toMatchObject({
_tag: "PreviewArtifactPathOutsideDirectoryError", message: "Preview artifact path is outside the configured artifact directory.",
artifactPath: "/tmp/t3/dev/settings.json",
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
});
expect("cause" in error).toBe(false);
createFromPath.mockReturnValueOnce({ isEmpty: () => true });
const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
expect(Exit.isFailure(invalidImageExit)).toBe(true);
if (Exit.isSuccess(invalidImageExit)) return;
expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({
_tag: "PreviewArtifactImageLoadError",
artifactPath,
}); });
}), }),
), ),
@@ -684,11 +279,7 @@ describe("PreviewManager", () => {
}, },
} as never); } as never);
yield* manager.subscribePointerEvents((event) => yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
Effect.sync(() => {
activity.push(event.phase);
}),
);
yield* manager.createTab("tab_1"); yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42); yield* manager.registerWebview("tab_1", 42);
const click = yield* manager const click = yield* manager
@@ -716,178 +307,6 @@ describe("PreviewManager", () => {
), ),
); );
effectIt.effect("types in background webviews and enables native key input", () =>
withManager((manager) =>
Effect.gen(function* () {
let failKeyDown = false;
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (
failKeyDown &&
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
throw new Error("key dispatch failed");
}
if (
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
humanInput?.(
{},
{
kind: "key",
key: params["key"],
code: params["code"] ?? "Digit1",
},
);
}
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
});
const restoreFocus = vi.fn();
const focus = vi.fn();
getFocusedWebContents.mockReturnValue({
id: 7,
isDestroyed: () => false,
focus: restoreFocus,
} as never);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
focus,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_input");
yield* manager.registerWebview("tab_input", 42);
yield* manager.automationType("tab_input", { text: "hello", clear: true });
yield* manager.automationType("tab_input", { text: "", clear: true });
yield* manager.automationPress("tab_input", { key: "x" });
const calls = sendCommand.mock.calls;
const methods = calls.map(([method]) => method);
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
const focusOnIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
);
const keyDownIndex = calls.findIndex(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
);
const keyUpIndex = calls.findIndex(
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
);
const focusOffIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
);
const typeEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('document.execCommand("insertText"'),
);
expect(typeEvaluation).toBeDefined();
const clearOnlyEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('const text = ""') &&
params.expression.includes("Object.getOwnPropertyDescriptor"),
);
expect(clearOnlyEvaluation).toBeDefined();
expect(methods).not.toContain("Input.insertText");
expect(enableIndex).toBeGreaterThanOrEqual(0);
expect(focus).toHaveBeenCalledOnce();
expect(restoreFocus).toHaveBeenCalledOnce();
expect(methods).toContain("Page.bringToFront");
expect(enableIndex).toBeLessThan(focusOnIndex);
expect(focusOnIndex).toBeLessThan(keyDownIndex);
expect(keyDownIndex).toBeLessThan(keyUpIndex);
expect(keyUpIndex).toBeLessThan(focusOffIndex);
expect(
calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
sendCommand.mockClear();
failKeyDown = true;
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
expect(Exit.isFailure(failedPress)).toBe(true);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyUp",
key: "y",
code: "KeyY",
modifiers: 0,
windowsVirtualKeyCode: 89,
location: 0,
isKeypad: false,
});
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
expect(restoreFocus).toHaveBeenCalledTimes(2);
expect(
sendCommand.mock.calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
sendCommand.mockClear();
failKeyDown = false;
yield* manager.automationPress("tab_input", { key: "!" });
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyDown",
key: "!",
code: "Digit1",
modifiers: 0,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
text: "!",
unmodifiedText: "!",
});
expect(restoreFocus).toHaveBeenCalledTimes(3);
}),
),
);
effectIt.effect("still interrupts agent control for a different human pointer event", () => effectIt.effect("still interrupts agent control for a different human pointer event", () =>
withManager((manager) => withManager((manager) =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -946,174 +365,10 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true); expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return; if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause)); const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({ expect(error.cause).toMatchObject({
_tag: "PreviewAutomationControlInterruptedError", name: "PreviewAutomationControlInterruptedError",
operation: "click",
tabId: "tab_1",
webContentsId: 42,
});
expect(error).toBeInstanceOf(Error);
if (error instanceof Error) {
expect(error.name).toBe("PreviewAutomationControlInterruptedError");
}
expect("cause" in error).toBe(false);
}),
),
);
effectIt.effect("derives evaluation detail kind and length from the same non-empty source", () =>
withManager((manager) =>
Effect.gen(function* () {
const text = "ReferenceError: fallbackDetail is not defined";
const exceptionDetails = {
text,
exception: { description: "" },
};
const sendCommand = vi.fn(async (method: string) =>
method === "Runtime.evaluate" ? { exceptionDetails } : undefined,
);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const exit = yield* Effect.exit(
manager.automationEvaluate("tab_1", { expression: "fallbackDetail" }),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewAutomationEvaluationError",
detailKind: "exception-text",
detailLength: text.length,
cause: exceptionDetails,
}); });
}), }),
), ),
); );
}); });
describe("PreviewOperationError", () => {
it("keeps timeline detail separate from its structured message", () => {
const cause = new Error("CDP command failed with an invalid node id");
const error = new PreviewManager.PreviewOperationError({
operation: "click.DOM.resolveNode",
tabId: "tab_1",
webContentsId: 42,
cause,
});
expect(error.message).not.toContain(cause.message);
expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
});
});
describe("Preview automation diagnostics", () => {
it("keeps browser exception detail out of structural diagnostics", () => {
const secret = "unrelated-browser-payload-secret";
const detail = "ReferenceError: missingValue is not defined";
const cause = {
text: "Uncaught Error",
exception: { description: detail },
unsafePayload: secret,
};
const error = new PreviewManager.PreviewAutomationEvaluationError({
tabId: "tab_1",
detailKind: "exception-description",
detailLength: detail.length,
cause,
});
const encoded = encodePreviewManagerError(error);
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
readonly cause?: unknown;
};
expect(error.cause).toBe(cause);
expect(encodedCause).toStrictEqual(cause);
expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
expect(error.message).not.toContain(secret);
expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
expect("detail" in error).toBe(false);
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
secret,
);
});
it("retains bounded selector diagnostics without exposing selector or reason text", () => {
const selector = "role=button[name='selector-secret']";
const reason = "Unexpected token near reason-secret";
const cause = { invalidSelector: true as const, message: reason };
const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
operation: "click",
tabId: "tab_1",
selectorKind: "locator",
selectorLength: selector.length,
reasonLength: reason.length,
cause,
});
const encoded = encodePreviewManagerError(error);
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
readonly cause?: unknown;
};
expect(error.cause).toBe(cause);
expect(encodedCause).toStrictEqual(cause);
expect(error).toMatchObject({
selectorKind: "locator",
selectorLength: selector.length,
reasonLength: reason.length,
});
expect(error.detail).toEqual({
selectorKind: "locator",
selectorLength: selector.length,
});
expect(error.message).not.toContain("secret");
expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
expect("selector" in error).toBe(false);
expect("reason" in error).toBe(false);
expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
reason,
);
});
it("does not retain a missing target locator", () => {
const selector = "[data-token='target-secret']";
const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
operation: "scroll",
tabId: "tab_1",
selectorKind: "selector",
selectorLength: selector.length,
});
expect(error.message).not.toContain(selector);
expect(JSON.stringify(error)).not.toContain(selector);
expect("locator" in error).toBe(false);
});
});
File diff suppressed because it is too large. Load diff
@@ -3,14 +3,10 @@ import * as Effect from "effect/Effect";
import { describe, expect } from "vite-plus/test"; import { describe, expect } from "vite-plus/test";
import { import {
extractPlaywrightInjectedRuntimeSource,
playwrightInjectedRuntimeInstallExpression, playwrightInjectedRuntimeInstallExpression,
playwrightInjectedRuntimeSource, playwrightInjectedRuntimeSource,
} from "./PlaywrightInjectedRuntime.ts"; } from "./PlaywrightInjectedRuntime.ts";
const bundleWithSourceLiteral = (literal: string): string =>
`const source3 = ${literal};\n }\n});`;
describe("playwright injected runtime", () => { describe("playwright injected runtime", () => {
effectIt.effect("extracts the pinned runtime from playwright-core", () => effectIt.effect("extracts the pinned runtime from playwright-core", () =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -27,54 +23,4 @@ describe("playwright injected runtime", () => {
expect(expression).toContain('testIdAttributeName":"data-testid'); expect(expression).toContain('testIdAttributeName":"data-testid');
}), }),
); );
effectIt.effect("reports a missing source marker without an artificial cause", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource("const source = 'missing';", "/tmp/coreBundle.js"),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceMarkerNotFoundError",
bundlePath: "/tmp/coreBundle.js",
marker: "source3 = ",
});
expect("cause" in error).toBe(false);
}),
);
effectIt.effect("keeps source validation metadata cause-free", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource(
bundleWithSourceLiteral('"short"'),
"/tmp/coreBundle.js",
),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceValidationError",
bundlePath: "/tmp/coreBundle.js",
actualType: "string",
actualLength: 5,
minimumLength: 100_000,
});
expect("cause" in error).toBe(false);
}),
);
effectIt.effect("preserves the source evaluation cause", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource(bundleWithSourceLiteral("("), "/tmp/coreBundle.js"),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceEvaluationError",
bundlePath: "/tmp/coreBundle.js",
timeoutMs: 1_000,
cause: expect.objectContaining({ name: "SyntaxError" }),
});
}),
);
}); });
@@ -1,183 +1,68 @@
// @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection. // @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection.
import * as NodeFSP from "node:fs/promises"; import { readFile } from "node:fs/promises";
import * as NodeModule from "node:module"; import { createRequire } from "node:module";
import * as NodePath from "node:path"; import { dirname, join } from "node:path";
import * as NodeVM from "node:vm"; import { runInNewContext } from "node:vm";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema"; 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); const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
const PLAYWRIGHT_SOURCE_MINIMUM_LENGTH = 100_000;
const PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS = 1_000;
const PLAYWRIGHT_SDK_LANGUAGE = "javascript";
const PLAYWRIGHT_BROWSER_NAME = "chromium";
export class PlaywrightPackageResolveError extends Schema.TaggedErrorClass<PlaywrightPackageResolveError>()( export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
"PlaywrightPackageResolveError", "PlaywrightInjectedRuntimeError",
{ )<{
specifier: Schema.String, readonly operation: string;
cause: Schema.Defect(), readonly cause: unknown;
}, }> {
) { override get message() {
override get message(): string { return `Playwright injected runtime operation failed: ${this.operation}`;
return `Failed to resolve Playwright package: ${this.specifier}`;
} }
} }
export class PlaywrightCoreBundleReadError extends Schema.TaggedErrorClass<PlaywrightCoreBundleReadError>()( const fail = (operation: string, cause: unknown) =>
"PlaywrightCoreBundleReadError", new PlaywrightInjectedRuntimeError({ operation, cause });
{
bundlePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read Playwright core bundle: ${this.bundlePath}`;
}
}
export class PlaywrightSourceMarkerNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceMarkerNotFoundError>()(
"PlaywrightSourceMarkerNotFoundError",
{
bundlePath: Schema.String,
marker: Schema.String,
},
) {
override get message(): string {
return `Playwright injected runtime marker ${JSON.stringify(this.marker)} was not found in ${this.bundlePath}`;
}
}
export class PlaywrightSourceTerminatorNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceTerminatorNotFoundError>()(
"PlaywrightSourceTerminatorNotFoundError",
{
bundlePath: Schema.String,
terminator: Schema.String,
},
) {
override get message(): string {
return `Playwright injected runtime terminator ${JSON.stringify(this.terminator)} was not found in ${this.bundlePath}`;
}
}
export class PlaywrightSourceEvaluationError extends Schema.TaggedErrorClass<PlaywrightSourceEvaluationError>()(
"PlaywrightSourceEvaluationError",
{
bundlePath: Schema.String,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to evaluate the Playwright injected runtime literal from ${this.bundlePath} within ${this.timeoutMs}ms`;
}
}
export class PlaywrightSourceValidationError extends Schema.TaggedErrorClass<PlaywrightSourceValidationError>()(
"PlaywrightSourceValidationError",
{
bundlePath: Schema.String,
actualType: Schema.String,
actualLength: Schema.NullOr(Schema.Number),
minimumLength: Schema.Number,
},
) {
override get message(): string {
const actual =
this.actualLength === null
? this.actualType
: `${this.actualType} with ${this.actualLength} characters`;
return `Playwright injected runtime from ${this.bundlePath} was ${actual}; expected a string with at least ${this.minimumLength} characters`;
}
}
export class PlaywrightOptionsEncodeError extends Schema.TaggedErrorClass<PlaywrightOptionsEncodeError>()(
"PlaywrightOptionsEncodeError",
{
sdkLanguage: Schema.String,
browserName: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode ${this.browserName} Playwright injected runtime options for ${this.sdkLanguage}`;
}
}
export const PlaywrightInjectedRuntimeError = Schema.Union([
PlaywrightPackageResolveError,
PlaywrightCoreBundleReadError,
PlaywrightSourceMarkerNotFoundError,
PlaywrightSourceTerminatorNotFoundError,
PlaywrightSourceEvaluationError,
PlaywrightSourceValidationError,
PlaywrightOptionsEncodeError,
]);
export type PlaywrightInjectedRuntimeError = typeof PlaywrightInjectedRuntimeError.Type;
export const extractPlaywrightInjectedRuntimeSource = Effect.fn(
"PlaywrightInjectedRuntime.extractSource",
)(function* (coreBundle: string, bundlePath: string) {
const start = coreBundle.indexOf(PLAYWRIGHT_SOURCE_MARKER);
if (start < 0) {
return yield* new PlaywrightSourceMarkerNotFoundError({
bundlePath,
marker: PLAYWRIGHT_SOURCE_MARKER,
});
}
const literalStart = start + PLAYWRIGHT_SOURCE_MARKER.length;
const literalEnd = coreBundle.indexOf(PLAYWRIGHT_SOURCE_TERMINATOR, literalStart);
if (literalEnd < 0) {
return yield* new PlaywrightSourceTerminatorNotFoundError({
bundlePath,
terminator: PLAYWRIGHT_SOURCE_TERMINATOR,
});
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () =>
NodeVM.runInNewContext(literal, Object.create(null), {
timeout: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
}),
catch: (cause) =>
new PlaywrightSourceEvaluationError({
bundlePath,
timeoutMs: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
cause,
}),
});
if (typeof source !== "string" || source.length < PLAYWRIGHT_SOURCE_MINIMUM_LENGTH) {
return yield* new PlaywrightSourceValidationError({
bundlePath,
actualType: typeof source,
actualLength: typeof source === "string" ? source.length : null,
minimumLength: PLAYWRIGHT_SOURCE_MINIMUM_LENGTH,
});
}
return source;
});
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")( export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
function* () { function* () {
const packageJsonPath = yield* Effect.try({ const packageJsonPath = yield* Effect.try({
try: () => require.resolve(PLAYWRIGHT_PACKAGE_SPECIFIER), try: () => require.resolve("playwright-core/package.json"),
catch: (cause) => catch: (cause) => fail("resolvePackage", cause),
new PlaywrightPackageResolveError({
specifier: PLAYWRIGHT_PACKAGE_SPECIFIER,
cause,
}),
}); });
const bundlePath = NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js");
const coreBundle = yield* Effect.tryPromise({ const coreBundle = yield* Effect.tryPromise({
try: () => NodeFSP.readFile(bundlePath, "utf8"), try: () => readFile(join(dirname(packageJsonPath), "lib/coreBundle.js"), "utf8"),
catch: (cause) => new PlaywrightCoreBundleReadError({ bundlePath, cause }), catch: (cause) => fail("readCoreBundle", cause),
}); });
return yield* extractPlaywrightInjectedRuntimeSource(coreBundle, bundlePath); const marker = "source3 = ";
const start = coreBundle.indexOf(marker);
if (start < 0) {
return yield* fail(
"findSourceMarker",
new Error("Playwright injected runtime marker was not found."),
);
}
const literalStart = start + marker.length;
const literalEnd = coreBundle.indexOf(";\n }\n});", literalStart);
if (literalEnd < 0) {
return yield* fail(
"findSourceTerminator",
new Error("Playwright injected runtime terminator was not found."),
);
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () => runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
catch: (cause) => fail("evaluateSourceLiteral", cause),
});
if (typeof source !== "string" || source.length < 100_000) {
return yield* fail(
"validateSource",
new Error("Playwright injected runtime extraction returned invalid source."),
);
}
return source;
}, },
); );
@@ -187,23 +72,14 @@ export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
const source = yield* playwrightInjectedRuntimeSource(); const source = yield* playwrightInjectedRuntimeSource();
const options = yield* encodeUnknownJson({ const options = yield* encodeUnknownJson({
isUnderTest: false, isUnderTest: false,
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE, sdkLanguage: "javascript",
testIdAttributeName: "data-testid", testIdAttributeName: "data-testid",
stableRafCount: 1, stableRafCount: 1,
browserName: PLAYWRIGHT_BROWSER_NAME, browserName: "chromium",
shouldPrependErrorPrefix: false, shouldPrependErrorPrefix: false,
isUtilityWorld: false, isUtilityWorld: false,
customEngines: [], customEngines: [],
}).pipe( }).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
Effect.mapError(
(cause) =>
new PlaywrightOptionsEncodeError({
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
browserName: PLAYWRIGHT_BROWSER_NAME,
cause,
}),
),
);
return `(() => { return `(() => {
if (globalThis.__t3PlaywrightInjected) return true; if (globalThis.__t3PlaywrightInjected) return true;
const module = { exports: {} }; const module = { exports: {} };
@@ -1,97 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
describe("preview keyboard packets", () => {
it("includes the Chromium virtual key code and Enter text", () => {
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
keyDown: {
type: "keyDown",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
text: "\r",
unmodifiedText: "\r",
},
keyUp: {
type: "keyUp",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
},
signal: { kind: "key", key: "Enter", code: "Enter" },
});
});
it("dispatches printable keys as text key-down events", () => {
const sequence = makePreviewAutomationKeySequence({ key: "z" });
expect(sequence.keyDown).toMatchObject({
type: "keyDown",
key: "z",
code: "KeyZ",
windowsVirtualKeyCode: 90,
text: "z",
});
expect(sequence.keyUp).not.toHaveProperty("text");
});
it("suppresses text and uses raw key-down for shortcuts", () => {
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
).toEqual({
type: "rawKeyDown",
key: "a",
code: "KeyA",
modifiers: 4,
windowsVirtualKeyCode: 65,
location: 0,
isKeypad: false,
commands: ["selectAll"],
});
});
it("maps common macOS editing shortcuts without changing other platforms", () => {
expect(
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
.keyDown.commands,
).toEqual(["redo"]);
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
).not.toHaveProperty("commands");
});
it("resolves shifted printable keys to their browser values", () => {
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
expect(sequence.keyDown).toMatchObject({
key: "!",
code: "Digit1",
modifiers: 8,
windowsVirtualKeyCode: 49,
text: "!",
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
it("keeps shifted key values while suppressing text for modified chords", () => {
const sequence = makePreviewAutomationKeySequence({
key: "1",
modifiers: ["Control", "Shift"],
});
expect(sequence.keyDown).toEqual({
type: "rawKeyDown",
key: "!",
code: "Digit1",
modifiers: 10,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
});
-203
View File
@@ -1,203 +0,0 @@
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
interface KeyDefinition {
readonly code: string;
readonly key: string;
readonly keyCode: number;
readonly text?: string;
readonly location?: number;
readonly shiftedKey?: string;
}
export interface PreviewAutomationKeyEvent {
readonly [key: string]: unknown;
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
readonly key: string;
readonly code: string;
readonly modifiers: number;
readonly windowsVirtualKeyCode: number;
readonly location: number;
readonly isKeypad: boolean;
readonly text?: string;
readonly unmodifiedText?: string;
readonly commands?: ReadonlyArray<string>;
}
export interface PreviewAutomationKeySequence {
readonly keyDown: PreviewAutomationKeyEvent;
readonly keyUp: PreviewAutomationKeyEvent;
readonly signal: {
readonly kind: "key";
readonly key: string;
readonly code: string;
};
}
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
End: { code: "End", key: "End", keyCode: 35 },
Home: { code: "Home", key: "Home", keyCode: 36 },
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
};
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
];
/**
* Chromium does not infer macOS editing commands from synthetic Meta chords.
* Keep the common browser editing/navigation shortcuts explicit so dispatched
* key events behave like their physical-key equivalents.
*/
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
"Meta+Backspace": "deleteToBeginningOfLine",
"Meta+ArrowUp": "moveToBeginningOfDocument",
"Meta+ArrowDown": "moveToEndOfDocument",
"Meta+ArrowLeft": "moveToLeftEndOfLine",
"Meta+ArrowRight": "moveToRightEndOfLine",
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
"Meta+KeyA": "selectAll",
"Meta+KeyC": "copy",
"Meta+KeyX": "cut",
"Meta+KeyV": "paste",
"Meta+KeyZ": "undo",
"Shift+Meta+KeyZ": "redo",
};
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
const macEditingCommands = (
code: string,
modifiers: PreviewAutomationPressInput["modifiers"],
): ReadonlyArray<string> => {
const shortcut = [
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
code,
].join("+");
const command = MAC_EDITING_COMMANDS[shortcut];
return command ? [command] : [];
};
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
(modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
}
}, 0);
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
const named = NAMED_KEYS[input.key];
if (named) return named;
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
if (functionKey) {
const number = Number(functionKey[1]);
return { code: input.key, key: input.key, keyCode: 111 + number };
}
if (/^[a-z]$/i.test(input.key)) {
const upper = input.key.toUpperCase();
const shifted = input.modifiers?.includes("Shift") ?? false;
const key = shifted || input.key === upper ? upper : input.key;
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
}
const printable = PRINTABLE_KEYS.find(
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
);
if (printable) {
const shifted = input.modifiers?.includes("Shift") ?? false;
const key =
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
? printable.shiftedKey
: printable.key;
return { ...printable, key, text: key };
}
return {
code: input.key.length > 1 ? input.key : "",
key: input.key,
keyCode: 0,
...(input.key.length === 1 ? { text: input.key } : {}),
};
}
/**
* Build Chromium CDP key packets using the same required fields and down-event
* choice as Playwright's pinned Chromium keyboard implementation.
*/
export function makePreviewAutomationKeySequence(
input: PreviewAutomationPressInput,
options?: { readonly isMac?: boolean },
): PreviewAutomationKeySequence {
const definition = resolveKeyDefinition(input);
const modifiers = modifierMask(input.modifiers);
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
const text = suppressText ? "" : (definition.text ?? "");
const location = definition.location ?? 0;
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
const shared = {
key: definition.key,
code: definition.code,
modifiers,
windowsVirtualKeyCode: definition.keyCode,
location,
isKeypad: location === 3,
};
return {
keyDown: {
type: text ? "keyDown" : "rawKeyDown",
...shared,
...(text ? { text, unmodifiedText: text } : {}),
...(commands.length > 0 ? { commands } : {}),
},
keyUp: { type: "keyUp", ...shared },
signal: { kind: "key", key: definition.key, code: definition.code },
};
}
@@ -8,6 +8,11 @@ import * as Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.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"; import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({ const DesktopSettingsPatch = Schema.Struct({
@@ -77,23 +82,20 @@ describe("DesktopSettings", () => {
withSettings( withSettings(
Effect.gen(function* () { Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings; const settings = yield* DesktopAppSettings.DesktopAppSettings;
assert.deepEqual(yield* settings.load, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS); assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
assert.deepEqual(yield* settings.get, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS); assert.deepEqual(yield* settings.get, DEFAULT_DESKTOP_SETTINGS);
}), }),
), ),
); );
it("defaults packaged nightly builds to the nightly update channel", () => { it("defaults packaged nightly builds to the nightly update channel", () => {
assert.deepEqual( assert.deepEqual(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"), {
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"), serverExposureMode: "local-only",
{ tailscaleServeEnabled: false,
serverExposureMode: "local-only", tailscaleServePort: 443,
tailscaleServeEnabled: false, updateChannel: "nightly",
tailscaleServePort: 443, updateChannelConfiguredByUser: false,
updateChannel: "nightly", } satisfies DesktopSettingsValue);
updateChannelConfiguredByUser: false,
} satisfies DesktopAppSettings.DesktopSettings,
);
}); });
it.effect("loads persisted settings and applies semantic updates", () => it.effect("loads persisted settings and applies semantic updates", () =>
@@ -114,7 +116,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443, tailscaleServePort: 8443,
updateChannel: "latest", updateChannel: "latest",
updateChannelConfiguredByUser: true, updateChannelConfiguredByUser: true,
} satisfies DesktopAppSettings.DesktopSettings); } satisfies DesktopSettingsValue);
const exposure = yield* settings.setServerExposureMode("local-only"); const exposure = yield* settings.setServerExposureMode("local-only");
assert.isTrue(exposure.changed); 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", () => it.effect("does not persist no-op semantic updates", () =>
withSettings( withSettings(
Effect.gen(function* () { Effect.gen(function* () {
@@ -186,7 +167,7 @@ describe("DesktopSettings", () => {
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.desktopSettingsPath, "{not-json"); 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, tailscaleServePort: 8443,
updateChannel: "latest", updateChannel: "latest",
updateChannelConfiguredByUser: false, updateChannelConfiguredByUser: false,
} satisfies DesktopAppSettings.DesktopSettings); } satisfies DesktopSettingsValue);
}), }),
), ),
); );
@@ -253,7 +234,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443, tailscaleServePort: 443,
updateChannel: "nightly", updateChannel: "nightly",
updateChannelConfiguredByUser: false, updateChannelConfiguredByUser: false,
} satisfies DesktopAppSettings.DesktopSettings); } satisfies DesktopSettingsValue);
}), }),
{ appVersion: "0.0.17-nightly.20260415.1" }, { appVersion: "0.0.17-nightly.20260415.1" },
), ),
@@ -275,7 +256,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443, tailscaleServePort: 443,
updateChannel: "latest", updateChannel: "latest",
updateChannelConfiguredByUser: true, updateChannelConfiguredByUser: true,
} satisfies DesktopAppSettings.DesktopSettings); } satisfies DesktopSettingsValue);
}), }),
{ appVersion: "0.0.17-nightly.20260415.1" }, { appVersion: "0.0.17-nightly.20260415.1" },
), ),
@@ -296,7 +277,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443, tailscaleServePort: 443,
updateChannel: "latest", updateChannel: "latest",
updateChannelConfiguredByUser: false, updateChannelConfiguredByUser: false,
} satisfies DesktopAppSettings.DesktopSettings); } satisfies DesktopSettingsValue);
}), }),
), ),
); );
+81 -133
View File
@@ -7,11 +7,13 @@ import {
import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto"; import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Path from "effect/Path"; import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef"; import * as SynchronizedRef from "effect/SynchronizedRef";
@@ -61,44 +63,32 @@ const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSet
changed, changed,
}); });
const DesktopSettingsWriteOperation = Schema.Literals([ export class DesktopSettingsWriteError extends Data.TaggedError("DesktopSettingsWriteError")<{
"create-temporary-file-name", readonly cause: PlatformError.PlatformError | Schema.SchemaError;
"encode-document", }> {
"create-directory", override get message() {
"write-temporary-file", return `Failed to write desktop settings: ${this.cause.message}`;
"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 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< export class DesktopAppSettings extends Context.Service<
DesktopAppSettings, DesktopAppSettings,
{ 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>;
}
>()("@t3tools/desktop/settings/DesktopAppSettings") {} >()("@t3tools/desktop/settings/DesktopAppSettings") {}
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings { export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
@@ -233,119 +223,77 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
readonly settings: DesktopSettings; readonly settings: DesktopSettings;
readonly defaultSettings: DesktopSettings; readonly defaultSettings: DesktopSettings;
readonly suffix: string; readonly suffix: string;
}): Effect.fn.Return<void, DesktopSettingsWriteError> { }): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath); const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`; const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson( const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings), toDesktopSettingsDocument(input.settings, input.defaultSettings),
).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "encode-document",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "replace-settings-file",
path: input.settingsPath,
cause,
}),
),
); );
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* () { export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment; DesktopAppSettings,
const fileSystem = yield* FileSystem.FileSystem; Effect.gen(function* () {
const path = yield* Path.Path; const environment = yield* DesktopEnvironment.DesktopEnvironment;
const crypto = yield* Crypto.Crypto; const fileSystem = yield* FileSystem.FileSystem;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings); const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
const persist = ( const persist = (
update: (settings: DesktopSettings) => DesktopSettings, update: (settings: DesktopSettings) => DesktopSettings,
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> => ): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
SynchronizedRef.modifyEffect(settingsRef, (settings) => { SynchronizedRef.modifyEffect(settingsRef, (settings) => {
const nextSettings = update(settings); const nextSettings = update(settings);
if (nextSettings === settings) { if (nextSettings === settings) {
return Effect.succeed([settingsChange(settings, false), settings] as const); return Effect.succeed([settingsChange(settings, false), settings] as const);
} }
return crypto.randomUUIDv4.pipe( return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")), Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError( Effect.flatMap((suffix) =>
(cause) => writeSettings({
new DesktopSettingsWriteError({ fileSystem,
operation: "create-temporary-file-name", path,
path: environment.desktopSettingsPath, settingsPath: environment.desktopSettingsPath,
cause, 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) => setTailscaleServe: (input) =>
writeSettings({ persist((settings) => setTailscaleServe(settings, input)).pipe(
fileSystem, Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
path, ),
settingsPath: environment.desktopSettingsPath, setUpdateChannel: (channel) =>
settings: nextSettings, persist((settings) => setUpdateChannel(settings, channel)).pipe(
defaultSettings: environment.defaultDesktopSettings, Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
suffix,
}),
), ),
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) => export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SETTINGS) =>
Layer.effect( Layer.effect(
@@ -1,129 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
interface LogRecord {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
const baseDir = "/virtual-home";
function makeLayer(fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopClientSettings.layer.pipe(
Layer.provideMerge(Layer.mergeAll(environmentLayer, NodeServices.layer, fileSystemLayer)),
);
}
const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
const records: Array<LogRecord> = [];
const logger = Logger.make(({ fiber, message }) => {
records.push({
message,
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
});
});
return Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
return {
result: yield* settings.get,
settingsPath: environment.clientSettingsPath,
records,
};
}).pipe(
Effect.provide(
Layer.mergeAll(
makeLayer(fileSystemLayer),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
};
describe("DesktopClientSettings diagnostics", () => {
it.effect("treats a missing settings file as expected without warning", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(FileSystem.layerNoop({}));
assert.isTrue(Option.isNone(result.result));
assert.deepEqual(result.records, []);
}),
);
it.effect("logs non-missing filesystem failures with the settings path", () => {
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
});
return Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
assert.deepEqual(result.records[0]?.message, [
"Could not read desktop client settings.",
permissionError,
]);
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
});
});
it.effect("logs malformed settings documents with the settings path", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.succeed("{not-json"),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
const message = result.records[0]?.message;
if (!Array.isArray(message)) {
return assert.fail("expected structured warning arguments");
}
assert.equal(message[0], "Could not decode desktop client settings.");
const schemaError = message[1];
if (schemaError === null || typeof schemaError !== "object") {
return assert.fail("expected the schema error in the warning");
}
assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError");
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
}),
);
});
@@ -5,7 +5,6 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts";
@@ -18,6 +17,7 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false, confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [], dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true, diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [], favorites: [],
providerModelPreferences: {}, providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path", sidebarProjectGroupingMode: "repository_path",
@@ -28,13 +28,13 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at", sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6, sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour", timestampFormat: "24-hour",
wordWrap: true,
}; };
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema)); const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
const decodeRecordJson = Schema.decodeEffect( const decodeRecordJson = Schema.decodeEffect(
Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
); );
function makeLayer(baseDir: string) { function makeLayer(baseDir: string) {
const environmentLayer = DesktopEnvironment.layer({ const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src", dirname: "/repo/apps/desktop/src",
@@ -106,29 +106,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.instanceOf(error.cause, PlatformError.PlatformError);
assert.isString(error.cause.stack);
assert.equal(
error.message,
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
);
assert.notInclude(error.message, error.cause.message);
}),
),
);
it.effect("loads lenient direct client settings documents", () => it.effect("loads lenient direct client settings documents", () =>
withClientSettings( withClientSettings(
Effect.gen(function* () { Effect.gen(function* () {
@@ -2,11 +2,13 @@ import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto"; import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Path from "effect/Path"; import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
@@ -25,41 +27,28 @@ const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> => const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
decodeLegacyClientSettingsDocumentJson(raw).pipe( decodeLegacyClientSettingsDocumentJson(raw).pipe(
Effect.map((document) => document.settings), Effect.map((document) => document.settings),
Effect.catchTags({ Effect.catch(() => decodeClientSettingsJsonValue(raw)),
SchemaError: () => decodeClientSettingsJsonValue(raw),
}),
); );
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson); const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
const DesktopClientSettingsWriteOperation = Schema.Literals([ export class DesktopClientSettingsWriteError extends Data.TaggedError(
"create-temporary-file-name",
"encode-document",
"create-directory",
"write-temporary-file",
"replace-settings-file",
]);
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
"DesktopClientSettingsWriteError", "DesktopClientSettingsWriteError",
{ )<{
operation: DesktopClientSettingsWriteOperation, readonly cause: PlatformError.PlatformError | Schema.SchemaError;
path: Schema.String, }> {
cause: Schema.Defect(), override get message() {
}, return `Failed to write desktop client settings: ${this.cause.message}`;
) {
override get message(): string {
return `Desktop client settings write failed during ${this.operation} at ${this.path}.`;
} }
} }
export interface DesktopClientSettingsShape {
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
readonly set: (settings: ClientSettings) => Effect.Effect<void, DesktopClientSettingsWriteError>;
}
export class DesktopClientSettings extends Context.Service< export class DesktopClientSettings extends Context.Service<
DesktopClientSettings, DesktopClientSettings,
{ DesktopClientSettingsShape
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
readonly set: (
settings: ClientSettings,
) => Effect.Effect<void, DesktopClientSettingsWriteError>;
}
>()("@t3tools/desktop/settings/DesktopClientSettings") {} >()("@t3tools/desktop/settings/DesktopClientSettings") {}
const readClientSettings = ( const readClientSettings = (
@@ -67,29 +56,14 @@ const readClientSettings = (
settingsPath: string, settingsPath: string,
): Effect.Effect<Option.Option<ClientSettings>> => ): Effect.Effect<Option.Option<ClientSettings>> =>
fileSystem.readFileString(settingsPath).pipe( fileSystem.readFileString(settingsPath).pipe(
Effect.map(Option.some), Effect.option,
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none<string>())
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<string>()),
),
}),
Effect.flatMap( Effect.flatMap(
Option.match({ Option.match({
onNone: () => Effect.succeed(Option.none<ClientSettings>()), onNone: () => Effect.succeed(Option.none<ClientSettings>()),
onSome: (raw) => onSome: (raw) =>
decodeClientSettingsJson(raw).pipe( decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)), Effect.map((settings) => Option.some(settings)),
Effect.catchTags({ Effect.orElseSucceed(() => Option.none<ClientSettings>()),
SchemaError: (cause) =>
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<ClientSettings>()),
),
}),
), ),
}), }),
), ),
@@ -101,87 +75,45 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
readonly settingsPath: string; readonly settingsPath: string;
readonly settings: ClientSettings; readonly settings: ClientSettings;
readonly suffix: string; readonly suffix: string;
}): Effect.fn.Return<void, DesktopClientSettingsWriteError> { }): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath); const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`; const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeClientSettingsJson(input.settings).pipe( const encoded = yield* encodeClientSettingsJson(input.settings);
Effect.mapError( yield* input.fileSystem.makeDirectory(directory, { recursive: true });
(cause) => yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
new DesktopClientSettingsWriteError({ yield* input.fileSystem.rename(tempPath, input.settingsPath);
operation: "encode-document",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "replace-settings-file",
path: input.settingsPath,
cause,
}),
),
);
}); });
export const make = Effect.gen(function* () { export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment; DesktopClientSettings,
const fileSystem = yield* FileSystem.FileSystem; Effect.gen(function* () {
const path = yield* Path.Path; const environment = yield* DesktopEnvironment.DesktopEnvironment;
const crypto = yield* Crypto.Crypto; const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
return DesktopClientSettings.of({ return DesktopClientSettings.of({
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe( get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
Effect.withSpan("desktop.clientSettings.get"), Effect.withSpan("desktop.clientSettings.get"),
),
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "create-temporary-file-name",
path: environment.clientSettingsPath,
cause,
}),
),
Effect.flatMap((suffix) =>
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
suffix,
}),
),
Effect.withSpan("desktop.clientSettings.set"),
), ),
}); set: (settings) =>
}); crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
export const layer = Layer.effect(DesktopClientSettings, make); 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()) => export const layerTest = (initialSettings: Option.Option<ClientSettings> = Option.none()) =>
Layer.effect( Layer.effect(
@@ -5,7 +5,6 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts";
@@ -35,15 +34,10 @@ const SavedEnvironmentRegistryDocumentProbe = Schema.Struct({
version: Schema.Number, version: Schema.Number,
records: Schema.Array(Schema.Unknown), records: Schema.Array(Schema.Unknown),
}); });
const SavedEnvironmentRegistryDocumentProbeJson = Schema.fromJsonString(
SavedEnvironmentRegistryDocumentProbe,
);
const decodeSavedEnvironmentRegistryDocumentProbe = Schema.decodeEffect( const decodeSavedEnvironmentRegistryDocumentProbe = Schema.decodeEffect(
SavedEnvironmentRegistryDocumentProbeJson, Schema.fromJsonString(SavedEnvironmentRegistryDocumentProbe),
);
const encodeSavedEnvironmentRegistryDocumentProbe = Schema.encodeEffect(
SavedEnvironmentRegistryDocumentProbeJson,
); );
function makeSafeStorageLayer(input: { function makeSafeStorageLayer(input: {
readonly available: boolean; readonly available: boolean;
readonly availabilityError?: unknown; readonly availabilityError?: unknown;
@@ -86,7 +80,7 @@ function makeSafeStorageLayer(input: {
} }
return Effect.succeed(decoded.slice("enc:".length)); return Effect.succeed(decoded.slice("enc:".length));
}, },
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]); } satisfies ElectronSafeStorage.ElectronSafeStorageShape);
} }
function makeLayer( function makeLayer(
@@ -97,7 +91,6 @@ function makeLayer(
readonly encryptError?: unknown; readonly encryptError?: unknown;
readonly decryptError?: unknown; readonly decryptError?: unknown;
}, },
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
) { ) {
const environmentLayer = DesktopEnvironment.layer({ const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src", dirname: "/repo/apps/desktop/src",
@@ -115,20 +108,18 @@ function makeLayer(
), ),
); );
const safeStorageLayer = makeSafeStorageLayer({ return DesktopSavedEnvironments.layer.pipe(
available: options?.availableSecretStorage ?? true, Layer.provideMerge(environmentLayer),
availabilityError: options?.availabilityError, Layer.provideMerge(
encryptError: options?.encryptError, makeSafeStorageLayer({
decryptError: options?.decryptError, available: options?.availableSecretStorage ?? true,
}); availabilityError: options?.availabilityError,
const dependencies = Layer.mergeAll( encryptError: options?.encryptError,
environmentLayer, decryptError: options?.decryptError,
safeStorageLayer, }),
NodeServices.layer, ),
fileSystemLayer, Layer.provideMerge(NodeServices.layer),
); );
return DesktopSavedEnvironments.layer.pipe(Layer.provideMerge(dependencies));
} }
const withSavedEnvironments = <A, E, R>( 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", () => it.effect("returns false when writing secrets while encryption is unavailable", () =>
withSavedEnvironments( withSavedEnvironments(
Effect.gen(function* () { Effect.gen(function* () {
@@ -271,11 +232,10 @@ describe("DesktopSavedEnvironments", () => {
), ),
); );
it.effect("adds saved-environment context to safe storage availability failures", () => { it.effect("surfaces typed safe storage availability failures", () => {
const cause = new Error("safe storage unavailable"); const cause = new Error("safe storage unavailable");
return withSavedEnvironments( return withSavedEnvironments(
Effect.gen(function* () { Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]); yield* savedEnvironments.setRegistry([savedRegistryRecord]);
@@ -286,22 +246,8 @@ describe("DesktopSavedEnvironments", () => {
}) })
.pipe(Effect.flip); .pipe(Effect.flip);
assert.instanceOf( assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
error, assert.equal(error.cause, cause);
DesktopSavedEnvironments.DesktopSavedEnvironmentSecretProtectionError,
);
assert.equal(error.operation, "check-encryption-availability");
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
const availabilityError =
error.cause as ElectronSafeStorage.ElectronSafeStorageAvailabilityError;
assert.strictEqual(availabilityError.cause, cause);
assert.equal(
error.message,
`Desktop saved-environment secret protection failed during check-encryption-availability for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
);
assert.notEqual(error.message, availabilityError.message);
}), }),
{ availabilityError: cause }, { availabilityError: cause },
); );
@@ -326,26 +272,6 @@ describe("DesktopSavedEnvironments", () => {
), ),
); );
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
});
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
}),
),
);
it.effect("treats empty saved environment documents as empty", () => it.effect("treats empty saved environment documents as empty", () =>
withSavedEnvironments( withSavedEnvironments(
Effect.gen(function* () { Effect.gen(function* () {
@@ -363,7 +289,7 @@ describe("DesktopSavedEnvironments", () => {
), ),
); );
it.effect("surfaces malformed saved environment documents", () => it.effect("treats malformed saved environment documents as empty", () =>
withSavedEnvironments( withSavedEnvironments(
Effect.gen(function* () { Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment; const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -372,99 +298,14 @@ describe("DesktopSavedEnvironments", () => {
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json"); yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip); assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.instanceOf( assert.isTrue(
registryError, Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
);
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,
); );
}), }),
), ),
); );
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", () => it.effect("returns false when writing a secret without metadata", () =>
withSavedEnvironments( withSavedEnvironments(
Effect.gen(function* () { Effect.gen(function* () {
@@ -2,12 +2,14 @@ import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/co
import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto"; import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding"; import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Path from "effect/Path"; import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema"; import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref"; import * as Ref from "effect/Ref";
@@ -70,126 +72,56 @@ const encodeSavedEnvironmentRegistryDocumentJson = Schema.encodeEffect(
SavedEnvironmentRegistryDocumentJson, SavedEnvironmentRegistryDocumentJson,
); );
const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([ export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
"create-temporary-file-name",
"encode-registry",
"create-directory",
"write-temporary-file",
"replace-registry-file",
]);
const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-secret",
"decrypt-secret",
]);
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
"DesktopSavedEnvironmentsWriteError", "DesktopSavedEnvironmentsWriteError",
{ )<{
operation: DesktopSavedEnvironmentsWriteOperation, readonly cause: PlatformError.PlatformError | Schema.SchemaError;
path: Schema.String, }> {
cause: Schema.Defect(), override get message() {
}, return `Failed to write desktop saved environments: ${this.cause.message}`;
) {
override get message(): string {
return `Desktop saved-environment write failed during ${this.operation} at ${this.path}.`;
} }
} }
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()( export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
"DesktopSavedEnvironmentsReadError",
{
registryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read desktop saved environments at ${this.registryPath}.`;
}
}
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>()(
"DesktopSavedEnvironmentSecretDecodeError", "DesktopSavedEnvironmentSecretDecodeError",
{ )<{
environmentId: Schema.String, readonly cause: Encoding.EncodingError;
registryPath: Schema.String, }> {
field: Schema.Literal("encryptedBearerToken"), override get message() {
cause: Schema.Defect(), return "Failed to decode desktop saved environment secret.";
},
) {
override get message(): string {
return `Failed to decode ${this.field} for environment ${this.environmentId} at ${this.registryPath}.`;
} }
} }
export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretProtectionError>()(
"DesktopSavedEnvironmentSecretProtectionError",
{
operation: DesktopSavedEnvironmentSecretProtectionOperation,
environmentId: Schema.String,
registryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
}
}
export type DesktopSavedEnvironmentsReadRegistryError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentsDocumentDecodeError;
export type DesktopSavedEnvironmentsMutationError =
| DesktopSavedEnvironmentsReadRegistryError
| DesktopSavedEnvironmentsWriteError;
export type DesktopSavedEnvironmentsGetSecretError = export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadRegistryError
| DesktopSavedEnvironmentSecretDecodeError | DesktopSavedEnvironmentSecretDecodeError
| DesktopSavedEnvironmentSecretProtectionError; | ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
export type DesktopSavedEnvironmentsSetSecretError = export type DesktopSavedEnvironmentsSetSecretError =
| DesktopSavedEnvironmentsMutationError | DesktopSavedEnvironmentsWriteError
| DesktopSavedEnvironmentSecretProtectionError; | ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
export interface DesktopSavedEnvironmentsShape {
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>;
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => 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< export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments, DesktopSavedEnvironments,
{ DesktopSavedEnvironmentsShape
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>;
}
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {} >()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
function toPersistedSavedEnvironmentRecord( function toPersistedSavedEnvironmentRecord(
@@ -244,31 +176,18 @@ function normalizeSavedEnvironmentRegistryDocument(
function readRegistryDocument( function readRegistryDocument(
fileSystem: FileSystem.FileSystem, fileSystem: FileSystem.FileSystem,
registryPath: string, registryPath: string,
): Effect.Effect<SavedEnvironmentRegistryDocument, DesktopSavedEnvironmentsReadRegistryError> { ): Effect.Effect<SavedEnvironmentRegistryDocument> {
return fileSystem.readFileString(registryPath).pipe( return fileSystem.readFileString(registryPath).pipe(
Effect.catch((error) => Effect.option,
error.reason._tag === "NotFound" Effect.flatMap(
? Effect.succeed<string | null>(null) Option.match({
: Effect.fail( onNone: () => Effect.succeed({ version: 1, records: [] }),
new DesktopSavedEnvironmentsReadError({ onSome: (raw) =>
registryPath, decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
cause: error,
}),
),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed({ version: 1, records: [] })
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument), Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.mapError( Effect.orElseSucceed(() => ({ version: 1, records: [] })),
(cause) =>
new DesktopSavedEnvironmentsDocumentDecodeError({
registryPath,
cause,
}),
),
), ),
}),
), ),
); );
} }
@@ -280,49 +199,13 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
readonly registryPath: string; readonly registryPath: string;
readonly document: SavedEnvironmentRegistryDocument; readonly document: SavedEnvironmentRegistryDocument;
readonly suffix: string; readonly suffix: string;
}): Effect.fn.Return<void, DesktopSavedEnvironmentsWriteError> { }): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.registryPath); const directory = input.path.dirname(input.registryPath);
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`; const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe( const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
Effect.mapError( yield* input.fileSystem.makeDirectory(directory, { recursive: true });
(cause) => yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
new DesktopSavedEnvironmentsWriteError({ yield* input.fileSystem.rename(tempPath, input.registryPath);
operation: "encode-registry",
path: input.registryPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "replace-registry-file",
path: input.registryPath,
cause,
}),
),
);
}, },
); );
@@ -348,213 +231,129 @@ function preserveExistingSecrets(
} }
function decodeSecretBytes( function decodeSecretBytes(
environmentId: string,
registryPath: string,
encoded: string, encoded: string,
): Effect.Effect<Uint8Array, DesktopSavedEnvironmentSecretDecodeError> { ): Effect.Effect<Uint8Array, DesktopSavedEnvironmentSecretDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe( return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError( Effect.mapError((cause) => new DesktopSavedEnvironmentSecretDecodeError({ cause })),
(cause) =>
new DesktopSavedEnvironmentSecretDecodeError({
environmentId,
registryPath,
field: "encryptedBearerToken",
cause,
}),
),
); );
} }
export const make = Effect.gen(function* () { export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment; DesktopSavedEnvironments,
const fileSystem = yield* FileSystem.FileSystem; Effect.gen(function* () {
const path = yield* Path.Path; const environment = yield* DesktopEnvironment.DesktopEnvironment;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage; const fileSystem = yield* FileSystem.FileSystem;
const crypto = yield* Crypto.Crypto; const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const writeDocument = (document: SavedEnvironmentRegistryDocument) => const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe( crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")), Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError( Effect.flatMap((suffix) =>
(cause) => writeRegistryDocument({
new DesktopSavedEnvironmentsWriteError({ fileSystem,
operation: "create-temporary-file-name", path,
path: environment.savedEnvironmentRegistryPath, registryPath: environment.savedEnvironmentRegistryPath,
cause, document,
suffix,
}), }),
), ),
Effect.flatMap((suffix) => Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })),
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,
); );
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}), return DesktopSavedEnvironments.of({
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")( getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
function* (environmentId) { 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,
);
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId }); yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument( const document = yield* readRegistryDocument(
fileSystem, fileSystem,
environment.savedEnvironmentRegistryPath, environment.savedEnvironmentRegistryPath,
); );
if (!document.records.some((record) => record.environmentId === environmentId)) { 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(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; return;
} }
yield* writeDocument({ yield* writeDocument({
version: document.version, 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)) {
return Option.none<string>();
}
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "check-encryption-availability",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
);
if (!encryptionAvailable) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(
environmentId,
environment.savedEnvironmentRegistryPath,
encoded.value,
);
return Option.some(
yield* safeStorage.decryptString(secretBytes).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "decrypt-secret",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
),
);
}),
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
const { environmentId, secret } = input;
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "check-encryption-availability",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
);
if (!encryptionAvailable) {
return false;
}
const encryptedBearerToken = Encoding.encodeBase64(
yield* safeStorage.encryptString(secret).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "encrypt-secret",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
),
);
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?: { export const layerTest = (input?: {
readonly records?: readonly PersistedSavedEnvironmentRecord[]; readonly records?: readonly PersistedSavedEnvironmentRecord[];
@@ -569,18 +368,6 @@ export const layerTest = (input?: {
return DesktopSavedEnvironments.of({ return DesktopSavedEnvironments.of({
getRegistry: Ref.get(recordsRef), getRegistry: Ref.get(recordsRef),
setRegistry: (records) => Ref.set(recordsRef, records), setRegistry: (records) => Ref.set(recordsRef, records),
removeEnvironment: (environmentId) =>
Ref.update(recordsRef, (records) =>
records.filter((record) => record.environmentId !== environmentId),
).pipe(
Effect.andThen(
Ref.update(secretsRef, (secrets) => {
const nextSecrets = new Map(secrets);
nextSecrets.delete(environmentId);
return nextSecrets;
}),
),
),
getSecret: (environmentId) => getSecret: (environmentId) =>
Ref.get(secretsRef).pipe( Ref.get(secretsRef).pipe(
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))), Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
@@ -1,23 +1,15 @@
import { assert, describe, it } from "@effect/vitest"; import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink"; import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream"; import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/unstable/process/ChildProcess"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts"; import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
const textEncoder = new TextEncoder(); const textEncoder = new TextEncoder();
const isDesktopShellEnvironmentCommandError = Schema.is(
DesktopShellEnvironment.DesktopShellEnvironmentCommandError,
);
function envOutput(values: Readonly<Record<string, string>>): string { function envOutput(values: Readonly<Record<string, string>>): string {
return Object.entries(values) return Object.entries(values)
.flatMap(([name, value]) => [ .flatMap(([name, value]) => [
@@ -67,21 +59,16 @@ function runShellEnvironment(input: {
readonly env: NodeJS.ProcessEnv; readonly env: NodeJS.ProcessEnv;
readonly platform: NodeJS.Platform; readonly platform: NodeJS.Platform;
readonly handler: (command: ChildProcess.Command) => string; readonly handler: (command: ChildProcess.Command) => string;
readonly failure?: PlatformError.PlatformError;
}) { }) {
const environmentLayer = Layer.succeed( const environmentLayer = Layer.succeed(
DesktopEnvironment.DesktopEnvironment, DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of({ DesktopEnvironment.DesktopEnvironment.of({
platform: input.platform, platform: input.platform,
} as DesktopEnvironment.DesktopEnvironment["Service"]), } as DesktopEnvironment.DesktopEnvironmentShape),
); );
const spawnerLayer = Layer.succeed( const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => ChildProcessSpawner.make((command) => Effect.succeed(makeProcess(input.handler(command)))),
input.failure === undefined
? Effect.succeed(makeProcess(input.handler(command)))
: Effect.fail(input.failure),
),
); );
const program = Effect.gen(function* () { const program = Effect.gen(function* () {
@@ -242,44 +229,4 @@ describe("DesktopShellEnvironment", () => {
); );
}), }),
); );
it.effect("logs command failures with safe probe context and the exact cause", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/bash",
PATH: "/usr/bin",
};
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "spawn",
pathOrDescriptor: "/bin/bash",
});
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
return runShellEnvironment({
env,
platform: "linux",
handler: () => "",
failure: cause,
}).pipe(
Effect.andThen(
Effect.sync(() => {
const errors = messages
.flatMap((message) => (Array.isArray(message) ? message : [message]))
.filter(isDesktopShellEnvironmentCommandError);
assert.lengthOf(errors, 1);
assert.equal(errors[0]?.probe, "login-shell");
assert.equal(errors[0]?.executable, "bash");
assert.equal(errors[0]?.argumentCount, 2);
assert.notProperty(errors[0] ?? {}, "args");
assert.equal(errors[0]?.cause, cause);
assert.notInclude(errors[0]?.message ?? "", cause.message);
}),
),
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
);
});
}); });
+29 -102
View File
@@ -3,9 +3,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Schema from "effect/Schema"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -21,49 +19,13 @@ interface WindowsProbeOptions {
readonly loadProfile: boolean; readonly loadProfile: boolean;
} }
const DesktopShellEnvironmentProbe = Schema.Literals([ export interface DesktopShellEnvironmentShape {
"login-shell", readonly installIntoProcess: Effect.Effect<void, never>;
"launchctl-path",
"powershell-profile",
"powershell-no-profile",
]);
type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
const desktopShellEnvironmentCommandFields = {
probe: DesktopShellEnvironmentProbe,
executable: Schema.String,
argumentCount: Schema.Number,
};
export class DesktopShellEnvironmentCommandError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandError>()(
"DesktopShellEnvironmentCommandError",
{
...desktopShellEnvironmentCommandFields,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
}
}
export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandTimeoutError>()(
"DesktopShellEnvironmentCommandTimeoutError",
{
...desktopShellEnvironmentCommandFields,
timeoutMs: Schema.Number,
},
) {
override get message(): string {
return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
}
} }
export class DesktopShellEnvironment extends Context.Service< export class DesktopShellEnvironment extends Context.Service<
DesktopShellEnvironment, DesktopShellEnvironment,
{ DesktopShellEnvironmentShape
readonly installIntoProcess: Effect.Effect<void>;
}
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {} >()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
const LOGIN_SHELL_ENV_NAMES = [ const LOGIN_SHELL_ENV_NAMES = [
@@ -166,18 +128,6 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`; const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`; const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
const logShellEnvironmentCommandError = (
error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
) =>
Effect.logWarning(error).pipe(
Effect.annotateLogs({
component: "desktop-shell-environment",
error,
}),
);
const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) => const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
names names
.map((name) => { .map((name) => {
@@ -226,14 +176,13 @@ const extractEnvironment = (output: string, names: ReadonlyArray<string>): Envir
}; };
const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: { const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
readonly probe: DesktopShellEnvironmentProbe;
readonly command: string; readonly command: string;
readonly args: ReadonlyArray<string>; readonly args: ReadonlyArray<string>;
readonly timeout: Duration.Duration; readonly timeout: Duration.Duration;
readonly shell?: boolean; readonly shell?: boolean;
}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> { }): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const output = yield* spawner return yield* spawner
.string( .string(
ChildProcess.make(input.command, input.args, { ChildProcess.make(input.command, input.args, {
shell: input.shell ?? false, shell: input.shell ?? false,
@@ -245,33 +194,10 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
}), }),
) )
.pipe( .pipe(
Effect.mapError(
(cause) =>
new DesktopShellEnvironmentCommandError({
probe: input.probe,
executable: executableName(input.command),
argumentCount: input.args.length,
cause,
}),
),
Effect.catchTags({
DesktopShellEnvironmentCommandError: (error) =>
logShellEnvironmentCommandError(error).pipe(Effect.as("")),
}),
Effect.timeoutOption(input.timeout), Effect.timeoutOption(input.timeout),
Effect.map(Option.getOrElse(() => "")),
Effect.orElseSucceed(() => ""),
); );
if (Option.isSome(output)) {
return output.value;
}
const error = new DesktopShellEnvironmentCommandTimeoutError({
probe: input.probe,
executable: executableName(input.command),
argumentCount: input.args.length,
timeoutMs: Duration.toMillis(input.timeout),
});
yield* logShellEnvironmentCommandError(error);
return "";
}); });
const readLoginShellEnvironment = ( const readLoginShellEnvironment = (
@@ -281,14 +207,16 @@ const readLoginShellEnvironment = (
names.length === 0 names.length === 0
? Effect.succeed({}) ? Effect.succeed({})
: runCommandOutput({ : runCommandOutput({
probe: "login-shell",
command: shell, command: shell,
args: ["-ilc", capturePosixEnvironmentCommand(names)], args: ["-ilc", capturePosixEnvironmentCommand(names)],
timeout: LOGIN_SHELL_TIMEOUT, timeout: LOGIN_SHELL_TIMEOUT,
}).pipe(Effect.map((output) => extractEnvironment(output, names))); }).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath = runCommandOutput({ const readLaunchctlPath: Effect.Effect<
probe: "launchctl-path", Option.Option<string>,
never,
ChildProcessSpawner.ChildProcessSpawner
> = runCommandOutput({
command: "/bin/launchctl", command: "/bin/launchctl",
args: ["getenv", "PATH"], args: ["getenv", "PATH"],
timeout: LAUNCHCTL_TIMEOUT, timeout: LAUNCHCTL_TIMEOUT,
@@ -311,7 +239,6 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
for (const command of WINDOWS_SHELL_CANDIDATES) { for (const command of WINDOWS_SHELL_CANDIDATES) {
const output = yield* runCommandOutput({ const output = yield* runCommandOutput({
probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
command, command,
args, args,
timeout: LOGIN_SHELL_TIMEOUT, timeout: LOGIN_SHELL_TIMEOUT,
@@ -409,20 +336,20 @@ const installShellEnvironment = (
return Effect.void; return Effect.void;
}; };
export const make = Effect.gen(function* () { export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment; DesktopShellEnvironment,
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; Effect.gen(function* () {
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] = const environment = yield* DesktopEnvironment.DesktopEnvironment;
installShellEnvironment({ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
env: process.env, return DesktopShellEnvironment.of({
platform: environment.platform, installIntoProcess: installShellEnvironment({
userShell: Option.none(), env: process.env,
}).pipe( platform: environment.platform,
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), userShell: Option.none(),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"), }).pipe(
); Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
return DesktopShellEnvironment.of({ installIntoProcess }); ),
}); });
}),
export const layer = Layer.effect(DesktopShellEnvironment, make); );
@@ -19,21 +19,6 @@ function makeTempHomeDir() {
} }
describe("sshEnvironment", () => { describe("sshEnvironment", () => {
it("keeps prompt presentation diagnostics distinct from the legacy wrapper message", () => {
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
requestId: "prompt-1",
destination: "devbox",
operation: "send-prompt-request",
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", () => { it("treats password prompt timeouts as cancellable authentication prompts", () => {
assert.equal( assert.equal(
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation( DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(
@@ -119,6 +104,7 @@ describe("sshEnvironment", () => {
Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, { Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {
request: () => Effect.die("unexpected password prompt request"), request: () => Effect.die("unexpected password prompt request"),
resolve: () => Effect.die("unexpected password prompt resolution"), resolve: () => Effect.die("unexpected password prompt resolution"),
cancelPending: () => Effect.void,
}), }),
), ),
Layer.provideMerge(NodeServices.layer), Layer.provideMerge(NodeServices.layer),
+41 -61
View File
@@ -4,7 +4,11 @@ import type {
DesktopSshEnvironmentTarget, DesktopSshEnvironmentTarget,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net"; 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 { discoverSshHosts } from "@t3tools/ssh/config";
import { import {
SshCommandError, SshCommandError,
@@ -15,14 +19,14 @@ import {
SshPasswordPromptError, SshPasswordPromptError,
SshReadinessError, SshReadinessError,
} from "@t3tools/ssh/errors"; } 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 Context from "effect/Context";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem"; import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Path from "effect/Path"; import * as Path from "effect/Path";
import * as HttpClient from "effect/unstable/http/HttpClient"; import { HttpClient } from "effect/unstable/http";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts"; import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
@@ -48,25 +52,27 @@ export type DesktopSshEnvironmentError =
| DesktopSshEnvironmentDiscoverError | DesktopSshEnvironmentDiscoverError
| DesktopSshEnvironmentOperationError; | 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< export class DesktopSshEnvironment extends Context.Service<
DesktopSshEnvironment, DesktopSshEnvironment,
{ 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>;
}
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {} >()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
export interface DesktopSshEnvironmentLayerOptions { export interface DesktopSshEnvironmentLayerOptions {
readonly resolveCliPackageSpec?: () => string; readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: Effect.Effect<SshTunnel.RemoteT3RunnerOptions>; readonly resolveCliRunner?: Effect.Effect<RemoteT3RunnerOptions>;
} }
function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) { 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 = ( const makePasswordPrompt = (
prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPrompts["Service"], prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPromptsShape,
): SshAuth.SshPasswordPrompt["Service"] => ({ ): SshPasswordPromptShape => ({
isAvailable: true, isAvailable: true,
request: (request: SshAuth.SshPasswordRequest) => request: (request: SshPasswordRequest) =>
prompts.request(request).pipe(Effect.mapError(toSshPasswordPromptError)), prompts.request(request).pipe(
Effect.mapError(
(cause) =>
new SshPasswordPromptError({
message: cause.message,
cause,
}),
),
),
}); });
export const make = Effect.gen(function* () { const make = Effect.gen(function* () {
const manager = yield* SshTunnel.SshEnvironmentManager; const manager = yield* SshEnvironmentManager;
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts; const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>(); const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>();
const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts)); const passwordPrompt = SshPasswordPrompt.of(makePasswordPrompt(prompts));
return DesktopSshEnvironment.of({ return DesktopSshEnvironment.of({
discoverHosts: (input) => discoverHosts: (input) =>
@@ -140,7 +120,7 @@ export const make = Effect.gen(function* () {
manager manager
.ensureEnvironment(target, ensureOptions) .ensureEnvironment(target, ensureOptions)
.pipe( .pipe(
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt), Effect.provideService(SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext), Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.ensureEnvironment"), Effect.withSpan("desktop.ssh.ensureEnvironment"),
), ),
@@ -148,7 +128,7 @@ export const make = Effect.gen(function* () {
manager manager
.disconnectEnvironment(target) .disconnectEnvironment(target)
.pipe( .pipe(
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt), Effect.provideService(SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext), Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.disconnectEnvironment"), Effect.withSpan("desktop.ssh.disconnectEnvironment"),
), ),
@@ -158,7 +138,7 @@ export const make = Effect.gen(function* () {
export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) => export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) =>
Layer.effect(DesktopSshEnvironment, make).pipe( Layer.effect(DesktopSshEnvironment, make).pipe(
Layer.provide( Layer.provide(
SshTunnel.SshEnvironmentManager.layer({ SshEnvironmentManager.layer({
...(options.resolveCliPackageSpec === undefined ...(options.resolveCliPackageSpec === undefined
? {} ? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }), : { resolveCliPackageSpec: options.resolveCliPackageSpec }),
@@ -9,7 +9,7 @@ import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron"; import type * as Electron from "electron";
import * as ElectronWindow from "../electron/ElectronWindow.ts"; 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"; import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
interface SentMessage { interface SentMessage {
@@ -17,13 +17,7 @@ interface SentMessage {
readonly args: readonly unknown[]; readonly args: readonly unknown[];
} }
function makeTestWindow( function makeTestWindow() {
options: {
readonly isDestroyedError?: unknown;
readonly isMinimizedError?: unknown;
readonly sendError?: unknown;
} = {},
) {
const listeners = new Map<string, Set<() => void>>(); const listeners = new Map<string, Set<() => void>>();
const sentMessages: SentMessage[] = []; const sentMessages: SentMessage[] = [];
let destroyed = false; let destroyed = false;
@@ -32,18 +26,8 @@ function makeTestWindow(
let focused = false; let focused = false;
const window = { const window = {
isDestroyed: () => { isDestroyed: () => destroyed,
if (options.isDestroyedError !== undefined) { isMinimized: () => minimized,
throw options.isDestroyedError;
}
return destroyed;
},
isMinimized: () => {
if (options.isMinimizedError !== undefined) {
throw options.isMinimizedError;
}
return minimized;
},
restore: () => { restore: () => {
restored = true; restored = true;
minimized = false; minimized = false;
@@ -61,11 +45,7 @@ function makeTestWindow(
}, },
webContents: { webContents: {
send: (channel: string, ...args: readonly unknown[]) => { send: (channel: string, ...args: readonly unknown[]) => {
const message = { channel, args }; sentMessages.push({ channel, args });
sentMessages.push(message);
if (options.sendError !== undefined) {
throw options.sendError;
}
}, },
}, },
}; };
@@ -75,7 +55,6 @@ function makeTestWindow(
sentMessages, sentMessages,
isRestored: () => restored, isRestored: () => restored,
isFocused: () => focused, isFocused: () => focused,
closedListenerCount: () => listeners.get("closed")?.size ?? 0,
close: () => { close: () => {
destroyed = true; destroyed = true;
const closedListeners = [...(listeners.get("closed") ?? [])]; const closedListeners = [...(listeners.get("closed") ?? [])];
@@ -128,12 +107,11 @@ describe("DesktopSshPasswordPrompts", () => {
}) })
.pipe(Effect.forkScoped); .pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* Effect.yieldNow; yield* Effect.yieldNow;
assert.equal(testWindow.sentMessages.length, 1); assert.equal(testWindow.sentMessages.length, 1);
const sent = testWindow.sentMessages[0]; const sent = testWindow.sentMessages[0];
assert.ok(sent); 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 }; const request = sent.args[0] as { readonly requestId: string; readonly destination: string };
assert.equal(request.destination, "devbox"); assert.equal(request.destination, "devbox");
assert.equal(testWindow.isRestored(), true); assert.equal(testWindow.isRestored(), true);
@@ -165,85 +143,4 @@ describe("DesktopSshPasswordPrompts", () => {
assert.equal(error.destination, "devbox"); assert.equal(error.destination, "devbox");
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped); }).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
}); });
it.effect("cleans up a prompt that fails during renderer delivery", () => {
const cause = new Error("renderer unavailable");
const testWindow = makeTestWindow({ sendError: cause });
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const error = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
assert.equal(error.operation, "send-prompt-request");
assert.equal(error.destination, "devbox");
const requestId = error.requestId;
if (requestId === null) {
assert.fail("renderer delivery failures must retain their request id");
}
assert.equal(testWindow.closedListenerCount(), 0);
const resolveError = yield* prompts
.resolve({ requestId, password: "secret" })
.pipe(Effect.flip);
assert.instanceOf(resolveError, DesktopSshPasswordPrompts.DesktopSshPromptExpiredError);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("keeps a submitted password when a later presentation step fails", () => {
const testWindow = makeTestWindow({
isMinimizedError: new Error("failed to read minimized state"),
});
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const requestFiber = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const sent = testWindow.sentMessages[0];
assert.ok(sent);
const request = sent.args[0] as { readonly requestId: string };
yield* prompts.resolve({ requestId: request.requestId, password: "secret" });
const password = yield* Fiber.join(requestFiber);
assert.equal(password, "secret");
assert.equal(testWindow.isFocused(), false);
assert.equal(testWindow.closedListenerCount(), 0);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("classifies a failed initial window availability check", () => {
const testWindow = makeTestWindow({ isDestroyedError: new Error("window unavailable") });
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const error = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
assert.equal(error.operation, "check-window-before-request");
assert.equal(error.requestId, null);
assert.deepEqual(testWindow.sentMessages, []);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
}); });
+114 -250
View File
@@ -3,6 +3,7 @@ import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contract
import type { SshPasswordRequest } from "@t3tools/ssh/auth"; import type { SshPasswordRequest } from "@t3tools/ssh/auth";
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto"; import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime"; import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred"; import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration"; import * as Duration from "effect/Duration";
@@ -10,155 +11,93 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import * as Ref from "effect/Ref"; 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 * 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 DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
type DesktopSshPasswordPromptResolutionInput = type DesktopSshPasswordPromptResolutionInput =
typeof DesktopSshPasswordPromptResolutionInputSchema.Type; typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
const DesktopSshPromptWindowAvailabilityStage = Schema.Literals([ export class DesktopSshPromptUnavailableError extends Data.TaggedError(
"before-request", "DesktopSshPromptUnavailableError",
"before-presentation", )<{
"after-send", readonly reason: string;
"after-restore", }> {
]); override get message() {
return this.reason;
const DesktopSshPromptPresentationOperation = Schema.Literals([
"check-window-before-request",
"check-window-before-presentation",
"register-window-close-listener",
"send-prompt-request",
"check-window-after-send",
"check-window-minimized",
"restore-window",
"check-window-after-restore",
"focus-window",
"remove-window-close-listener",
]);
type DesktopSshPromptPresentationOperation = typeof DesktopSshPromptPresentationOperation.Type;
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
"DesktopSshPromptRequestIdGenerationError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Secure randomness is unavailable.";
} }
} }
export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorClass<DesktopSshPromptWindowUnavailableError>()( export class DesktopSshPromptWindowUnavailableError extends Data.TaggedError(
"DesktopSshPromptWindowUnavailableError", "DesktopSshPromptWindowUnavailableError",
{ )<{
destination: Schema.String, readonly destination: string;
requestId: Schema.NullOr(Schema.String), }> {
stage: DesktopSshPromptWindowAvailabilityStage, override get message() {
}, return WINDOW_UNAVAILABLE_MESSAGE;
) {
override get message(): string {
const request = this.requestId === null ? "before a request id was assigned" : this.requestId;
return `T3 Code window is unavailable during ${this.stage} for SSH authentication to ${this.destination} (request: ${request}).`;
} }
} }
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()( export class DesktopSshPromptSendError extends Data.TaggedError("DesktopSshPromptSendError")<{
"DesktopSshPromptPresentationError", readonly requestId: string;
{ readonly destination: string;
requestId: Schema.NullOr(Schema.String), readonly cause: unknown;
destination: Schema.String, }> {
operation: DesktopSshPromptPresentationOperation, override get message() {
cause: Schema.Defect(), return WINDOW_UNAVAILABLE_MESSAGE;
},
) {
override get message(): string {
return `Failed to present SSH password prompt for ${this.destination}.`;
} }
} }
export class DesktopSshPromptTimedOutError extends Schema.TaggedErrorClass<DesktopSshPromptTimedOutError>()( export class DesktopSshPromptTimedOutError extends Data.TaggedError(
"DesktopSshPromptTimedOutError", "DesktopSshPromptTimedOutError",
{ )<{
requestId: Schema.String, readonly requestId: string;
destination: Schema.String, readonly destination: string;
}, }> {
) { override get message() {
override get message(): string {
return `SSH authentication timed out for ${this.destination}.`; return `SSH authentication timed out for ${this.destination}.`;
} }
} }
export class DesktopSshPromptCancelledError extends Schema.TaggedErrorClass<DesktopSshPromptCancelledError>()( export class DesktopSshPromptCancelledError extends Data.TaggedError(
"DesktopSshPromptCancelledError", "DesktopSshPromptCancelledError",
{ )<{
requestId: Schema.String, readonly requestId: string;
destination: Schema.String, readonly destination: string;
}, readonly reason: string;
) { }> {
override get message(): string { override get message() {
return `SSH authentication cancelled for ${this.destination}.`; return this.reason;
} }
} }
export class DesktopSshPromptWindowClosedError extends Schema.TaggedErrorClass<DesktopSshPromptWindowClosedError>()( export class DesktopSshPromptInvalidRequestIdError extends Data.TaggedError(
"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>()(
"DesktopSshPromptInvalidRequestIdError", "DesktopSshPromptInvalidRequestIdError",
{ )<{
requestId: Schema.String, readonly requestId: string;
}, }> {
) { override get message() {
override get message(): string {
return "Invalid SSH password prompt id."; return "Invalid SSH password prompt id.";
} }
} }
export class DesktopSshPromptExpiredError extends Schema.TaggedErrorClass<DesktopSshPromptExpiredError>()( export class DesktopSshPromptExpiredError extends Data.TaggedError("DesktopSshPromptExpiredError")<{
"DesktopSshPromptExpiredError", readonly requestId: string;
{ }> {
requestId: Schema.String, override get message() {
},
) {
override get message(): string {
return "SSH password prompt expired. Try connecting again."; return "SSH password prompt expired. Try connecting again.";
} }
} }
export type DesktopSshPasswordPromptRequestError = export type DesktopSshPasswordPromptRequestError =
| DesktopSshPromptRequestIdGenerationError | DesktopSshPromptUnavailableError
| DesktopSshPromptWindowUnavailableError | DesktopSshPromptWindowUnavailableError
| DesktopSshPromptPresentationError | DesktopSshPromptSendError
| DesktopSshPromptTimedOutError | DesktopSshPromptTimedOutError
| DesktopSshPromptCancelledError | DesktopSshPromptCancelledError;
| DesktopSshPromptWindowClosedError
| DesktopSshPromptServiceStoppedError;
export type DesktopSshPasswordPromptResolveError = export type DesktopSshPasswordPromptResolveError =
| DesktopSshPromptInvalidRequestIdError | DesktopSshPromptInvalidRequestIdError
@@ -168,28 +107,28 @@ export type DesktopSshPasswordPromptError =
| DesktopSshPasswordPromptRequestError | DesktopSshPasswordPromptRequestError
| DesktopSshPasswordPromptResolveError; | DesktopSshPasswordPromptResolveError;
export const DesktopSshPasswordPromptCancellation = Schema.Union([ export function isDesktopSshPasswordPromptCancellation(
DesktopSshPromptCancelledError, error: unknown,
DesktopSshPromptWindowClosedError, ): error is DesktopSshPromptCancelledError | DesktopSshPromptTimedOutError {
DesktopSshPromptServiceStoppedError, return (
DesktopSshPromptTimedOutError, error instanceof DesktopSshPromptCancelledError ||
]); error instanceof DesktopSshPromptTimedOutError
export type DesktopSshPasswordPromptCancellation = typeof DesktopSshPasswordPromptCancellation.Type; );
}
export const isDesktopSshPasswordPromptCancellation = Schema.is( export interface DesktopSshPasswordPromptsShape {
DesktopSshPasswordPromptCancellation, 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< export class DesktopSshPasswordPrompts extends Context.Service<
DesktopSshPasswordPrompts, DesktopSshPasswordPrompts,
{ DesktopSshPasswordPromptsShape
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
readonly resolve: (
input: DesktopSshPasswordPromptResolutionInput,
) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
}
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {} >()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
interface PendingSshPasswordPrompt { interface PendingSshPasswordPrompt {
@@ -198,7 +137,7 @@ interface PendingSshPasswordPrompt {
readonly deferred: Deferred.Deferred<string, DesktopSshPasswordPromptRequestError>; readonly deferred: Deferred.Deferred<string, DesktopSshPasswordPromptRequestError>;
} }
export interface DesktopSshPasswordPromptsOptions { interface LayerOptions {
readonly passwordPromptTimeoutMs?: number; readonly passwordPromptTimeoutMs?: number;
} }
@@ -222,16 +161,14 @@ const failPending = (
error: DesktopSshPasswordPromptRequestError, error: DesktopSshPasswordPromptRequestError,
) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid); ) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid);
export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* ( const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
options: DesktopSshPasswordPromptsOptions = {},
) {
const electronWindow = yield* ElectronWindow.ElectronWindow; const electronWindow = yield* ElectronWindow.ElectronWindow;
const crypto = yield* Crypto.Crypto; const crypto = yield* Crypto.Crypto;
const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>()); const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
const passwordPromptTimeoutMs = const passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS; options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
const cancelPending = () => const cancelPending = (reason: string): Effect.Effect<void> =>
Ref.getAndSet(pendingRef, new Map()).pipe( Ref.getAndSet(pendingRef, new Map()).pipe(
Effect.flatMap((pending) => Effect.flatMap((pending) =>
Effect.forEach( Effect.forEach(
@@ -239,9 +176,10 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
(entry) => (entry) =>
failPending( failPending(
entry, entry,
new DesktopSshPromptServiceStoppedError({ new DesktopSshPromptCancelledError({
requestId: entry.requestId, requestId: entry.requestId,
destination: entry.destination, destination: entry.destination,
reason,
}), }),
), ),
{ discard: true }, { discard: true },
@@ -250,11 +188,13 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
Effect.asVoid, 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( const resolve = Effect.fn("desktop.sshPasswordPrompts.resolve")(function* (
"desktop.sshPasswordPrompts.resolve", input: DesktopSshPasswordPromptResolutionInput,
)(function* (input) { ): Effect.fn.Return<void, DesktopSshPasswordPromptResolveError> {
const requestId = input.requestId.trim(); const requestId = input.requestId.trim();
if (requestId.length === 0) { if (requestId.length === 0) {
return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId }); return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId });
@@ -272,6 +212,7 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
new DesktopSshPromptCancelledError({ new DesktopSshPromptCancelledError({
requestId, requestId,
destination: entry.destination, destination: entry.destination,
reason: `SSH authentication cancelled for ${entry.destination}.`,
}), }),
); );
return; return;
@@ -280,43 +221,19 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid); yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid);
}); });
const request: DesktopSshPasswordPrompts["Service"]["request"] = Effect.fn( const request = Effect.fn("desktop.sshPasswordPrompts.request")(function* (
"desktop.sshPasswordPrompts.request", input: SshPasswordRequest,
)(function* (input) { ): Effect.fn.Return<string, DesktopSshPasswordPromptRequestError> {
const window = yield* electronWindow.main; const window = yield* electronWindow.main;
if (Option.isNone(window)) { if (Option.isNone(window) || window.value.isDestroyed()) {
return yield* new DesktopSshPromptWindowUnavailableError({ return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination, destination: input.destination,
requestId: null,
stage: "before-request",
});
}
const unavailableBeforeRequest = yield* Effect.try({
try: () => window.value.isDestroyed(),
catch: (cause) =>
new DesktopSshPromptPresentationError({
requestId: null,
destination: input.destination,
operation: "check-window-before-request",
cause,
}),
});
if (unavailableBeforeRequest) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId: null,
stage: "before-request",
}); });
} }
const requestId = yield* crypto.randomUUIDv4.pipe( const requestId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError( Effect.mapError(
(cause) => () => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
new DesktopSshPromptRequestIdGenerationError({
destination: input.destination,
cause,
}),
), ),
); );
const now = yield* DateTime.now; const now = yield* DateTime.now;
@@ -350,9 +267,10 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
onSome: (pending) => onSome: (pending) =>
failPending( failPending(
pending, pending,
new DesktopSshPromptWindowClosedError({ new DesktopSshPromptCancelledError({
requestId, requestId,
destination: input.destination, destination: input.destination,
reason: "SSH authentication was cancelled because the app window closed.",
}), }),
), ),
}), }),
@@ -360,25 +278,11 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
), ),
); );
}; };
const runPresentationOperation = <A>( const cleanup = Effect.sync(() => {
operation: DesktopSshPromptPresentationOperation,
evaluate: () => A,
) =>
Effect.try({
try: evaluate,
catch: (cause) =>
new DesktopSshPromptPresentationError({
requestId,
destination: input.destination,
operation,
cause,
}),
});
const cleanup = runPresentationOperation("remove-window-close-listener", () => {
if (!window.value.isDestroyed()) { if (!window.value.isDestroyed()) {
window.value.removeListener("closed", cancelOnWindowClosed); window.value.removeListener("closed", cancelOnWindowClosed);
} }
}).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid); }).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
const waitForPassword = Deferred.await(deferred).pipe( const waitForPassword = Deferred.await(deferred).pipe(
Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)), Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
Effect.flatMap( Effect.flatMap(
@@ -394,80 +298,40 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
}), }),
), ),
); );
const preferSubmittedPassword = (error: DesktopSshPasswordPromptRequestError) =>
Deferred.poll(deferred).pipe(
Effect.flatMap(
Option.match({
onSome: (completion) => completion,
onNone: () =>
Ref.get(pendingRef).pipe(
Effect.flatMap((entries) =>
entries.has(requestId) ? Effect.fail(error) : Deferred.await(deferred),
),
),
}),
),
);
return yield* Effect.gen(function* () { return yield* Effect.try({
const unavailableBeforePresentation = yield* runPresentationOperation( try: () => {
"check-window-before-presentation", if (window.value.isDestroyed()) {
() => window.value.isDestroyed(), throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
); }
if (unavailableBeforePresentation) { window.value.once("closed", cancelOnWindowClosed);
return yield* new DesktopSshPromptWindowUnavailableError({ window.value.webContents.send(IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
destination: input.destination, if (window.value.isDestroyed()) {
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
}
if (window.value.isMinimized()) {
window.value.restore();
}
if (window.value.isDestroyed()) {
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
}
window.value.focus();
},
catch: (cause) =>
new DesktopSshPromptSendError({
requestId, requestId,
stage: "before-presentation", destination: input.destination,
}); cause,
} }),
yield* runPresentationOperation("register-window-close-listener", () => }).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
window.value.once("closed", cancelOnWindowClosed),
);
return yield* Effect.gen(function* () {
yield* runPresentationOperation("send-prompt-request", () =>
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest),
);
yield* Effect.yieldNow;
const unavailableAfterSend = yield* runPresentationOperation(
"check-window-after-send",
() => window.value.isDestroyed(),
);
if (unavailableAfterSend) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "after-send",
});
}
const minimized = yield* runPresentationOperation("check-window-minimized", () =>
window.value.isMinimized(),
);
if (minimized) {
yield* runPresentationOperation("restore-window", () => window.value.restore());
}
const unavailableAfterRestore = yield* runPresentationOperation(
"check-window-after-restore",
() => window.value.isDestroyed(),
);
if (unavailableAfterRestore) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "after-restore",
});
}
yield* runPresentationOperation("focus-window", () => window.value.focus());
return yield* waitForPassword;
}).pipe(Effect.catch(preferSubmittedPassword));
}).pipe(Effect.ensuring(cleanup));
}); });
return DesktopSshPasswordPrompts.of({ return DesktopSshPasswordPrompts.of({
request, request,
resolve, resolve,
cancelPending,
}); });
}); });
export const layer = (options: DesktopSshPasswordPromptsOptions = {}) => export const layer = (options: LayerOptions = {}) =>
Layer.effect(DesktopSshPasswordPrompts, make(options)); Layer.effect(DesktopSshPasswordPrompts, make(options));
Loaded 100 of 1530 files, more files were not shown because too many files have changed in this diff. Show more