Compare commits

..
Author SHA1 Message Date
Cursor Agent b2af107f91 fix: cloud switch retry and encrypted catalog availability handling
- Fix cloud environment switch showing ON for error/offline states, which
  blocked retry since React Native Switch only fires onValueChange on
  transitions. The switch now only shows ON for connected/connecting/
  reconnecting states, allowing users to toggle ON to retry from error
  or offline states.

- Fix DesktopConnectionCatalogStore.get returning an empty Option when
  an encrypted catalog exists but safe storage is unavailable. This
  silently hid the catalog and risked overwriting it. Now fails with
  ElectronSafeStorageAvailabilityError so callers can surface the issue
  instead of treating it as an empty catalog.
2026-06-21 21:34:09 +00:00
Julius Marminge 38f46e6971 Refresh mobile dependency lockfile
- Update React Native peer dependency snapshots and local module hashes
2026-06-21 14:19:53 -07:00
Julius Marmingeandcodex ed0b6119c2 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-18 00:20:24 -07:00
Julius Marmingeandcodex b01bf05c50 Restore retained environment HTTP test helper
Co-authored-by: codex <[email protected]>
2026-06-18 00:19:18 -07:00
Julius Marmingeandcodex 344fca1edc Restore client behavior and stabilize async UI state
Co-authored-by: codex <[email protected]>
2026-06-18 00:17:04 -07:00
Julius Marminge c09f491b37 nuke browser tests cause codex just gets caught up in them 2026-06-18 00:00:47 -07:00
Julius Marmingeandcodex c55ae239ff Harden terminal reconnection and asset URL handling
- Keep terminal state consistent across close, reopen, and stale metadata
- Load historical attachments through signed asset URLs
- Serialize resizes and ignore requests for closed terminals

Co-authored-by: codex <[email protected]>
2026-06-17 22:24:54 -07:00
Julius Marminge ca35205f43 Stabilize draft promotion and live session recovery
- Finalize promoted drafts from inferred live threads
- Retry transient RPC and thread sync failures within a session
- Preserve full thread history and delay shell cache persistence
2026-06-17 19:26:56 -07:00
Julius Marminge 2b9cf7d18a Refactor connection-aware asset and VCS state handling
- Route mobile/web asset URLs through shared runtime state
- Replace remote HTTP header plumbing with environment asset URLs
- Add optional cached remote status reads without upstream refresh
2026-06-17 16:36:38 -07:00
Julius Marmingeandcodex a2ed9bbb4f Fix browser atom command mocks
Co-authored-by: codex <[email protected]>
2026-06-17 00:41:42 -07:00
Julius Marmingeandcodex 841bbd9a17 Harden connection state handling across app
- adopt atom command results for connection and relay flows
- preserve relay error trace IDs and improve failure handling
- add coverage for auth, registration, and environment updates

Co-authored-by: codex <[email protected]>
2026-06-16 23:47:55 -07:00
Julius Marminge 55228d4119 rm doc 2026-06-16 23:38:01 -07:00
Julius Marminge ebda0b6d28 rm service indirection 2026-06-16 23:38:01 -07:00
Julius Marmingeandcodex bd079220f8 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-16 23:38:01 -07:00
Julius Marmingeandcodex c1281076e6 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-16 16:47:56 -07:00
Julius Marmingeandcodex 449d7993d1 Centralize client runtime state management
Co-authored-by: codex <[email protected]>
2026-06-16 15:42:37 -07:00
Julius Marmingeandcodex 2eaface4b1 Rewrite client connection architecture
Move web, desktop, server, and mobile connection state onto the shared client runtime while preserving the separately reviewed native mobile UI stack.

Co-authored-by: codex <[email protected]>
2026-06-16 11:11:45 -07:00
732 changed files with 22722 additions and 31742 deletions

No files matched your search

-7
View File
@@ -8,13 +8,6 @@
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# 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.
# T3CODE_RELAY_URL=https://relay.example.com
-1
View File
@@ -38,7 +38,6 @@ jobs:
run: |
test -f 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:
name: Test
-2
View File
@@ -2,12 +2,10 @@ name: Mobile EAS Preview
on:
pull_request:
types: [opened, reopened, synchronize, labeled, unlabeled]
jobs:
preview:
name: EAS Preview
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
-15
View File
@@ -425,9 +425,6 @@ jobs:
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
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_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
@@ -455,21 +452,9 @@ jobs:
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 "$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"
printf '%s' "$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."
args+=(--signed)
else
@@ -1,76 +0,0 @@
---
title: Effect Service Conventions
model: claude-opus-4-8
effort: high
input: full_diff
tools:
- browse_code
- git_tools
- github_api_read_only
- modify_pr
include:
- "apps/**/*.ts"
- "apps/**/*.tsx"
- "packages/**/*.ts"
- "packages/**/*.tsx"
- "infra/**/*.ts"
- "infra/**/*.tsx"
conclusion: failure
showToolCalls: true
---
# Effect service review
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
## Imports and module namespaces
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
## Service definition
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
## File layout and migrations
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
## Change discipline
- Preserve useful comments, invariants, and specification documentation while moving code.
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
-3
View File
@@ -12,8 +12,6 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@clerk/electron": "catalog:",
"@clerk/electron-passkeys": "catalog:",
"@effect/platform-node": "catalog:",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
@@ -22,7 +20,6 @@
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
@@ -1,23 +1,23 @@
import * as NodeFSP from "node:fs/promises";
import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { compile } from "tailwindcss";
const directory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const appRoot = NodePath.join(directory, "..");
const sourcePath = NodePath.join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = NodePath.join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = NodePath.join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = NodeModule.createRequire(import.meta.url);
const tailwindRoot = NodePath.dirname(require.resolve("tailwindcss/package.json"));
const directory = dirname(fileURLToPath(import.meta.url));
const appRoot = join(directory, "..");
const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = createRequire(import.meta.url);
const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
NodeFSP.readFile(sourcePath, "utf8"),
NodeFSP.readFile(preloadPath, "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "theme.css"), "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "preflight.css"), "utf8"),
readFile(sourcePath, "utf8"),
readFile(preloadPath, "utf8"),
readFile(join(tailwindRoot, "theme.css"), "utf8"),
readFile(join(tailwindRoot, "preflight.css"), "utf8"),
]);
const candidates = new Set(
@@ -37,4 +37,4 @@ const encodedCss = `'${css
.replaceAll("\n", "\\n")}'`;
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
await NodeFSP.writeFile(outputPath, moduleSource);
await writeFile(outputPath, moduleSource);
+9 -13
View File
@@ -1,7 +1,7 @@
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { join } from "node:path";
import {
desktopDir,
@@ -64,7 +64,7 @@ function killChildTreeByPid(pid, signal) {
return;
}
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
}
function cleanupStaleDevApps() {
@@ -72,9 +72,7 @@ function cleanupStaleDevApps() {
return;
}
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {
stdio: "ignore",
});
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
}
function startApp() {
@@ -89,7 +87,7 @@ function startApp() {
? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const electronCommand = resolveElectronLaunchCommand(launchArgs);
const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
const app = spawn(electronCommand.electronPath, electronCommand.args, {
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
@@ -182,8 +180,8 @@ function scheduleRestart() {
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = NodeFS.watch(
NodePath.join(desktopDir, directory),
const watcher = watch(
join(desktopDir, directory),
{ persistent: true },
(_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
@@ -204,9 +202,7 @@ function killChildTree(signal) {
}
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
stdio: "ignore",
});
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
}
async function shutdown(exitCode) {
+94 -90
View File
@@ -1,18 +1,29 @@
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import { spawnSync } from "node:child_process";
import {
copyFileSync,
chmodSync,
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
export const desktopDir = NodePath.resolve(__dirname, "..");
const repoRoot = NodePath.resolve(desktopDir, "..", "..");
const devBundleIdSuffix = NodePath.basename(repoRoot)
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const devBundleIdSuffix = basename(repoRoot)
.toLowerCase()
.replaceAll(/[^a-z0-9]+/g, "");
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
@@ -20,36 +31,31 @@ export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 12;
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = NodePath.join(
repoRoot,
"assets",
"dev",
"blueprint-macos-1024.png",
);
const LAUNCHER_VERSION = 11;
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
const hostPlatform = NodeOS.platform();
function resolveDevelopmentProtocolCallbackPort() {
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
return configuredPort + 1;
}
return 13774;
}
function setPlistString(plistPath, key, value) {
const replaceResult = NodeChildProcess.spawnSync(
"plutil",
["-replace", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
encoding: "utf8",
});
if (replaceResult.status === 0) {
return;
}
const insertResult = NodeChildProcess.spawnSync(
"plutil",
["-insert", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
encoding: "utf8",
});
if (insertResult.status === 0) {
return;
}
@@ -60,24 +66,16 @@ function setPlistString(plistPath, key, value) {
function setPlistJson(plistPath, key, value) {
const serialized = JSON.stringify(value);
const replaceResult = NodeChildProcess.spawnSync(
"plutil",
["-replace", key, "-json", serialized, plistPath],
{
encoding: "utf8",
},
);
const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
if (replaceResult.status === 0) {
return;
}
const insertResult = NodeChildProcess.spawnSync(
"plutil",
["-insert", key, "-json", serialized, plistPath],
{
encoding: "utf8",
},
);
const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
if (insertResult.status === 0) {
return;
}
@@ -87,7 +85,7 @@ function setPlistJson(plistPath, key, value) {
}
function runChecked(command, args) {
const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
@@ -101,7 +99,8 @@ function shellSingleQuote(value) {
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
const 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],
@@ -110,17 +109,28 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
["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);
NodeFS.writeFileSync(
writeFileSync(
targetBinaryPath,
[
"#!/bin/sh",
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
'for arg in "$@"; do',
' 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) {
@@ -150,24 +160,21 @@ function registerMacLauncherBundle(appBundlePath) {
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
NodeFS.mkdirSync(runtimeDir, { recursive: true });
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
if (
NodeFS.existsSync(generatedIconPath) &&
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
) {
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
return generatedIconPath;
}
const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
NodeFS.mkdirSync(iconsetDir, { recursive: true });
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
@@ -177,7 +184,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(size),
developmentMacIconPngPath,
"--out",
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
@@ -187,7 +194,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(retinaSize),
developmentMacIconPngPath,
"--out",
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
@@ -200,12 +207,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
);
return defaultIconPath;
} finally {
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
@@ -217,9 +224,9 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
},
]);
const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
const resourcesDir = join(appBundlePath, "Contents", "Resources");
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
@@ -231,7 +238,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
];
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
const infoPlistPath = NodePath.join(
const infoPlistPath = join(
appBundlePath,
"Contents",
"Frameworks",
@@ -239,7 +246,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
"Contents",
"Info.plist",
);
if (!NodeFS.existsSync(infoPlistPath)) {
if (!existsSync(infoPlistPath)) {
continue;
}
@@ -255,34 +262,34 @@ function patchHelperBundleInfoPlists(appBundlePath) {
function readJson(path) {
try {
return JSON.parse(NodeFS.readFileSync(path, "utf8"));
return JSON.parse(readFileSync(path, "utf8"));
} catch {
return null;
}
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
const metadataPath = join(runtimeDir, "metadata.json");
NodeFS.mkdirSync(runtimeDir, { recursive: true });
mkdirSync(runtimeDir, { recursive: true });
const expectedMetadata = {
launcherVersion: LAUNCHER_VERSION,
sourceAppBundlePath,
sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: statSync(iconPath).mtimeMs,
appBundleId: APP_BUNDLE_ID,
appProtocolSchemes: APP_PROTOCOL_SCHEMES,
};
const currentMetadata = readJson(metadataPath);
if (
NodeFS.existsSync(targetBinaryPath) &&
existsSync(targetBinaryPath) &&
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
@@ -290,21 +297,18 @@ function buildMacLauncher(electronBinaryPath) {
return targetBinaryPath;
}
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
rmSync(targetAppBundlePath, { recursive: true, force: true });
// verbatimSymlinks keeps the framework's relative symlinks intact
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
// rewrites them to absolute paths into node_modules, which escape the
// bundle and crash sandboxed helper processes (icudtl.dat not found).
NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
recursive: true,
verbatimSymlinks: true,
});
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
@@ -315,9 +319,9 @@ function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
return true;
}
const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
const sandboxPath = join(dirname(electronBinaryPath), "chrome-sandbox");
try {
const sandboxStat = NodeFS.statSync(sandboxPath);
const sandboxStat = statSync(sandboxPath);
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
} catch {
return false;
@@ -338,7 +342,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
export function resolveElectronPath() {
ensureElectronRuntime();
const require = NodeModule.createRequire(import.meta.url);
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
if (hostPlatform !== "darwin") {
@@ -361,11 +365,11 @@ export function resolveDevProtocolClient() {
return null;
}
const require = NodeModule.createRequire(import.meta.url);
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."),
appBundleId: APP_BUNDLE_ID,
};
}
@@ -1,14 +1,14 @@
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeChildProcess from "node:child_process";
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { arch, platform, tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
const require = NodeModule.createRequire(import.meta.url);
const require = createRequire(import.meta.url);
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostPlatform = NodeOS.platform();
const hostPlatform = platform();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostArch = NodeOS.arch();
const hostArch = arch();
function getPlatformPath() {
switch (hostPlatform) {
@@ -27,28 +27,26 @@ function getPlatformPath() {
function ensureExecutable(filePath) {
if (hostPlatform !== "win32") {
NodeFS.chmodSync(filePath, 0o755);
chmodSync(filePath, 0o755);
}
}
function repairPathFile(electronDir, platformPath) {
const pathFile = NodePath.join(electronDir, "path.txt");
const currentPath = NodeFS.existsSync(pathFile)
? NodeFS.readFileSync(pathFile, "utf8")
: undefined;
const pathFile = join(electronDir, "path.txt");
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
if (currentPath !== platformPath) {
NodeFS.writeFileSync(pathFile, platformPath);
writeFileSync(pathFile, platformPath);
}
}
function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [NodePath.join(electronDir, "dist", platformPath)];
const paths = [join(electronDir, "dist", platformPath)];
if (hostPlatform === "darwin") {
paths.push(
NodePath.join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
NodePath.join(
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
join(
electronDir,
"dist",
"Electron.app",
@@ -68,7 +66,7 @@ function isMachO(filePath) {
return true;
}
const result = NodeChildProcess.spawnSync("file", ["-b", filePath], {
const result = spawnSync("file", ["-b", filePath], {
encoding: "utf8",
});
@@ -77,7 +75,7 @@ function isMachO(filePath) {
function missingRuntimePaths(electronDir, platformPath) {
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
return !NodeFS.existsSync(runtimePath);
return !existsSync(runtimePath);
});
}
@@ -87,8 +85,8 @@ function invalidRuntimePaths(electronDir, platformPath) {
}
return [
NodePath.join(electronDir, "dist", platformPath),
NodePath.join(
join(electronDir, "dist", platformPath),
join(
electronDir,
"dist",
"Electron.app",
@@ -97,11 +95,11 @@ function invalidRuntimePaths(electronDir, platformPath) {
"Electron Framework.framework",
"Electron Framework",
),
].filter((runtimePath) => NodeFS.existsSync(runtimePath) && !isMachO(runtimePath));
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
}
function runChecked(command, args) {
const result = NodeChildProcess.spawnSync(command, args, {
const result = spawnSync(command, args, {
encoding: "utf8",
stdio: "inherit",
});
@@ -116,8 +114,8 @@ function runChecked(command, args) {
}
function installElectronRuntime(electronDir, version) {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-"));
const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
try {
runChecked("curl", [
@@ -127,34 +125,34 @@ function installElectronRuntime(electronDir, version) {
zipPath,
]);
if (hostPlatform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, NodePath.join(electronDir, "dist")]);
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
} else {
runChecked("python3", [
"-c",
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
zipPath,
NodePath.join(electronDir, "dist"),
join(electronDir, "dist"),
]);
}
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
rmSync(tempDir, { recursive: true, force: true });
}
}
export function ensureElectronRuntime() {
const electronPackageJsonPath = require.resolve("electron/package.json");
const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = NodePath.dirname(electronPackageJsonPath);
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = dirname(electronPackageJsonPath);
const platformPath = getPlatformPath();
const electronPath = NodePath.join(electronDir, "dist", platformPath);
const electronPath = join(electronDir, "dist", platformPath);
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) {
NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true });
if (existsSync(join(electronDir, "dist"))) {
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
}
NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true });
rmSync(join(electronDir, "path.txt"), { force: true });
installElectronRuntime(electronDir, electronPackageJson.version);
}
+7 -7
View File
@@ -1,16 +1,16 @@
import * as NodeChildProcess from "node:child_process";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const desktopDir = NodePath.resolve(__dirname, "..");
const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test...");
const electronCommand = resolveElectronLaunchCommand([mainJs]);
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
const child = spawn(electronCommand.electronPath, electronCommand.args, {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
+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";
@@ -6,7 +6,7 @@ const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
const child = spawn(electronCommand.electronPath, electronCommand.args, {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+8 -8
View File
@@ -1,13 +1,13 @@
import * as NodeFSP from "node:fs/promises";
import * as NodeNet from "node:net";
import * as NodePath from "node:path";
import * as NodeTimersPromises from "node:timers/promises";
import * as FileSystem from "node:fs/promises";
import * as Net from "node:net";
import * as Path from "node:path";
import * as Timers from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) {
try {
await NodeFSP.access(filePath);
await FileSystem.access(filePath);
return true;
} catch {
return false;
@@ -16,7 +16,7 @@ async function fileExists(filePath) {
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => {
const socket = NodeNet.createConnection({ host, port });
const socket = Net.createConnection({ host, port });
let settled = false;
const finish = (ready) => {
@@ -47,7 +47,7 @@ async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, conn
const pendingFiles = [];
for (const relativeFilePath of files) {
const ready = await fileExists(NodePath.resolve(baseDir, relativeFilePath));
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
if (!ready) {
pendingFiles.push(relativeFilePath);
}
@@ -114,6 +114,6 @@ export async function waitForResources({
);
}
await NodeTimersPromises.setTimeout(intervalMs);
await Timers.setTimeout(intervalMs);
}
}
+8 -17
View File
@@ -11,13 +11,12 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.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 DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
@@ -101,12 +100,12 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
): Effect.fn.Return<
void,
never,
| DesktopShutdown.DesktopShutdown
| DesktopLifecycle.DesktopShutdown
| DesktopState.DesktopState
| ElectronApp.ElectronApp
| ElectronDialog.ElectronDialog
> {
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const state = yield* DesktopState.DesktopState;
const electronApp = yield* ElectronApp.ElectronApp;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -164,16 +163,6 @@ const bootstrap = Effect.gen(function* () {
}
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
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", {
baseUrl: backendConfig.httpBaseUrl.href,
});
@@ -200,8 +189,9 @@ const startup = Effect.gen(function* () {
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const clerk = yield* DesktopClerk.DesktopClerk;
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const updates = yield* DesktopUpdates.DesktopUpdates;
@@ -219,7 +209,7 @@ const startup = Effect.gen(function* () {
yield* appIdentity.configure;
yield* lifecycle.register;
yield* clerk.configure;
yield* cloudAuth.configure;
yield* electronApp.whenReady.pipe(
Effect.withSpan("desktop.electron.whenReady"),
@@ -228,6 +218,7 @@ const startup = Effect.gen(function* () {
yield* logStartupInfo("app ready");
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* electronProtocol.registerDesktopFileProtocol;
yield* updates.configure;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
@@ -238,7 +229,7 @@ const scopedProgram = Effect.scoped(
yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
yield* Effect.addFinalizer(() =>
@@ -63,7 +63,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}),
appendCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
} satisfies ElectronApp.ElectronAppShape);
const makeAssetsLayer = (png: Option.Option<string>) =>
Layer.succeed(DesktopAssets.DesktopAssets, {
@@ -73,7 +73,7 @@ const makeAssetsLayer = (png: Option.Option<string>) =>
png,
}),
resolveResourcePath: () => Effect.succeed(Option.none()),
} satisfies DesktopAssets.DesktopAssets["Service"]);
} satisfies DesktopAssets.DesktopAssetsShape);
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
const { env, ...environmentOverrides } = overrides;
+6 -4
View File
@@ -18,12 +18,14 @@ const AppPackageMetadata = Schema.Struct({
});
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
export interface DesktopAppIdentityShape {
readonly resolveUserDataPath: Effect.Effect<string>;
readonly configure: Effect.Effect<void>;
}
export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity,
{
readonly resolveUserDataPath: Effect.Effect<string>;
readonly configure: Effect.Effect<void>;
}
DesktopAppIdentityShape
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
const normalizeCommitHash = (value: string): Option.Option<string> => {
+8 -7
View File
@@ -12,13 +12,14 @@ export interface DesktopIconPaths {
readonly png: Option.Option<string>;
}
export class DesktopAssets extends Context.Service<
DesktopAssets,
{
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/app/DesktopAssets") {}
export interface DesktopAssetsShape {
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
}
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
"@t3tools/desktop/app/DesktopAssets",
) {}
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
fileName: string,
@@ -1,280 +0,0 @@
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
}
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
{
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
const DesktopBackendChildLogRecord = Schema.Struct({
message: Schema.String,
level: Schema.Literals(["INFO", "ERROR"]),
timestamp: Schema.String,
annotations: Schema.Record(Schema.String, Schema.Unknown),
spans: Schema.Record(Schema.String, Schema.Unknown),
fiberId: Schema.String,
});
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
Schema.fromJsonString(DesktopBackendChildLogRecord),
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
};
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
});
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, never> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.orElseSucceed(() => 0),
);
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes?: number;
readonly maxFiles?: number;
}): Effect.fn.Return<
RotatingLogFileWriter,
DesktopLogFileWriterError,
FileSystem.FileSystem | Path.Path
> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
const directory = path.dirname(input.filePath);
const baseName = path.basename(input.filePath);
if (maxBytes < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxBytes",
value: maxBytes,
});
}
if (maxFiles < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxFiles",
value: maxFiles,
});
}
yield* fileSystem.makeDirectory(directory, { recursive: true });
const withSuffix = (index: number) => `${input.filePath}.${index}`;
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem
.exists(input.filePath)
.pipe(Effect.orElseSucceed(() => false));
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
if (chunk.byteLength === 0) return Effect.void;
return mutex.withPermits(1)(
Effect.gen(function* () {
const beforeSize = yield* Ref.get(currentSize);
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
yield* rotate;
}
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
yield* Ref.set(currentSize, afterSize);
if (afterSize > maxBytes) {
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
),
);
};
yield* pruneOverflowBackups;
return {
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
});
const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.sync(() => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
}).pipe(Effect.ignore);
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
function* (
logFile: RotatingLogFileWriter,
input: {
readonly message: string;
readonly level: "INFO" | "ERROR";
readonly annotations: Record<string, unknown>;
},
): Effect.fn.Return<void> {
return yield* Effect.gen(function* () {
const timestamp = DateTime.formatIso(yield* DateTime.now);
const encoded = yield* encodeDesktopBackendChildLogRecord({
message: input.message,
level: input.level,
timestamp,
annotations: input.annotations,
spans: {},
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
});
yield* logFile.writeText(`${encoded}\n`);
}).pipe(Effect.ignore({ log: true }));
},
);
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
const service = Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
function* ({ phase, details }) {
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
annotations: {
component: "desktop-backend-child",
runId,
phase,
details: sanitizeLogValue(details),
},
});
},
),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId,
stream: streamName,
text: textDecoder.decode(chunk),
},
});
},
),
}) satisfies DesktopBackendOutputLog["Service"],
});
return DesktopBackendOutputLog.of(service);
});
export const layer = Layer.effect(DesktopBackendOutputLog, make);
-94
View File
@@ -1,94 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { 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";
describe("DesktopClerk", () => {
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
assert.equal(
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
"clerk.t3.codes",
);
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
});
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment: true,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
return Effect.gen(function* () {
yield* Effect.scoped(
Layer.build(
DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
),
),
);
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.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();
});
});
-91
View File
@@ -1,91 +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 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 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,
},
});
}
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
(bridge) => Effect.sync(() => bridge.cleanup()),
);
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"),
),
});
}),
);
@@ -21,6 +21,7 @@ const textEncoder = new TextEncoder();
const decodeConnectionCatalog = Schema.decodeEffect(
Schema.fromJsonString(ConnectionCatalogDocument),
);
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
@@ -39,7 +40,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
return decoded.slice("encrypted:".length);
});
},
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(
@@ -235,10 +236,8 @@ describe("DesktopConnectionCatalogStore", () => {
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
}),
),
@@ -254,7 +253,7 @@ describe("DesktopConnectionCatalogStore", () => {
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
pathOrDescriptor: `${baseDir}/connection-catalog.json`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
@@ -271,113 +270,10 @@ describe("DesktopConnectionCatalogStore", () => {
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
);
assert.notEqual(error.message, permissionError.message);
assert.equal(error.cause, permissionError);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("reports the failed catalog write operation and path", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: `${baseDir}/userdata`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
makeDirectory: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.set("{}").pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
);
assert.equal(error.operation, "create-directory");
assert.equal(error.path, `${baseDir}/userdata`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("reports the legacy migration stage", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError,
);
assert.equal(error.operation, "read-legacy-registry");
assert.equal(error.catalogPath, `${environment.stateDir}/connection-catalog.json`);
assert.instanceOf(
error.cause,
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
);
const registryError =
error.cause as DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError;
assert.exists(registryError.cause);
assert.equal(
error.message,
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${environment.stateDir}/connection-catalog.json.`,
);
assert.notEqual(error.message, registryError.message);
}),
),
);
it.effect("reports invalid encrypted catalog data without exposing it", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n');
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError,
);
assert.equal(error.resource, "encryptedCatalog");
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
assert.equal(
error.message,
`Failed to decode encryptedCatalog for the desktop connection catalog at ${catalogPath}.`,
);
assert.notInclude(error.message, "%%%");
}),
),
);
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -14,12 +14,14 @@ import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
@@ -46,149 +48,76 @@ const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"create-temporary-file-name",
"encode-document",
"create-directory",
"write-temporary-file",
"replace-catalog-file",
]);
type DesktopConnectionCatalogStoreWriteOperation =
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"read-legacy-registry",
"read-legacy-secret",
"encode-catalog",
"persist-catalog",
]);
type DesktopConnectionCatalogStoreMigrationOperation =
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
"DesktopConnectionCatalogStoreWriteError",
{
operation: DesktopConnectionCatalogStoreWriteOperation,
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop connection catalog: ${this.cause.message}`;
}
}
const writeError = (
operation: DesktopConnectionCatalogStoreWriteOperation,
path: string,
cause: unknown,
): DesktopConnectionCatalogStoreWriteError =>
new DesktopConnectionCatalogStoreWriteError({
operation,
path,
cause,
});
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
"DesktopConnectionCatalogStoreDecodeError",
{
resource: Schema.Literal("encryptedCatalog"),
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode the desktop connection catalog.";
}
}
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
"DesktopConnectionCatalogStoreReadError",
{
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDocumentDecodeError>()(
"DesktopConnectionCatalogStoreDocumentDecodeError",
{
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreMigrationError>()(
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
"DesktopConnectionCatalogStoreMigrationError",
{
operation: DesktopConnectionCatalogStoreMigrationOperation,
catalogPath: Schema.String,
environmentId: Schema.optionalKey(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const environment =
this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to migrate legacy desktop saved environments.";
}
}
const migrationError = (
operation: DesktopConnectionCatalogStoreMigrationOperation,
catalogPath: string,
cause: unknown,
environmentId?: string,
): DesktopConnectionCatalogStoreMigrationError =>
new DesktopConnectionCatalogStoreMigrationError({
operation,
catalogPath,
...(environmentId === undefined ? {} : { environmentId }),
cause,
});
export interface DesktopConnectionCatalogStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
| DesktopConnectionCatalogStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
{
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDocumentDecodeError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| ElectronSafeStorage.ElectronSafeStorageError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
>;
readonly clear: Effect.Effect<void>;
}
DesktopConnectionCatalogStoreShape
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
function decodeSecretBytes(
catalogPath: string,
encoded: string,
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreDecodeError({
resource: "encryptedCatalog",
catalogPath,
cause,
}),
),
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
);
}
@@ -197,32 +126,16 @@ const readDocument = (
catalogPath: string,
): Effect.Effect<
Option.Option<EncryptedConnectionCatalogDocument>,
DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
PlatformError.PlatformError | Schema.SchemaError
> =>
fileSystem.readFileString(catalogPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound"
? Effect.succeed<string | null>(null)
: Effect.fail(
new DesktopConnectionCatalogStoreReadError({
catalogPath,
cause: error,
}),
),
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(
Effect.map(Option.some),
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreDocumentDecodeError({
catalogPath,
cause,
}),
),
),
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
),
);
@@ -232,24 +145,14 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
readonly catalogPath: string;
readonly document: EncryptedConnectionCatalogDocument;
readonly suffix: string;
}): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
Effect.mapError((cause) => writeError("encode-document", input.catalogPath, cause)),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* Effect.gen(function* () {
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.catalogPath)
.pipe(
Effect.mapError((cause) => writeError("replace-catalog-file", input.catalogPath, cause)),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.catalogPath);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
@@ -272,11 +175,10 @@ const migrateSavedEnvironmentRecords = Effect.fn(
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
)(function* (
records: readonly PersistedSavedEnvironmentRecord[],
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
catalogPath: string,
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironmentsShape,
): Effect.fn.Return<
RuntimeConnectionCatalogDocumentType,
DesktopConnectionCatalogStoreMigrationError
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
> {
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
@@ -330,13 +232,7 @@ const migrateSavedEnvironmentRecords = Effect.fn(
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments
.getSecret(record.environmentId)
.pipe(
Effect.mapError((cause) =>
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
),
);
const token = yield* savedEnvironments.getSecret(record.environmentId);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
@@ -354,82 +250,83 @@ const migrateSavedEnvironmentRecords = Effect.fn(
};
});
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
export const layer = Layer.effect(
DesktopConnectionCatalogStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
});
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry.pipe(
Effect.mapError((cause) => migrationError("read-legacy-registry", catalogPath, cause)),
);
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
Effect.mapError((cause) => migrationError("encode-catalog", catalogPath, cause)),
);
yield* writeCatalog(encoded).pipe(
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
);
return Option.some(encoded);
});
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath);
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
Effect.flatMap(safeStorage.decryptString),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
const records = yield* savedEnvironments.getRegistry;
if (records.length === 0) {
return Option.none<string>();
}
yield* writeCatalog(catalog);
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
error,
}),
),
Effect.withSpan("desktop.connectionCatalogStore.clear"),
),
});
});
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
yield* writeCatalog(encoded);
return Option.some(encoded);
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
export const layer = Layer.effect(DesktopConnectionCatalogStore, make);
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
);
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* safeStorage.isEncryptionAvailable)) {
return yield* new ElectronSafeStorage.ElectronSafeStorageAvailabilityError({
cause: new Error(
"Safe storage encryption is unavailable; cannot decrypt the existing connection catalog",
),
});
}
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
Effect.flatMap(safeStorage.decryptString),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
error,
}),
),
Effect.withSpan("desktop.connectionCatalogStore.clear"),
),
});
}),
);
+55 -50
View File
@@ -11,7 +11,10 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import {
type DesktopSettings,
resolveDefaultDesktopSettings,
} from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
@@ -27,53 +30,55 @@ export interface MakeDesktopEnvironmentInput {
readonly runningUnderArm64Translation: boolean;
}
export interface DesktopEnvironmentShape {
readonly path: Path.Path;
readonly dirname: string;
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly isPackaged: boolean;
readonly isDevelopment: boolean;
readonly appVersion: string;
readonly appPath: string;
readonly resourcesPath: string;
readonly homeDirectory: string;
readonly appDataDirectory: string;
readonly baseDir: string;
readonly stateDir: string;
readonly desktopSettingsPath: string;
readonly clientSettingsPath: string;
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
readonly appUpdateYmlPath: string;
readonly devServerUrl: Option.Option<URL>;
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
readonly configuredBackendPort: Option.Option<number>;
readonly commitHashOverride: Option.Option<string>;
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpExportIntervalMs: number;
readonly branding: DesktopAppBranding;
readonly displayName: string;
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
export class DesktopEnvironment extends Context.Service<
DesktopEnvironment,
{
readonly path: Path.Path;
readonly dirname: string;
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly isPackaged: boolean;
readonly isDevelopment: boolean;
readonly appVersion: string;
readonly appPath: string;
readonly resourcesPath: string;
readonly homeDirectory: string;
readonly appDataDirectory: string;
readonly baseDir: string;
readonly stateDir: string;
readonly desktopSettingsPath: string;
readonly clientSettingsPath: string;
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
readonly appUpdateYmlPath: string;
readonly devServerUrl: Option.Option<URL>;
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
readonly configuredBackendPort: Option.Option<number>;
readonly commitHashOverride: Option.Option<string>;
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpExportIntervalMs: number;
readonly branding: DesktopAppBranding;
readonly displayName: string;
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
DesktopEnvironmentShape
>()("@t3tools/desktop/app/DesktopEnvironment") {}
const APP_BASE_NAME = "T3 Code";
@@ -131,9 +136,9 @@ function resolveDesktopRuntimeInfo(input: {
};
}
const make = Effect.fn("desktop.environment.make")(function* (
const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
input: MakeDesktopEnvironmentInput,
): Effect.fn.Return<DesktopEnvironment["Service"], Config.ConfigError, Path.Path> {
): Effect.fn.Return<DesktopEnvironmentShape, Config.ConfigError, Path.Path> {
const path = yield* Path.Path;
const config = yield* DesktopConfig.DesktopConfig;
const homeDirectory = input.homeDirectory;
@@ -203,7 +208,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
userDataDirName,
legacyUserDataDirName,
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
runtimeInfo: resolveDesktopRuntimeInfo({
platform: input.platform,
processArch: input.processArch,
@@ -245,4 +250,4 @@ const make = Effect.fn("desktop.environment.make")(function* (
});
export const layer = (input: MakeDesktopEnvironmentInput) =>
Layer.effect(DesktopEnvironment, make(input));
Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
+125 -92
View File
@@ -1,6 +1,7 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
@@ -8,36 +9,67 @@ import * as Scope from "effect/Scope";
import type * as Electron from "electron";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
export interface DesktopShutdownShape {
readonly request: Effect.Effect<void>;
readonly awaitRequest: Effect.Effect<void>;
readonly markComplete: Effect.Effect<void>;
readonly awaitComplete: Effect.Effect<void>;
readonly isComplete: Effect.Effect<boolean>;
}
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
) {}
const makeShutdown = Effect.gen(function* () {
const requested = yield* Deferred.make<void>();
const completed = yield* Deferred.make<void>();
const completedRef = yield* Ref.make(false);
return DesktopShutdown.of({
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
awaitRequest: Deferred.await(requested),
markComplete: Ref.set(completedRef, true).pipe(
Effect.andThen(Deferred.succeed(completed, undefined)),
Effect.asVoid,
),
awaitComplete: Deferred.await(completed),
isComplete: Ref.get(completedRef),
});
});
export const layerShutdown = Layer.effect(DesktopShutdown, makeShutdown);
export type DesktopLifecycleRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopShutdown.DesktopShutdown
| DesktopShutdown
| DesktopState.DesktopState
| DesktopWindow.DesktopWindow
| ElectronApp.ElectronApp
| ElectronTheme.ElectronTheme;
export interface DesktopLifecycleShape {
readonly relaunch: (
reason: string,
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
/**
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
*/
export class DesktopLifecycle extends Context.Service<
DesktopLifecycle,
{
readonly relaunch: (
reason: string,
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
>()("@t3tools/desktop/app/DesktopLifecycle") {}
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
"@t3tools/desktop/app/DesktopLifecycle",
) {}
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
makeComponentLogger("desktop-lifecycle");
DesktopObservability.makeComponentLogger("desktop-lifecycle");
function addScopedListener<Args extends ReadonlyArray<unknown>>(
target: unknown,
@@ -61,8 +93,8 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
}
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
const shutdown = yield* DesktopShutdown.DesktopShutdown;
function* (): Effect.fn.Return<void, never, DesktopShutdown> {
const shutdown = yield* DesktopShutdown;
yield* shutdown.request;
yield* shutdown.awaitComplete;
},
@@ -122,82 +154,83 @@ function quitFromSignal(
);
}
export const make = DesktopLifecycle.of({
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const state = yield* DesktopState.DesktopState;
yield* logLifecycleInfo("desktop relaunch requested", { reason });
yield* Effect.gen(function* () {
yield* Effect.yieldNow;
yield* Ref.set(state.quitting, true);
yield* requestDesktopShutdownAndWait();
if (environment.isDevelopment) {
yield* electronApp.exit(75);
return;
export const layer = Layer.succeed(
DesktopLifecycle,
DesktopLifecycle.of({
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const state = yield* DesktopState.DesktopState;
yield* logLifecycleInfo("desktop relaunch requested", { reason });
yield* Effect.gen(function* () {
yield* Effect.yieldNow;
yield* Ref.set(state.quitting, true);
yield* requestDesktopShutdownAndWait();
if (environment.isDevelopment) {
yield* electronApp.exit(75);
return;
}
yield* electronApp.relaunch({
execPath: process.execPath,
args: process.argv.slice(1),
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) =>
logLifecycleError("desktop relaunch failed", {
cause: Cause.pretty(cause),
}),
),
Effect.forkDetach,
Effect.asVoid,
);
}),
register: Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronApp = yield* ElectronApp.ElectronApp;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed,
() => {
quitAllowed = true;
},
);
});
yield* electronApp.on("activate", () => {
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
});
yield* electronApp.on("window-all-closed", () => {
void runEffect(
Effect.gen(function* () {
const app = yield* ElectronApp.ElectronApp;
const state = yield* DesktopState.DesktopState;
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
yield* app.quit;
}
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
);
});
if (environment.platform !== "win32") {
yield* addScopedListener(process, "SIGINT", () => {
quitFromSignal("SIGINT", runEffect);
});
yield* addScopedListener(process, "SIGTERM", () => {
quitFromSignal("SIGTERM", runEffect);
});
}
yield* electronApp.relaunch({
execPath: process.execPath,
args: process.argv.slice(1),
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) =>
logLifecycleError("desktop relaunch failed", {
cause: Cause.pretty(cause),
}),
),
Effect.forkDetach,
Effect.asVoid,
);
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
}),
register: Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronApp = yield* ElectronApp.ElectronApp;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed,
() => {
quitAllowed = true;
},
);
});
yield* electronApp.on("activate", () => {
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
});
yield* electronApp.on("window-all-closed", () => {
void runEffect(
Effect.gen(function* () {
const app = yield* ElectronApp.ElectronApp;
const state = yield* DesktopState.DesktopState;
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
yield* app.quit;
}
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
);
});
if (environment.platform !== "win32") {
yield* addScopedListener(process, "SIGINT", () => {
quitFromSignal("SIGINT", runEffect);
});
yield* addScopedListener(process, "SIGTERM", () => {
quitFromSignal("SIGTERM", runEffect);
});
}
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
});
export const layer = Layer.succeed(DesktopLifecycle, make);
);
+282 -8
View File
@@ -1,20 +1,52 @@
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Tracer from "effect/Tracer";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
export interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
}
export interface DesktopBackendOutputLogShape {
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
}
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
DesktopBackendOutputLogShape
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
export type DesktopLogAnnotations = Record<string, unknown>;
@@ -50,7 +82,165 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
};
}
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
class DesktopLogFileWriterConfigurationError extends Data.TaggedError(
"DesktopLogFileWriterConfigurationError",
)<{
readonly option: "maxBytes" | "maxFiles";
readonly value: number;
}> {
override get message() {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
const DesktopBackendChildLogRecord = Schema.Struct({
message: Schema.String,
level: Schema.Literals(["INFO", "ERROR"]),
timestamp: Schema.String,
annotations: Schema.Record(Schema.String, Schema.Unknown),
spans: Schema.Record(Schema.String, Schema.Unknown),
fiberId: Schema.String,
});
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
Schema.fromJsonString(DesktopBackendChildLogRecord),
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
};
const currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
});
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, never> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.orElseSucceed(() => 0),
);
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes?: number;
readonly maxFiles?: number;
}): Effect.fn.Return<
RotatingLogFileWriter,
DesktopLogFileWriterError,
FileSystem.FileSystem | Path.Path
> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
const directory = path.dirname(input.filePath);
const baseName = path.basename(input.filePath);
if (maxBytes < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxBytes",
value: maxBytes,
});
}
if (maxFiles < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxFiles",
value: maxFiles,
});
}
yield* fileSystem.makeDirectory(directory, { recursive: true });
const withSuffix = (index: number) => `${input.filePath}.${index}`;
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem
.exists(input.filePath)
.pipe(Effect.orElseSucceed(() => false));
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
if (chunk.byteLength === 0) return Effect.void;
return mutex.withPermits(1)(
Effect.gen(function* () {
const beforeSize = yield* Ref.get(currentSize);
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
yield* rotate;
}
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
yield* Ref.set(currentSize, afterSize);
if (afterSize > maxBytes) {
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
),
);
};
yield* pruneOverflowBackups;
return {
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
});
const readPersistedOtlpTracesUrl: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
@@ -70,6 +260,90 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
return yield* readPersistedOtlpTracesUrl;
});
const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.sync(() => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
}).pipe(Effect.ignore);
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
function* (
logFile: RotatingLogFileWriter,
input: {
readonly message: string;
readonly level: "INFO" | "ERROR";
readonly annotations: Record<string, unknown>;
},
): Effect.fn.Return<void> {
return yield* Effect.gen(function* () {
const timestamp = DateTime.formatIso(yield* DateTime.now);
const encoded = yield* encodeDesktopBackendChildLogRecord({
message: input.message,
level: input.level,
timestamp,
annotations: input.annotations,
spans: {},
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
});
yield* logFile.writeText(`${encoded}\n`);
}).pipe(Effect.ignore({ log: true }));
},
);
const backendOutputLogLayer = Layer.effect(
DesktopBackendOutputLog,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
return Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn(
"desktop.observability.backendOutput.writeSessionBoundary",
)(function* ({ phase, details }) {
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
annotations: {
component: "desktop-backend-child",
runId,
phase,
details: sanitizeLogValue(details),
},
});
}),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId,
stream: streamName,
text: textDecoder.decode(chunk),
},
});
},
),
}) satisfies DesktopBackendOutputLogShape,
});
}),
);
const desktopLoggerLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"),
@@ -82,8 +356,8 @@ const tracerLayer = Layer.unwrap(
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
});
const delegate = Option.isNone(otlpTracesUrl)
@@ -101,8 +375,8 @@ const tracerLayer = Layer.unwrap(
});
const tracer = yield* makeLocalFileTracer({
filePath: tracePath,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
sink,
...(delegate ? { delegate } : {}),
@@ -113,7 +387,7 @@ const tracerLayer = Layer.unwrap(
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll(
DesktopBackendOutputLogModule.layer,
backendOutputLogLayer,
desktopLoggerLayer,
tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
-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 Ref from "effect/Ref";
export class DesktopState extends Context.Service<
export interface DesktopStateShape {
readonly backendReady: Ref.Ref<boolean>;
readonly quitting: Ref.Ref<boolean>;
}
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
"@t3tools/desktop/app/DesktopState",
) {}
export const layer = Layer.effect(
DesktopState,
{
readonly backendReady: Ref.Ref<boolean>;
readonly quitting: Ref.Ref<boolean>;
}
>()("@t3tools/desktop/app/DesktopState") {}
const make = Effect.all({
backendReady: Ref.make(false),
quitting: Ref.make(false),
});
export const layer = Layer.effect(DesktopState, make);
Effect.all({
backendReady: Ref.make(false),
quitting: Ref.make(false),
}),
);
@@ -34,7 +34,7 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
} satisfies DesktopServerExposure.DesktopServerExposureShape);
function makeEnvironmentLayer(
baseDir: string,
@@ -14,14 +14,16 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
export interface DesktopBackendConfigurationShape {
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
}
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
{
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
}
DesktopBackendConfigurationShape
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
interface BackendObservabilitySettings {
@@ -54,7 +56,11 @@ const { logWarning: logBackendConfigurationWarning } = DesktopObservability.make
"desktop-backend-configuration",
);
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const readPersistedBackendObservabilitySettings: Effect.Effect<
BackendObservabilitySettings,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const exists = yield* fileSystem
@@ -124,39 +130,40 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
},
);
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const crypto = yield* Crypto.Crypto;
const tokenRef = yield* Ref.make(Option.none<string>());
const getOrCreateBootstrapToken = Effect.gen(function* () {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
export const layer = Layer.effect(
DesktopBackendConfiguration,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const crypto = yield* Crypto.Crypto;
const tokenRef = yield* Ref.make(Option.none<string>());
const getOrCreateBootstrapToken = Effect.gen(function* () {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return yield* resolveBackendStartConfig({
bootstrapToken,
observabilitySettings,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
});
});
export const layer = Layer.effect(DesktopBackendConfiguration, make);
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return yield* resolveBackendStartConfig({
bootstrapToken,
observabilitySettings,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
});
}),
);
@@ -104,9 +104,9 @@ function decodeBootstrap(raw: string) {
function makeManagerLayer(input: {
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
readonly desktopState?: DesktopState.DesktopState["Service"];
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
readonly desktopState?: DesktopState.DesktopStateShape;
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
}) {
return DesktopBackendManager.layer.pipe(
@@ -127,7 +127,7 @@ function makeManagerLayer(input: {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
...input.backendOutputLog,
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected createMain"),
ensureMain: Effect.die("unexpected ensureMain"),
@@ -138,7 +138,7 @@ function makeManagerLayer(input: {
dispatchMenuAction: () => Effect.void,
syncAppearance: Effect.void,
...input.desktopWindow,
} satisfies DesktopWindow.DesktopWindow["Service"]),
} satisfies DesktopWindow.DesktopWindowShape),
),
),
);
@@ -1,5 +1,6 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -15,9 +16,8 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
DesktopBackendBootstrap,
@@ -59,38 +59,29 @@ interface BackendProcessExit {
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
url: Schema.URL,
},
) {
override get message(): string {
export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
readonly url: URL;
}> {
override get message() {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
class BackendProcessBootstrapEncodeError extends Data.TaggedError(
"BackendProcessBootstrapEncodeError",
{
detail: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
)<{
readonly cause: Schema.SchemaError;
}> {
override get message() {
return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
}
}
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
detail: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to spawn desktop backend process: ${this.detail}`;
class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
readonly cause: PlatformError.PlatformError;
}> {
override get message() {
return `Failed to spawn desktop backend process: ${this.cause.message}`;
}
}
@@ -115,14 +106,16 @@ export interface DesktopBackendSnapshot {
readonly restartScheduled: boolean;
}
export interface DesktopBackendManagerShape {
readonly start: Effect.Effect<void>;
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
}
export class DesktopBackendManager extends Context.Service<
DesktopBackendManager,
{
readonly start: Effect.Effect<void>;
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
}
DesktopBackendManagerShape
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
@@ -237,13 +230,7 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError(
(cause) =>
new BackendProcessBootstrapEncodeError({
detail: cause.message,
cause,
}),
),
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
);
const onOutput = options.onOutput ?? (() => Effect.void);
const command = ChildProcess.make(
@@ -269,15 +256,9 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
},
);
const handle = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
detail: cause.message,
cause,
}),
),
);
const handle = yield* spawner
.spawn(command)
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
@@ -296,7 +277,7 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
return describeProcessExit(yield* Effect.result(handle.exitCode));
});
export const make = Effect.gen(function* () {
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
const parentScope = yield* Scope.Scope;
const fileSystem = yield* FileSystem.FileSystem;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
@@ -622,4 +603,4 @@ export const make = Effect.gen(function* () {
});
});
export const layer = Layer.effect(DesktopBackendManager, make);
export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());
@@ -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,33 +0,0 @@
import * as NodeOS from "node:os";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
readonly family: string | number;
readonly internal: boolean;
readonly netmask?: string;
readonly mac?: string;
readonly cidr?: string | null;
readonly scopeid?: number;
}
export type NetworkInterfaces = Readonly<
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
>;
export class DesktopNetworkInterfaces extends Context.Service<
DesktopNetworkInterfaces,
{
readonly read: Effect.Effect<NetworkInterfaces>;
}
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
export const make = (): DesktopNetworkInterfaces["Service"] =>
DesktopNetworkInterfaces.of({
read: Effect.sync(() => NodeOS.networkInterfaces()),
});
export const layer = Layer.succeed(DesktopNetworkInterfaces, make());
@@ -7,18 +7,21 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import {
DesktopEnvironment,
layer as makeDesktopEnvironmentLayer,
} from "../app/DesktopEnvironment.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
const encoder = new TextEncoder();
const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {};
const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
const emptyNetworkInterfaces: DesktopNetworkInterfaces = {};
const lanNetworkInterfaces: DesktopNetworkInterfaces = {
en0: [
{
address: "192.168.1.20",
@@ -28,7 +31,7 @@ const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
],
};
const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
tailscale0: [
{
address: "100.90.1.2",
@@ -69,7 +72,7 @@ function dieOnSpawnLayer() {
}
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
return DesktopEnvironment.layer({
return makeDesktopEnvironmentLayer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
@@ -88,13 +91,13 @@ function makeEnvironmentLayer(baseDir: string, env: Record<string, string | unde
function makeLayer(input: {
readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
readonly networkInterfaces?: DesktopNetworkInterfaces;
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
const networkLayer = Layer.succeed(DesktopNetworkInterfaces.DesktopNetworkInterfaces, {
const networkLayer = Layer.succeed(DesktopServerExposure.DesktopNetworkInterfacesService, {
read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
});
@@ -110,12 +113,12 @@ function makeLayer(input: {
}
const withHarness = <A, E, R>(
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
networkInterfaces: DesktopNetworkInterfaces,
effect: Effect.Effect<
A,
E,
| R
| DesktopEnvironment.DesktopEnvironment
| DesktopEnvironment
| FileSystem.FileSystem
| DesktopServerExposure.DesktopServerExposure
| DesktopAppSettings.DesktopAppSettings
@@ -1,3 +1,5 @@
import * as NodeOS from "node:os";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
@@ -8,27 +10,41 @@ import type {
DesktopServerExposureMode,
DesktopServerExposureState,
} from "@t3tools/contracts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
readonly family: string | number;
readonly internal: boolean;
readonly netmask?: string;
readonly mac?: string;
readonly cidr?: string | null;
readonly scopeid?: number;
}
export type DesktopNetworkInterfaces = Readonly<
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
>;
interface ResolvedDesktopServerExposure {
readonly mode: DesktopServerExposureMode;
readonly bindHost: string;
@@ -75,7 +91,7 @@ const isHttpsEndpointUrl = (value: string): boolean => {
};
const resolveLanAdvertisedHost = (
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
networkInterfaces: DesktopNetworkInterfaces,
explicitHost: string | undefined,
): string | null => {
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
@@ -100,7 +116,7 @@ const resolveLanAdvertisedHost = (
const resolveDesktopServerExposure = (input: {
readonly mode: DesktopServerExposureMode;
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly advertisedHostOverride?: string;
}): ResolvedDesktopServerExposure => {
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
@@ -202,25 +218,25 @@ const resolveDesktopCoreAdvertisedEndpoints = (
return endpoints;
};
export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErrorClass<DesktopServerExposureNoNetworkAddressError>()(
type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
"DesktopServerExposureNoNetworkAddressError",
{
port: Schema.Number,
},
) {
override get message(): string {
)<{
readonly port: number;
}> {
override get message() {
return `No reachable network address is available for desktop network access on port ${this.port}.`;
}
}
export class DesktopServerExposurePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposurePersistenceError>()(
export class DesktopServerExposurePersistenceError extends Data.TaggedError(
"DesktopServerExposurePersistenceError",
{
operation: Schema.Literals(["server-exposure-mode", "tailscale-serve"]),
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
)<{
readonly operation: DesktopServerExposurePersistenceOperation;
readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
}> {
override get message() {
return `Failed to persist desktop ${this.operation} settings.`;
}
}
@@ -244,25 +260,36 @@ export interface DesktopServerExposureChange {
readonly requiresRelaunch: boolean;
}
export interface DesktopServerExposureShape {
readonly getState: Effect.Effect<DesktopServerExposureState>;
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
readonly configureFromSettings: (input: {
readonly port: number;
}) => Effect.Effect<DesktopServerExposureState>;
readonly setMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
export class DesktopServerExposure extends Context.Service<
DesktopServerExposure,
{
readonly getState: Effect.Effect<DesktopServerExposureState>;
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
readonly configureFromSettings: (input: {
readonly port: number;
}) => Effect.Effect<DesktopServerExposureState>;
readonly setMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
DesktopServerExposureShape
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
export interface DesktopNetworkInterfacesServiceShape {
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
}
export class DesktopNetworkInterfacesService extends Context.Service<
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesServiceShape
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
interface RuntimeState {
readonly requestedMode: DesktopServerExposureMode;
readonly mode: DesktopServerExposureMode;
@@ -284,10 +311,10 @@ interface ResolvedRuntimeState {
const initialRuntimeState = (): RuntimeState =>
runtimeStateFromResolvedExposure({
requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
settings: DEFAULT_DESKTOP_SETTINGS,
exposure: resolveDesktopServerExposure({
mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
port: 0,
networkInterfaces: {},
}),
@@ -321,7 +348,7 @@ const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure
function runtimeStateFromResolvedExposure(input: {
readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopAppSettings.DesktopSettings;
readonly settings: DesktopSettings;
readonly exposure: ResolvedDesktopServerExposure;
readonly port: number;
}): RuntimeState {
@@ -342,9 +369,9 @@ function runtimeStateFromResolvedExposure(input: {
function resolveRuntimeState(input: {
readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopAppSettings.DesktopSettings;
readonly settings: DesktopSettings;
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly advertisedHostOverride: Option.Option<string>;
}): ResolvedRuntimeState {
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
@@ -381,12 +408,12 @@ const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): bo
previous.bindHost !== next.bindHost ||
previous.localHttpUrl !== next.localHttpUrl;
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
const networkInterfaces = yield* DesktopNetworkInterfacesService;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
const stateRef = yield* Ref.make(initialRuntimeState());
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
@@ -537,3 +564,10 @@ export const make = Effect.gen(function* () {
});
export const layer = Layer.effect(DesktopServerExposure, make);
export const networkInterfacesLayer = Layer.succeed(
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesService.of({
read: Effect.sync(() => NodeOS.networkInterfaces()),
}),
);
@@ -9,10 +9,10 @@ import {
} from "@t3tools/tailscale";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
@@ -25,7 +25,7 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
function resolveTailscaleIpAdvertisedEndpoints(input: {
readonly port: number;
readonly networkInterfaces: NetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces;
}): readonly AdvertisedEndpoint[] {
const seen = new Set<string>();
const endpoints: AdvertisedEndpoint[] = [];
@@ -103,7 +103,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
readonly port: number;
readonly serveEnabled?: boolean;
readonly servePort?: number;
readonly networkInterfaces: NetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly statusJson?: string | null;
readonly readMagicDnsName?: Effect.Effect<
string | null,
+36 -35
View File
@@ -13,40 +13,41 @@ export interface ElectronAppMetadata {
readonly runningUnderArm64Translation: boolean;
}
export class ElectronApp extends Context.Service<
ElectronApp,
{
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronApp") {}
export interface ElectronAppShape {
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
"@t3tools/desktop/electron/ElectronApp",
) {}
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
eventName: string,
@@ -62,7 +63,7 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
}),
).pipe(Effect.asVoid);
export const make = ElectronApp.of({
const make = ElectronApp.of({
metadata: Effect.sync(() => ({
appVersion: Electron.app.getVersion(),
appPath: Electron.app.getAppPath(),
+15 -14
View File
@@ -17,21 +17,22 @@ export interface ElectronDialogConfirmInput {
readonly message: string;
}
export class ElectronDialog extends Context.Service<
ElectronDialog,
{
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronDialog") {}
export interface ElectronDialogShape {
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
export const make = ElectronDialog.of({
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
"@t3tools/desktop/electron/ElectronDialog",
) {}
const make = ElectronDialog.of({
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
onNone: () => ({
+115 -113
View File
@@ -1,11 +1,11 @@
import type { ContextMenuItem } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
export interface ElectronMenuPosition {
readonly x: number;
@@ -23,18 +23,19 @@ export interface ElectronMenuTemplateInput {
readonly template: readonly Electron.MenuItemConstructorOptions[];
}
export class ElectronMenu extends Context.Service<
ElectronMenu,
{
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronMenu") {}
export interface ElectronMenuShape {
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
}
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
"@t3tools/desktop/electron/ElectronMenu",
) {}
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
@@ -79,113 +80,114 @@ const normalizePosition = (
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
export const layer = Layer.effect(
ElectronMenu,
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache;
}
try {
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
}
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache;
}
};
try {
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
}
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
return destructiveMenuIconCache;
};
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: Electron.MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children, complete);
} else {
itemOption.click = () => complete(Option.some(item.id));
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (Option.isSome(destructiveIcon)) {
itemOption.icon = destructiveIcon.value;
}
}
template.push(itemOption);
}
return template;
};
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
if (normalizedItems.length === 0) {
resume(Effect.succeed(Option.none()));
return;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
let completed = false;
const complete = (selectedItemId: Option.Option<string>) => {
if (completed) {
const itemOption: Electron.MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children, complete);
} else {
itemOption.click = () => complete(Option.some(item.id));
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (Option.isSome(destructiveIcon)) {
itemOption.icon = destructiveIcon.value;
}
}
template.push(itemOption);
}
return template;
};
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
if (normalizedItems.length === 0) {
resume(Effect.succeed(Option.none()));
return;
}
completed = true;
resume(Effect.succeed(selectedItemId));
};
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
}),
});
});
let completed = false;
const complete = (selectedItemId: Option.Option<string>) => {
if (completed) {
return;
}
completed = true;
resume(Effect.succeed(selectedItemId));
};
export const layer = Layer.effect(ElectronMenu, make);
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
}),
});
}),
);
@@ -1,132 +1,105 @@
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 type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
handleMock: vi.fn(),
netFetchMock: vi.fn(),
unhandleMock: vi.fn(),
}));
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
vi.hoisted(() => ({
registerFileProtocolMock: vi.fn(),
registerSchemesAsPrivilegedMock: vi.fn(),
unregisterProtocolMock: vi.fn(),
}));
vi.mock("electron", () => ({
net: { fetch: netFetchMock },
protocol: { handle: handleMock, unhandle: unhandleMock },
protocol: {
registerFileProtocol: registerFileProtocolMock,
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
unregisterProtocol: unregisterProtocolMock,
},
}));
import * as ElectronProtocol from "./ElectronProtocol.ts";
describe("ElectronProtocol", () => {
beforeEach(() => {
handleMock.mockReset();
netFetchMock.mockReset();
unhandleMock.mockReset();
registerFileProtocolMock.mockReset();
registerSchemesAsPrivilegedMock.mockReset();
unregisterProtocolMock.mockReset();
});
it.effect("proxies the stable renderer origin to the current app server", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock.mockResolvedValue(new Response("ok"));
it("normalizes safe desktop protocol pathnames", () => {
assert.equal(
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
"settings/general",
);
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
});
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:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
);
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");
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
it.effect("registers desktop scheme privileges through a layer", () =>
Effect.scoped(
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
Effect.andThen(
Effect.sync(() => {
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
[
[
{
scheme: "t3",
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
],
],
]);
}),
),
),
),
);
it.effect("rejects custom protocol requests for another host", () =>
it.effect("scopes registered file protocols", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
let capturedHandler:
| ((
request: Electron.ProtocolRequest,
callback: (response: Electron.ProtocolResponse) => void,
) => void)
| undefined;
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
capturedHandler = handler;
return true;
});
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,
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
yield* electronProtocol.registerFileProtocol({
scheme: "t3",
handler: () => Effect.succeed({ path: "/app/index.html" }),
});
assert.isDefined(capturedHandler);
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
resume(Effect.succeed(response)),
);
});
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
}),
);
assert.equal(response.status, 404);
assert.equal(netFetchMock.mock.calls.length, 0);
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)),
);
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
const directives = Object.fromEntries(
policy.split("; ").map((directive) => {
const [name, ...sources] = directive.split(" ");
return [name, sources];
}),
);
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
assert.deepEqual(directives["img-src"], [
"'self'",
"t3code:",
"blob:",
"data:",
"http:",
"https:",
]);
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
});
});
+233 -107
View File
@@ -1,146 +1,272 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export const DESKTOP_HOST = "app";
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
export function getDesktopScheme(isDevelopment: boolean): string {
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
}
export const DESKTOP_SCHEME = "t3";
export function getDesktopOrigin(isDevelopment: boolean): string {
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
}
export function getDesktopUrl(isDevelopment: boolean): string {
return `${getDesktopOrigin(isDevelopment)}/`;
}
export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<ElectronProtocolRegistrationError>()(
export class ElectronProtocolRegistrationError extends Data.TaggedError(
"ElectronProtocolRegistrationError",
{
scheme: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to register ${this.scheme}: protocol.`;
}
}
export interface DesktopProtocolRegistrationInput {
)<{
readonly scheme: string;
readonly targetOrigin: URL;
readonly backendOrigin: URL;
readonly clerkFrontendApiHostname: string | undefined;
readonly cause: unknown;
}> {
override get message() {
return `Failed to register ${this.scheme}: file protocol.`;
}
}
export class ElectronProtocol extends Context.Service<
ElectronProtocol,
{
readonly registerDesktopProtocol: (
input: DesktopProtocolRegistrationInput,
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
"ElectronProtocolStaticBundleMissingError",
)<{}> {
override get message() {
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
}
>()("@t3tools/desktop/electron/ElectronProtocol") {}
}
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
const clerkOrigin = input.clerkFrontendApiHostname
? `https://${input.clerkFrontendApiHostname}`
: undefined;
const scriptSources = [
"'self'",
"'unsafe-inline'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
export interface ElectronProtocolShape {
readonly registerFileProtocol: <E, R>(input: {
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.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"),
];
// The renderer connects directly to user-configured environments in addition to
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
// origins are not known when this response policy is created, so restrict
// connections by the network schemes the client supports instead of by host.
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
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 });
for (const candidate of candidates) {
const hasIndex = yield* fileSystem
.exists(environment.path.join(candidate, "index.html"))
.pipe(Effect.orElseSucceed(() => false));
if (hasIndex) {
return Option.some(candidate);
}
}
return Option.none<string>();
});
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const init: RequestInit = {
method: request.method,
headers: request.headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
function* (
staticRoot: string,
requestUrl: string,
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
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");
}
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
const resolvedPath = environment.path.join(staticRoot, requestedPath);
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;
}
const response = await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
const make = Effect.gen(function* () {
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
function* (input: DesktopProtocolRegistrationInput) {
if (yield* Ref.get(registered)) return;
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
function* <E, R>({
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(
Effect.try({
try: () => {
Electron.protocol.handle(input.scheme, (request) =>
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
const registered = Electron.protocol.registerFileProtocol(
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 }),
}).pipe(Effect.andThen(Ref.set(registered, true))),
catch: (cause) =>
cause instanceof ElectronProtocolRegistrationError
? cause
: new ElectronProtocolRegistrationError({ scheme, cause }),
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
),
),
() =>
Effect.sync(() => {
Electron.protocol.unhandle(input.scheme);
}).pipe(Effect.andThen(Ref.set(registered, false))),
Electron.protocol.unregisterProtocol(scheme);
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => {
const next = new Set(protocols);
next.delete(scheme);
return next;
}),
),
),
);
},
);
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);
@@ -1,69 +1,56 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
const electronSafeStorageErrorFields = {
cause: Schema.Defect(),
};
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
export class ElectronSafeStorageAvailabilityError extends Schema.TaggedErrorClass<ElectronSafeStorageAvailabilityError>()(
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
"ElectronSafeStorageAvailabilityError",
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to check encryption availability.";
}
}
export class ElectronSafeStorageEncryptError extends Schema.TaggedErrorClass<ElectronSafeStorageEncryptError>()(
export class ElectronSafeStorageEncryptError extends Data.TaggedError(
"ElectronSafeStorageEncryptError",
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to encrypt a string.";
}
}
export class ElectronSafeStorageDecryptError extends Schema.TaggedErrorClass<ElectronSafeStorageDecryptError>()(
export class ElectronSafeStorageDecryptError extends Data.TaggedError(
"ElectronSafeStorageDecryptError",
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to decrypt a string.";
}
}
export const ElectronSafeStorageError = Schema.Union([
ElectronSafeStorageAvailabilityError,
ElectronSafeStorageEncryptError,
ElectronSafeStorageDecryptError,
]);
export type ElectronSafeStorageError = typeof ElectronSafeStorageError.Type;
export const isElectronSafeStorageError = Schema.is(ElectronSafeStorageError);
export interface ElectronSafeStorageShape {
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
export class ElectronSafeStorage extends Context.Service<
ElectronSafeStorage,
{
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
ElectronSafeStorageShape
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
export const make = ElectronSafeStorage.of({
const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
+9 -8
View File
@@ -20,15 +20,16 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
}
}
export class ElectronShell extends Context.Service<
ElectronShell,
{
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronShell") {}
export interface ElectronShellShape {
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
export const make = ElectronShell.of({
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
"@t3tools/desktop/electron/ElectronShell",
) {}
const make = ElectronShell.of({
openExternal: (rawUrl) =>
Option.match(parseSafeExternalUrl(rawUrl), {
onNone: () => Effect.succeed(false),
+10 -9
View File
@@ -6,16 +6,17 @@ import * as Scope from "effect/Scope";
import * as Electron from "electron";
export class ElectronTheme extends Context.Service<
ElectronTheme,
{
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronTheme") {}
export interface ElectronThemeShape {
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
export const make = ElectronTheme.of({
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
"@t3tools/desktop/electron/ElectronTheme",
) {}
const make = ElectronTheme.of({
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
setSource: (theme) =>
Effect.suspend(() => {
@@ -73,7 +73,6 @@ describe("ElectronUpdater", () => {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.equal(error.cause, cause);
assert.equal(error.message, "Electron updater failed to check for updates.");
}
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
+46 -57
View File
@@ -1,7 +1,7 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import { autoUpdater } from "electron-updater";
@@ -10,76 +10,67 @@ type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
const electronUpdaterErrorFields = {
cause: Schema.Defect(),
};
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
"ElectronUpdaterCheckForUpdatesError",
{
...electronUpdaterErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to check for updates.";
}
}
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
"ElectronUpdaterDownloadUpdateError",
{
...electronUpdaterErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to download the update.";
}
}
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
"ElectronUpdaterQuitAndInstallError",
{
...electronUpdaterErrorFields,
},
) {
override get message(): string {
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to quit and install the update.";
}
}
export const ElectronUpdaterError = Schema.Union([
ElectronUpdaterCheckForUpdatesError,
ElectronUpdaterDownloadUpdateError,
ElectronUpdaterQuitAndInstallError,
]);
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
export type ElectronUpdaterError =
| ElectronUpdaterCheckForUpdatesError
| ElectronUpdaterDownloadUpdateError
| ElectronUpdaterQuitAndInstallError;
export class ElectronUpdater extends Context.Service<
ElectronUpdater,
{
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronUpdater") {}
export interface ElectronUpdaterShape {
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export const make = ElectronUpdater.of({
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
"@t3tools/desktop/electron/ElectronUpdater",
) {}
export const layer = Layer.succeed(ElectronUpdater, {
setFeedURL: (options) =>
Effect.suspend(() => {
autoUpdater.setFeedURL(options);
@@ -145,6 +136,4 @@ export const make = ElectronUpdater.of({
}),
).pipe(Effect.asVoid);
},
});
export const layer = Layer.succeed(ElectronUpdater, make);
} satisfies ElectronUpdaterShape);
+27 -29
View File
@@ -1,45 +1,43 @@
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
"ElectronWindowCreateError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to create Electron BrowserWindow.";
}
}
export class ElectronWindow extends Context.Service<
ElectronWindow,
{
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
}
>()("@t3tools/desktop/electron/ElectronWindow") {}
export interface ElectronWindowShape {
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
}
export const make = Effect.gen(function* () {
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
"@t3tools/desktop/electron/ElectronWindow",
) {}
const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+13 -15
View File
@@ -1,6 +1,5 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -34,19 +33,20 @@ export interface DesktopSyncIpcMethod<E, R> {
readonly handler: () => Effect.Effect<unknown, E, R>;
}
export class DesktopIpc extends Context.Service<
DesktopIpc,
{
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
}
>()("@t3tools/desktop/ipc/DesktopIpc") {}
export interface DesktopIpcShape {
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
}
export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
"@t3tools/desktop/ipc/DesktopIpc",
) {}
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
DesktopIpc.of({
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
channel,
@@ -97,8 +97,6 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
}),
});
export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
/**
* Convenience helpers for creating IPC methods
*/
+12 -2
View File
@@ -1,6 +1,13 @@
import * as Effect from "effect/Effect";
import * as DesktopIpc from "./DesktopIpc.ts";
import {
clearCloudAuthToken,
createCloudAuthRequest,
fetchCloudAuth,
getCloudAuthToken,
setCloudAuthToken,
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
clearConnectionCatalog,
@@ -33,7 +40,6 @@ import {
import {
confirm,
getAppBranding,
getLocalEnvironmentBearerToken,
getLocalEnvironmentBootstrap,
openExternal,
pickFolder,
@@ -48,7 +54,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
@@ -75,6 +80,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
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(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
+6 -2
View File
@@ -3,6 +3,12 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
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 UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
@@ -12,8 +18,6 @@ export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
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_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
@@ -5,9 +5,9 @@ import * as Schema from "effect/Schema";
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getClientSettings = DesktopIpc.makeIpcMethod({
export const getClientSettings = makeIpcMethod({
channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(ClientSettingsSchema),
@@ -17,7 +17,7 @@ export const getClientSettings = DesktopIpc.makeIpcMethod({
}),
});
export const setClientSettings = DesktopIpc.makeIpcMethod({
export const setClientSettings = makeIpcMethod({
channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
payload: ClientSettingsSchema,
result: Schema.Void,
@@ -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(Object.fromEntries(headers.entries())),
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));
}),
});
@@ -4,9 +4,9 @@ import * as Schema from "effect/Schema";
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
export const getConnectionCatalog = makeIpcMethod({
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
@@ -16,7 +16,7 @@ export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
}),
});
export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
export const setConnectionCatalog = makeIpcMethod({
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
@@ -26,7 +26,7 @@ export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
}),
});
export const clearConnectionCatalog = DesktopIpc.makeIpcMethod({
export const clearConnectionCatalog = makeIpcMethod({
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
+26 -26
View File
@@ -22,12 +22,12 @@ import {
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as NodeURL from "node:url";
import { pathToFileURL } from "node:url";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
for (const window of BrowserWindow.getAllWindows()) {
@@ -52,7 +52,7 @@ export const installPreviewEventForwarding = Effect.fn(
});
});
export const createTab = DesktopIpc.makeIpcMethod({
export const createTab = makeIpcMethod({
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
@@ -62,7 +62,7 @@ export const createTab = DesktopIpc.makeIpcMethod({
}),
});
export const closeTab = DesktopIpc.makeIpcMethod({
export const closeTab = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
@@ -72,7 +72,7 @@ export const closeTab = DesktopIpc.makeIpcMethod({
}),
});
export const registerWebview = DesktopIpc.makeIpcMethod({
export const registerWebview = makeIpcMethod({
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
payload: DesktopPreviewRegisterWebviewInputSchema,
result: Schema.Void,
@@ -82,7 +82,7 @@ export const registerWebview = DesktopIpc.makeIpcMethod({
}),
});
export const navigate = DesktopIpc.makeIpcMethod({
export const navigate = makeIpcMethod({
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
payload: DesktopPreviewNavigateInputSchema,
result: Schema.Void,
@@ -96,11 +96,11 @@ const tabMethod = (
channel: string,
name: string,
invoke: (
manager: PreviewManager.PreviewManager["Service"],
manager: PreviewManager.PreviewManagerShape,
tabId: string,
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
) =>
DesktopIpc.makeIpcMethod({
makeIpcMethod({
channel,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
@@ -166,7 +166,7 @@ export const stopRecording = tabMethod(
(manager, tabId) => manager.stopRecording(tabId),
);
export const clearCookies = DesktopIpc.makeIpcMethod({
export const clearCookies = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
@@ -176,7 +176,7 @@ export const clearCookies = DesktopIpc.makeIpcMethod({
}),
});
export const clearCache = DesktopIpc.makeIpcMethod({
export const clearCache = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
@@ -186,7 +186,7 @@ export const clearCache = DesktopIpc.makeIpcMethod({
}),
});
export const getPreviewConfig = DesktopIpc.makeIpcMethod({
export const getPreviewConfig = makeIpcMethod({
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
payload: DesktopPreviewConfigInputSchema,
result: DesktopPreviewWebviewConfigSchema,
@@ -196,12 +196,12 @@ export const getPreviewConfig = DesktopIpc.makeIpcMethod({
return {
partition: yield* manager.getBrowserPartition(environmentId),
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
preloadUrl: pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
};
}),
});
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
export const setAnnotationTheme = makeIpcMethod({
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
payload: DesktopPreviewAnnotationThemeInputSchema,
result: Schema.Void,
@@ -211,7 +211,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
}),
});
export const pickElement = DesktopIpc.makeIpcMethod({
export const pickElement = makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
@@ -221,7 +221,7 @@ export const pickElement = DesktopIpc.makeIpcMethod({
}),
});
export const captureScreenshot = DesktopIpc.makeIpcMethod({
export const captureScreenshot = makeIpcMethod({
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: DesktopPreviewScreenshotArtifactSchema,
@@ -231,7 +231,7 @@ export const captureScreenshot = DesktopIpc.makeIpcMethod({
}),
});
export const revealArtifact = DesktopIpc.makeIpcMethod({
export const revealArtifact = makeIpcMethod({
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void,
@@ -241,7 +241,7 @@ export const revealArtifact = DesktopIpc.makeIpcMethod({
}),
});
export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
export const copyArtifactToClipboard = makeIpcMethod({
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void,
@@ -251,7 +251,7 @@ export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
}),
});
export const automationStatus = DesktopIpc.makeIpcMethod({
export const automationStatus = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationStatus,
@@ -261,7 +261,7 @@ export const automationStatus = DesktopIpc.makeIpcMethod({
}),
});
export const automationSnapshot = DesktopIpc.makeIpcMethod({
export const automationSnapshot = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationSnapshot,
@@ -271,7 +271,7 @@ export const automationSnapshot = DesktopIpc.makeIpcMethod({
}),
});
export const automationClick = DesktopIpc.makeIpcMethod({
export const automationClick = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
payload: DesktopPreviewAutomationClickInputSchema,
result: Schema.Void,
@@ -281,7 +281,7 @@ export const automationClick = DesktopIpc.makeIpcMethod({
}),
});
export const automationType = DesktopIpc.makeIpcMethod({
export const automationType = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
payload: DesktopPreviewAutomationTypeInputSchema,
result: Schema.Void,
@@ -291,7 +291,7 @@ export const automationType = DesktopIpc.makeIpcMethod({
}),
});
export const automationPress = DesktopIpc.makeIpcMethod({
export const automationPress = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
payload: DesktopPreviewAutomationPressInputSchema,
result: Schema.Void,
@@ -301,7 +301,7 @@ export const automationPress = DesktopIpc.makeIpcMethod({
}),
});
export const automationScroll = DesktopIpc.makeIpcMethod({
export const automationScroll = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
payload: DesktopPreviewAutomationScrollInputSchema,
result: Schema.Void,
@@ -311,7 +311,7 @@ export const automationScroll = DesktopIpc.makeIpcMethod({
}),
});
export const automationEvaluate = DesktopIpc.makeIpcMethod({
export const automationEvaluate = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
payload: DesktopPreviewAutomationEvaluateInputSchema,
result: Schema.Unknown,
@@ -321,7 +321,7 @@ export const automationEvaluate = DesktopIpc.makeIpcMethod({
}),
});
export const automationWaitFor = DesktopIpc.makeIpcMethod({
export const automationWaitFor = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
payload: DesktopPreviewAutomationWaitForInputSchema,
result: Schema.Void,
@@ -331,7 +331,7 @@ export const automationWaitFor = DesktopIpc.makeIpcMethod({
}),
});
export const saveRecording = DesktopIpc.makeIpcMethod({
export const saveRecording = makeIpcMethod({
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
payload: DesktopPreviewRecordingSaveInputSchema,
result: DesktopPreviewRecordingArtifactSchema,
@@ -9,14 +9,14 @@ import * as Schema from "effect/Schema";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SetTailscaleServeEnabledInput = Schema.Struct({
enabled: Schema.Boolean,
port: Schema.optionalKey(Schema.Number),
});
export const getServerExposureState = DesktopIpc.makeIpcMethod({
export const getServerExposureState = makeIpcMethod({
channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopServerExposureStateSchema,
@@ -26,7 +26,7 @@ export const getServerExposureState = DesktopIpc.makeIpcMethod({
}),
});
export const setServerExposureMode = DesktopIpc.makeIpcMethod({
export const setServerExposureMode = makeIpcMethod({
channel: IpcChannels.SET_SERVER_EXPOSURE_MODE_CHANNEL,
payload: DesktopServerExposureModeSchema,
result: DesktopServerExposureStateSchema,
@@ -41,7 +41,7 @@ export const setServerExposureMode = DesktopIpc.makeIpcMethod({
}),
});
export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({
export const setTailscaleServeEnabled = makeIpcMethod({
channel: IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL,
payload: SetTailscaleServeEnabledInput,
result: DesktopServerExposureStateSchema,
@@ -58,7 +58,7 @@ export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({
}),
});
export const getAdvertisedEndpoints = DesktopIpc.makeIpcMethod({
export const getAdvertisedEndpoints = makeIpcMethod({
channel: IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL,
payload: Schema.Void,
result: Schema.Array(AdvertisedEndpoint),
@@ -33,7 +33,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
@@ -107,7 +107,7 @@ const withLoopbackSshApi =
),
);
export const discoverSshHosts = DesktopIpc.makeIpcMethod({
export const discoverSshHosts = makeIpcMethod({
channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,
payload: Schema.Void,
result: Schema.Array(DesktopDiscoveredSshHostSchema),
@@ -117,7 +117,7 @@ export const discoverSshHosts = DesktopIpc.makeIpcMethod({
}),
});
export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
export const ensureSshEnvironment = makeIpcMethod({
channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentEnsureInputSchema,
result: DesktopSshEnvironmentEnsureResultSchema,
@@ -139,7 +139,7 @@ export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
}),
});
export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
export const disconnectSshEnvironment = makeIpcMethod({
channel: IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentTargetSchema,
result: Schema.Void,
@@ -149,7 +149,7 @@ export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
}),
});
export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
export const fetchSshEnvironmentDescriptor = makeIpcMethod({
channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
payload: DesktopSshHttpBaseUrlInputSchema,
result: ExecutionEnvironmentDescriptor,
@@ -160,7 +160,7 @@ export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
}),
});
export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
export const bootstrapSshBearerSession = makeIpcMethod({
channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
payload: DesktopSshBearerBootstrapInputSchema,
result: AuthAccessTokenResult,
@@ -177,7 +177,7 @@ export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
}),
});
export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
export const fetchSshSessionState = makeIpcMethod({
channel: IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL,
payload: DesktopSshBearerRequestInputSchema,
result: AuthSessionState,
@@ -194,7 +194,7 @@ export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
}),
});
export const issueSshWebSocketTicket = DesktopIpc.makeIpcMethod({
export const issueSshWebSocketTicket = makeIpcMethod({
channel: IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
payload: DesktopSshBearerRequestInputSchema,
result: AuthWebSocketTicketResult,
@@ -211,7 +211,7 @@ export const issueSshWebSocketTicket = DesktopIpc.makeIpcMethod({
}),
});
export const resolveSshPasswordPrompt = DesktopIpc.makeIpcMethod({
export const resolveSshPasswordPrompt = makeIpcMethod({
channel: IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
payload: DesktopSshPasswordPromptResolutionInputSchema,
result: Schema.Void,
+6 -6
View File
@@ -9,9 +9,9 @@ import * as Schema from "effect/Schema";
import * as DesktopUpdates from "../../updates/DesktopUpdates.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getUpdateState = DesktopIpc.makeIpcMethod({
export const getUpdateState = makeIpcMethod({
channel: IpcChannels.UPDATE_GET_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateStateSchema,
@@ -21,7 +21,7 @@ export const getUpdateState = DesktopIpc.makeIpcMethod({
}),
});
export const setUpdateChannel = DesktopIpc.makeIpcMethod({
export const setUpdateChannel = makeIpcMethod({
channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
payload: DesktopUpdateChannelSchema,
result: DesktopUpdateStateSchema,
@@ -31,7 +31,7 @@ export const setUpdateChannel = DesktopIpc.makeIpcMethod({
}),
});
export const downloadUpdate = DesktopIpc.makeIpcMethod({
export const downloadUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_DOWNLOAD_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateActionResultSchema,
@@ -41,7 +41,7 @@ export const downloadUpdate = DesktopIpc.makeIpcMethod({
}),
});
export const installUpdate = DesktopIpc.makeIpcMethod({
export const installUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateActionResultSchema,
@@ -51,7 +51,7 @@ export const installUpdate = DesktopIpc.makeIpcMethod({
}),
});
export const checkForUpdate = DesktopIpc.makeIpcMethod({
export const checkForUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_CHECK_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateCheckResultSchema,
+8 -19
View File
@@ -10,7 +10,6 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.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 ElectronWindow from "../../electron/ElectronWindow.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
const ContextMenuPosition = Schema.Struct({
x: Schema.Number,
@@ -36,7 +35,7 @@ function toWebSocketBaseUrl(httpBaseUrl: URL): string {
return url.href;
}
export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
export const getAppBranding = makeSyncIpcMethod({
channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
result: Schema.NullOr(DesktopAppBrandingSchema),
handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
@@ -45,7 +44,7 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
@@ -65,17 +64,7 @@ export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
}),
});
export const getLocalEnvironmentBearerToken = DesktopIpc.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({
export const pickFolder = makeIpcMethod({
channel: IpcChannels.PICK_FOLDER_CHANNEL,
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
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,
payload: Schema.String,
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,
payload: DesktopThemeSchema,
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,
payload: ContextMenuInput,
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,
payload: Schema.String,
result: Schema.Boolean,
+17 -30
View File
@@ -14,29 +14,28 @@ import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import serverPackageJson from "../../server/package.json" with { type: "json" };
import type { DesktopSettings as DesktopSettingsValue } from "./settings/DesktopAppSettings.ts";
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
import * as ElectronApp from "./electron/ElectronApp.ts";
import * as ElectronDialog from "./electron/ElectronDialog.ts";
import * as ElectronMenu from "./electron/ElectronMenu.ts";
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
import * as DesktopSecretStorage from "./electron/ElectronSafeStorage.ts";
import * as ElectronShell from "./electron/ElectronShell.ts";
import * as ElectronTheme from "./electron/ElectronTheme.ts";
import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
import * as ElectronWindow from "./electron/ElectronWindow.ts";
import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopClerk from "./app/DesktopClerk.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
import * as DesktopObservability from "./app/DesktopObservability.ts";
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
@@ -47,7 +46,7 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts";
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
@@ -69,8 +68,8 @@ const desktopEnvironmentLayer = Layer.unwrap(
);
const resolveDesktopSshCliRunner = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
settings: DesktopAppSettings.DesktopSettings,
environment: DesktopEnvironment.DesktopEnvironmentShape,
settings: DesktopSettingsValue,
): RemoteT3RunnerOptions => {
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
@@ -106,20 +105,21 @@ const electronLayer = Layer.mergeAll(
ElectronDialog.layer,
ElectronMenu.layer,
ElectronProtocol.layer,
ElectronSafeStorage.layer,
DesktopSecretStorage.layer,
ElectronShell.layer,
ElectronTheme.layer,
ElectronUpdater.layer,
ElectronWindow.layer,
DesktopIpc.layer(Electron.ipcMain),
Layer.succeed(DesktopIpc.DesktopIpc, DesktopIpc.make(Electron.ipcMain)),
);
const desktopFoundationLayer = Layer.mergeAll(
DesktopState.layer,
DesktopShutdown.layer,
DesktopLifecycle.layerShutdown,
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
@@ -129,12 +129,12 @@ const desktopSshLayer = desktopSshEnvironmentLayer.pipe(
);
const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
Layer.provideMerge(DesktopNetworkInterfaces.layer),
Layer.provideMerge(DesktopServerExposure.networkInterfacesLayer),
Layer.provideMerge(desktopFoundationLayer),
);
const desktopPreviewLayer = PreviewManager.layer.pipe(
Layer.provideMerge(BrowserSession.layer),
Layer.provideMerge(PreviewBrowserSession.layer),
Layer.provideMerge(desktopFoundationLayer),
);
@@ -149,30 +149,17 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(desktopWindowLayer),
);
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopCloudAuth.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
const desktopClerkLayer = DesktopClerk.layer.pipe(
Layer.provideMerge(desktopEnvironmentLayer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ElectronApp.layer),
);
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
Layer.flatMap(() =>
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
+17 -5
View File
@@ -4,13 +4,10 @@ import type {
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
@@ -42,8 +39,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
@@ -100,6 +95,23 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }),
}),
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) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
+18 -20
View File
@@ -2,38 +2,36 @@ import type { Session } from "electron";
import { session } from "electron";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
"BrowserSessionError",
{
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
readonly operation: string;
readonly cause: unknown;
}> {
override get message() {
return `Desktop preview browser session operation failed: ${this.operation}`;
}
}
export class BrowserSession extends Context.Service<
BrowserSession,
{
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
readonly isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
}
>()("@t3tools/desktop/preview/BrowserSession") {}
export interface BrowserSessionShape {
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
readonly isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
}
export const make = Effect.gen(function* BrowserSessionMake() {
export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
"@t3tools/desktop/preview/BrowserSession",
) {}
const make = Effect.gen(function* BrowserSessionMake() {
const crypto = yield* Crypto.Crypto;
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
+2 -54
View File
@@ -59,7 +59,7 @@ const environmentLayer = Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of({
browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
} as DesktopEnvironment.DesktopEnvironment["Service"]),
} as DesktopEnvironment.DesktopEnvironmentShape),
);
const fileSystemLayer = FileSystem.layerNoop({
@@ -82,7 +82,7 @@ const layer = PreviewManager.layer.pipe(
const withManager = <A>(
use: (
manager: PreviewManager.PreviewManager["Service"],
manager: PreviewManager.PreviewManagerShape,
) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
) =>
Effect.gen(function* () {
@@ -128,58 +128,6 @@ describe("PreviewManager", () => {
),
);
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("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
+127 -207
View File
@@ -37,6 +37,7 @@ import {
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -431,17 +432,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
) {
const tabs = yield* SynchronizedRef.get(tabsRef);
const tab = tabs.get(tabId);
if (!tab) {
return yield* fail("requireWebContents", new PreviewTabNotFoundError({ tabId }));
}
if (!tab) return yield* fail("requireWebContents", new PreviewTabNotFoundError(tabId));
if (tab.webContentsId == null) {
return yield* fail("requireWebContents", new PreviewWebviewNotInitializedError({ tabId }));
return yield* fail("requireWebContents", new PreviewWebviewNotInitializedError(tabId));
}
const wc = webContents.fromId(tab.webContentsId);
if (!wc) {
return yield* fail(
"requireWebContents",
new PreviewWebContentsNotFoundError({ tabId, webContentsId: tab.webContentsId }),
new PreviewWebContentsNotFoundError(tabId, tab.webContentsId),
);
}
return wc;
@@ -846,7 +845,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
} else {
const error = Option.getOrNull(Cause.findErrorOption(exit.cause));
const underlying = isPreviewManagerError(error) ? error.cause : error;
const underlying = error instanceof PreviewManagerError ? error.cause : error;
const interrupted =
underlying instanceof Error &&
underlying.name === "PreviewAutomationControlInterruptedError";
@@ -1162,7 +1161,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
) {
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
if (!tab) {
return yield* fail("registerWebview", new PreviewTabNotFoundError({ tabId }));
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
}
const wc = webContents.fromId(webContentsId);
const mainWindow = yield* Ref.get(mainWindowRef);
@@ -1173,7 +1172,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
) {
return yield* fail(
"registerWebview",
new PreviewWebContentsNotFoundError({ tabId, webContentsId }),
new PreviewWebContentsNotFoundError(tabId, webContentsId),
);
}
const attached = yield* Ref.get(attachedRef);
@@ -1196,103 +1195,26 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
const registeredAt = yield* currentIso;
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) {
return [
Option.none<{ readonly state: PreviewTabState; readonly pendingUrl: string | null }>(),
tabs,
] as const;
}
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
const next: PreviewTabState = {
...current,
webContentsId,
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
updatedAt: registeredAt,
};
return [
Option.some({
state: next,
pendingUrl,
}),
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
if (Math.abs(tab.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt("registerWebview.restoreZoom", () => wc.setZoomFactor(tab.zoomFactor)).pipe(
Effect.ignore,
);
}
yield* update(tabId, {
webContentsId,
navStatus: computeNavStatus(wc),
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor: tab.zoomFactor,
});
if (Option.isNone(registration)) {
return yield* fail("registerWebview", new PreviewTabNotFoundError({ tabId }));
}
const { state: registered, pendingUrl } = registration.value;
yield* emit(tabId, registered);
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt("registerWebview.restoreZoom", () =>
wc.setZoomFactor(registered.zoomFactor),
).pipe(Effect.ignore);
}
yield* attempt("registerWebview.sendTheme", () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
const latestNavStatus = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.navStatus;
if (
pendingUrl &&
latestNavStatus?.kind === "Loading" &&
latestNavStatus.url === pendingUrl &&
wc.getURL() !== pendingUrl
) {
runFork(
attemptPromise("registerWebview.loadPendingUrl", () => wc.loadURL(pendingUrl)).pipe(
Effect.ignore,
),
);
}
});
const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) {
const wc = yield* requireWebContents(tabId);
const url = yield* attempt("navigate.normalizeUrl", () => normalizePreviewUrl(rawUrl));
const updatedAt = yield* currentIso;
const pending = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
const next: PreviewTabState = {
tabId,
webContentsId: current?.webContentsId ?? null,
navStatus: {
kind: "Loading",
url,
title: current?.navStatus.kind === "Idle" || !current ? "" : current.navStatus.title,
},
canGoBack: current?.canGoBack ?? false,
canGoForward: current?.canGoForward ?? false,
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
controller: current?.controller ?? "none",
updatedAt,
};
return [
next,
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
});
yield* emit(tabId, pending);
if (pending.webContentsId == null) return;
const wc = webContents.fromId(pending.webContentsId);
if (!wc) {
const detached = { ...pending, webContentsId: null };
yield* SynchronizedRef.update(tabsRef, (tabs) =>
tabs.get(tabId)?.webContentsId !== pending.webContentsId
? tabs
: replaceMap(tabs, (copy) => {
copy.set(tabId, detached);
}),
);
yield* emit(tabId, detached);
return;
}
if (wc.getURL() === url) {
yield* attempt("navigate.reload", () => wc.reload());
return;
@@ -2201,131 +2123,129 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
};
});
export class PreviewTabNotFoundError extends Schema.TaggedErrorClass<PreviewTabNotFoundError>()(
"PreviewTabNotFoundError",
{ tabId: Schema.String },
) {
override get message(): string {
return `Preview tab not found: ${this.tabId}`;
export class PreviewTabNotFoundError extends Error {
readonly tabId: string;
constructor(tabId: string) {
super(`Preview tab not found: ${tabId}`);
this.name = "PreviewTabNotFoundError";
this.tabId = tabId;
}
}
export class PreviewWebContentsNotFoundError extends Schema.TaggedErrorClass<PreviewWebContentsNotFoundError>()(
"PreviewWebContentsNotFoundError",
{ tabId: Schema.String, webContentsId: Schema.Number },
) {
override get message(): string {
return `WebContents ${this.webContentsId} not found for preview tab ${this.tabId}`;
export class PreviewWebContentsNotFoundError extends Error {
readonly tabId: string;
readonly webContentsId: number;
constructor(tabId: string, webContentsId: number) {
super(`WebContents ${webContentsId} not found for preview tab ${tabId}`);
this.name = "PreviewWebContentsNotFoundError";
this.tabId = tabId;
this.webContentsId = webContentsId;
}
}
export class PreviewWebviewNotInitializedError extends Schema.TaggedErrorClass<PreviewWebviewNotInitializedError>()(
"PreviewWebviewNotInitializedError",
{ tabId: Schema.String },
) {
override get message(): string {
return `Preview tab "${this.tabId}" has no webview registered`;
export class PreviewWebviewNotInitializedError extends Error {
readonly tabId: string;
constructor(tabId: string) {
super(`Preview tab "${tabId}" has no webview registered`);
this.name = "PreviewWebviewNotInitializedError";
this.tabId = tabId;
}
}
export class PreviewManagerError extends Schema.TaggedErrorClass<PreviewManagerError>()(
"PreviewManagerError",
{
operation: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
export class PreviewManagerError extends Data.TaggedError("PreviewManagerError")<{
readonly operation: string;
readonly cause: unknown;
}> {
override get message() {
return `Desktop preview operation failed: ${this.operation}`;
}
}
const isPreviewManagerError = Schema.is(PreviewManagerError);
export interface PreviewManagerShape {
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
readonly isBrowserPartition: (partition: string) => boolean;
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly registerWebview: (
tabId: string,
webContentsId: number,
) => Effect.Effect<void, PreviewManagerError>;
readonly navigate: (tabId: string, url: string) => Effect.Effect<void, PreviewManagerError>;
readonly goBack: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly goForward: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly refresh: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
readonly getBrowserPartition: (scope?: string) => Effect.Effect<string, PreviewManagerError>;
readonly setAnnotationTheme: (
theme: DesktopPreviewAnnotationTheme,
) => Effect.Effect<void, PreviewManagerError>;
readonly pickElement: (
tabId: string,
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly captureScreenshot: (
tabId: string,
) => Effect.Effect<DesktopPreviewScreenshotArtifact, PreviewManagerError>;
readonly revealArtifact: (path: string) => Effect.Effect<void, PreviewManagerError>;
readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;
readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly saveRecording: (
tabId: string,
mimeType: string,
data: Uint8Array,
) => Effect.Effect<DesktopPreviewRecordingArtifact, PreviewManagerError>;
readonly automationStatus: (
tabId: string,
) => Effect.Effect<PreviewAutomationStatus, PreviewManagerError>;
readonly automationSnapshot: (
tabId: string,
) => Effect.Effect<PreviewAutomationSnapshot, PreviewManagerError>;
readonly automationClick: (
tabId: string,
input: PreviewAutomationClickInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly automationType: (
tabId: string,
input: PreviewAutomationTypeInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly automationPress: (
tabId: string,
input: PreviewAutomationPressInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly automationScroll: (
tabId: string,
input: PreviewAutomationScrollInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly automationEvaluate: (
tabId: string,
input: PreviewAutomationEvaluateInput,
) => Effect.Effect<unknown, PreviewManagerError>;
readonly automationWaitFor: (
tabId: string,
input: PreviewAutomationWaitForInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly subscribeStateChanges: (listener: Listener) => Effect.Effect<void, never, Scope.Scope>;
readonly subscribePointerEvents: (
listener: PointerEventListener,
) => Effect.Effect<void, never, Scope.Scope>;
readonly subscribeRecordingFrames: (
listener: RecordingFrameListener,
) => Effect.Effect<void, never, Scope.Scope>;
}
export class PreviewManager extends Context.Service<
PreviewManager,
{
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
readonly isBrowserPartition: (partition: string) => boolean;
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly registerWebview: (
tabId: string,
webContentsId: number,
) => Effect.Effect<void, PreviewManagerError>;
readonly navigate: (tabId: string, url: string) => Effect.Effect<void, PreviewManagerError>;
readonly goBack: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly goForward: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly refresh: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
readonly getBrowserPartition: (scope?: string) => Effect.Effect<string, PreviewManagerError>;
readonly setAnnotationTheme: (
theme: DesktopPreviewAnnotationTheme,
) => Effect.Effect<void, PreviewManagerError>;
readonly pickElement: (
tabId: string,
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly captureScreenshot: (
tabId: string,
) => Effect.Effect<DesktopPreviewScreenshotArtifact, PreviewManagerError>;
readonly revealArtifact: (path: string) => Effect.Effect<void, PreviewManagerError>;
readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;
readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly saveRecording: (
tabId: string,
mimeType: string,
data: Uint8Array,
) => Effect.Effect<DesktopPreviewRecordingArtifact, PreviewManagerError>;
readonly automationStatus: (
tabId: string,
) => Effect.Effect<PreviewAutomationStatus, PreviewManagerError>;
readonly automationSnapshot: (
tabId: string,
) => Effect.Effect<PreviewAutomationSnapshot, PreviewManagerError>;
readonly automationClick: (
tabId: string,
input: PreviewAutomationClickInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly automationType: (
tabId: string,
input: PreviewAutomationTypeInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly automationPress: (
tabId: string,
input: PreviewAutomationPressInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly automationScroll: (
tabId: string,
input: PreviewAutomationScrollInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly automationEvaluate: (
tabId: string,
input: PreviewAutomationEvaluateInput,
) => Effect.Effect<unknown, PreviewManagerError>;
readonly automationWaitFor: (
tabId: string,
input: PreviewAutomationWaitForInput,
) => Effect.Effect<void, PreviewManagerError>;
readonly subscribeStateChanges: (listener: Listener) => Effect.Effect<void, never, Scope.Scope>;
readonly subscribePointerEvents: (
listener: PointerEventListener,
) => Effect.Effect<void, never, Scope.Scope>;
readonly subscribeRecordingFrames: (
listener: RecordingFrameListener,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/preview/Manager/PreviewManager") {}
export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
"@t3tools/desktop/preview/Manager/PreviewManager",
) {}
export const make = Effect.gen(function* PreviewManagerMake() {
const make = Effect.gen(function* PreviewManagerMake() {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const browserSession = yield* BrowserSession.BrowserSession;
const operations = yield* makeNativeOperations(environment.browserArtifactsDir);
@@ -1,14 +1,14 @@
// @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection.
import * as NodeFSP from "node:fs/promises";
import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeVM from "node:vm";
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { runInNewContext } from "node:vm";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const require = createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
@@ -32,11 +32,7 @@ export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRunt
catch: (cause) => fail("resolvePackage", cause),
});
const coreBundle = yield* Effect.tryPromise({
try: () =>
NodeFSP.readFile(
NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js"),
"utf8",
),
try: () => readFile(join(dirname(packageJsonPath), "lib/coreBundle.js"), "utf8"),
catch: (cause) => fail("readCoreBundle", cause),
});
const marker = "source3 = ";
@@ -57,7 +53,7 @@ export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRunt
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () => NodeVM.runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
try: () => runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
catch: (cause) => fail("evaluateSourceLiteral", cause),
});
if (typeof source !== "string" || source.length < 100_000) {
@@ -8,6 +8,11 @@ import * as Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import {
DEFAULT_DESKTOP_SETTINGS,
resolveDefaultDesktopSettings,
type DesktopSettings as DesktopSettingsValue,
} from "./DesktopAppSettings.ts";
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({
@@ -77,23 +82,20 @@ describe("DesktopSettings", () => {
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
assert.deepEqual(yield* settings.load, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
assert.deepEqual(yield* settings.get, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
assert.deepEqual(yield* settings.get, DEFAULT_DESKTOP_SETTINGS);
}),
),
);
it("defaults packaged nightly builds to the nightly update channel", () => {
assert.deepEqual(
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
} satisfies DesktopAppSettings.DesktopSettings,
);
assert.deepEqual(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"), {
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
} satisfies DesktopSettingsValue);
});
it.effect("loads persisted settings and applies semantic updates", () =>
@@ -114,7 +116,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
} satisfies DesktopAppSettings.DesktopSettings);
} satisfies DesktopSettingsValue);
const exposure = yield* settings.setServerExposureMode("local-only");
assert.isTrue(exposure.changed);
@@ -135,27 +137,6 @@ describe("DesktopSettings", () => {
),
);
it.effect("reports the failed desktop settings write operation and path", () =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* fileSystem.makeDirectory(environment.desktopSettingsPath, { recursive: true });
const error = yield* settings.setServerExposureMode("network-accessible").pipe(Effect.flip);
assert.instanceOf(error, DesktopAppSettings.DesktopSettingsWriteError);
assert.equal(error.operation, "replace-settings-file");
assert.equal(error.path, environment.desktopSettingsPath);
assert.exists(error.cause);
assert.equal(
error.message,
`Desktop settings write failed during replace-settings-file at ${environment.desktopSettingsPath}.`,
);
}),
),
);
it.effect("does not persist no-op semantic updates", () =>
withSettings(
Effect.gen(function* () {
@@ -186,7 +167,7 @@ describe("DesktopSettings", () => {
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.desktopSettingsPath, "{not-json");
assert.deepEqual(yield* settings.load, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
}),
),
);
@@ -214,7 +195,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
} satisfies DesktopAppSettings.DesktopSettings);
} satisfies DesktopSettingsValue);
}),
),
);
@@ -253,7 +234,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
} satisfies DesktopAppSettings.DesktopSettings);
} satisfies DesktopSettingsValue);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
),
@@ -275,7 +256,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
} satisfies DesktopAppSettings.DesktopSettings);
} satisfies DesktopSettingsValue);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
),
@@ -296,7 +277,7 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
} satisfies DesktopAppSettings.DesktopSettings);
} satisfies DesktopSettingsValue);
}),
),
);
+82 -107
View File
@@ -7,11 +7,13 @@ import {
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
@@ -61,50 +63,32 @@ const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSet
changed,
});
const DesktopSettingsWriteOperation = Schema.Literals([
"create-temporary-file-name",
"encode-document",
"create-directory",
"write-temporary-file",
"replace-settings-file",
]);
type DesktopSettingsWriteOperation = typeof DesktopSettingsWriteOperation.Type;
export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSettingsWriteError>()(
"DesktopSettingsWriteError",
{
operation: DesktopSettingsWriteOperation,
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop settings write failed during ${this.operation} at ${this.path}.`;
export class DesktopSettingsWriteError extends Data.TaggedError("DesktopSettingsWriteError")<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop settings: ${this.cause.message}`;
}
}
const writeError = (
operation: DesktopSettingsWriteOperation,
path: string,
cause: unknown,
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
export interface DesktopAppSettingsShape {
readonly load: Effect.Effect<DesktopSettings>;
readonly get: Effect.Effect<DesktopSettings>;
readonly setServerExposureMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setTailscaleServe: (input: {
readonly enabled: boolean;
readonly port: Option.Option<number>;
}) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setUpdateChannel: (
channel: DesktopUpdateChannel,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
}
export class DesktopAppSettings extends Context.Service<
DesktopAppSettings,
{
readonly load: Effect.Effect<DesktopSettings>;
readonly get: Effect.Effect<DesktopSettings>;
readonly setServerExposureMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setTailscaleServe: (input: {
readonly enabled: boolean;
readonly port: Option.Option<number>;
}) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setUpdateChannel: (
channel: DesktopUpdateChannel,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
}
DesktopAppSettingsShape
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
@@ -239,86 +223,77 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
readonly settings: DesktopSettings;
readonly defaultSettings: DesktopSettings;
readonly suffix: string;
}): Effect.fn.Return<void, DesktopSettingsWriteError> {
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
).pipe(Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)));
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.settingsPath)
.pipe(
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
);
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.settingsPath);
});
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
export const layer = Layer.effect(
DesktopAppSettings,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
const persist = (
update: (settings: DesktopSettings) => DesktopSettings,
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
SynchronizedRef.modifyEffect(settingsRef, (settings) => {
const nextSettings = update(settings);
if (nextSettings === settings) {
return Effect.succeed([settingsChange(settings, false), settings] as const);
}
const persist = (
update: (settings: DesktopSettings) => DesktopSettings,
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
SynchronizedRef.modifyEffect(settingsRef, (settings) => {
const nextSettings = update(settings);
if (nextSettings === settings) {
return Effect.succeed([settingsChange(settings, false), settings] as const);
}
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
suffix,
}),
),
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
);
});
return DesktopAppSettings.of({
get: SynchronizedRef.get(settingsRef),
load: Effect.gen(function* () {
const settings = yield* readSettings(
fileSystem,
environment.desktopSettingsPath,
environment.appVersion,
);
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
}).pipe(Effect.withSpan("desktop.settings.load")),
setServerExposureMode: (mode) =>
persist((settings) => setServerExposureMode(settings, mode)).pipe(
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
),
Effect.flatMap((suffix) =>
writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
suffix,
}),
setTailscaleServe: (input) =>
persist((settings) => setTailscaleServe(settings, input)).pipe(
Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
),
setUpdateChannel: (channel) =>
persist((settings) => setUpdateChannel(settings, channel)).pipe(
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
),
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
);
});
return DesktopAppSettings.of({
get: SynchronizedRef.get(settingsRef),
load: Effect.gen(function* () {
const settings = yield* readSettings(
fileSystem,
environment.desktopSettingsPath,
environment.appVersion,
);
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
}).pipe(Effect.withSpan("desktop.settings.load")),
setServerExposureMode: (mode) =>
persist((settings) => setServerExposureMode(settings, mode)).pipe(
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
),
setTailscaleServe: (input) =>
persist((settings) => setTailscaleServe(settings, input)).pipe(
Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
),
setUpdateChannel: (channel) =>
persist((settings) => setUpdateChannel(settings, channel)).pipe(
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
),
});
});
export const layer = Layer.effect(DesktopAppSettings, make);
}),
);
export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SETTINGS) =>
Layer.effect(
@@ -34,6 +34,7 @@ const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(Clien
const decodeRecordJson = Schema.decodeEffect(
Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
);
function makeLayer(baseDir: string) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
@@ -105,27 +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.exists(error.cause);
assert.equal(
error.message,
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
);
}),
),
);
it.effect("loads lenient direct client settings documents", () =>
withClientSettings(
Effect.gen(function* () {
@@ -2,11 +2,13 @@ import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
@@ -29,43 +31,24 @@ const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Sc
);
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
const DesktopClientSettingsWriteOperation = Schema.Literals([
"create-temporary-file-name",
"encode-document",
"create-directory",
"write-temporary-file",
"replace-settings-file",
]);
type DesktopClientSettingsWriteOperation = typeof DesktopClientSettingsWriteOperation.Type;
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
export class DesktopClientSettingsWriteError extends Data.TaggedError(
"DesktopClientSettingsWriteError",
{
operation: DesktopClientSettingsWriteOperation,
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop client settings write failed during ${this.operation} at ${this.path}.`;
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop client settings: ${this.cause.message}`;
}
}
const writeError = (
operation: DesktopClientSettingsWriteOperation,
path: string,
cause: unknown,
): DesktopClientSettingsWriteError =>
new DesktopClientSettingsWriteError({ operation, path, cause });
export interface DesktopClientSettingsShape {
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
readonly set: (settings: ClientSettings) => Effect.Effect<void, DesktopClientSettingsWriteError>;
}
export class DesktopClientSettings extends Context.Service<
DesktopClientSettings,
{
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
readonly set: (
settings: ClientSettings,
) => Effect.Effect<void, DesktopClientSettingsWriteError>;
}
DesktopClientSettingsShape
>()("@t3tools/desktop/settings/DesktopClientSettings") {}
const readClientSettings = (
@@ -92,56 +75,45 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
readonly settingsPath: string;
readonly settings: ClientSettings;
readonly suffix: string;
}): Effect.fn.Return<void, DesktopClientSettingsWriteError> {
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.settingsPath)
.pipe(
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
);
const encoded = yield* encodeClientSettingsJson(input.settings);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.settingsPath);
});
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
export const layer = Layer.effect(
DesktopClientSettings,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
return DesktopClientSettings.of({
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
Effect.withSpan("desktop.clientSettings.get"),
),
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.clientSettingsPath, cause),
),
Effect.flatMap((suffix) =>
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
suffix,
}),
),
Effect.withSpan("desktop.clientSettings.set"),
return DesktopClientSettings.of({
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
Effect.withSpan("desktop.clientSettings.get"),
),
});
});
export const layer = Layer.effect(DesktopClientSettings, make);
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
suffix,
}),
),
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
Effect.withSpan("desktop.clientSettings.set"),
),
});
}),
);
export const layerTest = (initialSettings: Option.Option<ClientSettings> = Option.none()) =>
Layer.effect(
@@ -5,7 +5,6 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts";
@@ -35,15 +34,10 @@ const SavedEnvironmentRegistryDocumentProbe = Schema.Struct({
version: Schema.Number,
records: Schema.Array(Schema.Unknown),
});
const SavedEnvironmentRegistryDocumentProbeJson = Schema.fromJsonString(
SavedEnvironmentRegistryDocumentProbe,
);
const decodeSavedEnvironmentRegistryDocumentProbe = Schema.decodeEffect(
SavedEnvironmentRegistryDocumentProbeJson,
);
const encodeSavedEnvironmentRegistryDocumentProbe = Schema.encodeEffect(
SavedEnvironmentRegistryDocumentProbeJson,
Schema.fromJsonString(SavedEnvironmentRegistryDocumentProbe),
);
function makeSafeStorageLayer(input: {
readonly available: boolean;
readonly availabilityError?: unknown;
@@ -86,7 +80,7 @@ function makeSafeStorageLayer(input: {
}
return Effect.succeed(decoded.slice("enc:".length));
},
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(
@@ -97,7 +91,6 @@ function makeLayer(
readonly encryptError?: unknown;
readonly decryptError?: unknown;
},
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
@@ -115,20 +108,18 @@ function makeLayer(
),
);
const safeStorageLayer = makeSafeStorageLayer({
available: options?.availableSecretStorage ?? true,
availabilityError: options?.availabilityError,
encryptError: options?.encryptError,
decryptError: options?.decryptError,
});
const dependencies = Layer.mergeAll(
environmentLayer,
safeStorageLayer,
NodeServices.layer,
fileSystemLayer,
return DesktopSavedEnvironments.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(
makeSafeStorageLayer({
available: options?.availableSecretStorage ?? true,
availabilityError: options?.availabilityError,
encryptError: options?.encryptError,
decryptError: options?.decryptError,
}),
),
Layer.provideMerge(NodeServices.layer),
);
return DesktopSavedEnvironments.layer.pipe(Layer.provideMerge(dependencies));
}
const withSavedEnvironments = <A, E, R>(
@@ -224,36 +215,6 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("reports invalid saved secret encoding without exposing the secret", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
const encoded = yield* encodeSavedEnvironmentRegistryDocumentProbe({
version: 1,
records: [{ ...savedRegistryRecord, encryptedBearerToken: "%%%" }],
});
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, `${encoded}\n`);
const error = yield* savedEnvironments
.getSecret(savedRegistryRecord.environmentId)
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentSecretDecodeError);
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
assert.equal(error.field, "encryptedBearerToken");
assert.exists(error.cause);
assert.equal(
error.message,
`Failed to decode encryptedBearerToken for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
);
assert.notInclude(error.message, "%%%");
}),
),
);
it.effect("returns false when writing secrets while encryption is unavailable", () =>
withSavedEnvironments(
Effect.gen(function* () {
@@ -311,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", () =>
withSavedEnvironments(
Effect.gen(function* () {
@@ -360,96 +301,16 @@ describe("DesktopSavedEnvironments", () => {
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
assert.instanceOf(
registryError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
);
assert.equal(registryError.registryPath, environment.savedEnvironmentRegistryPath);
assert.exists(registryError.cause);
const secretError = yield* savedEnvironments
.getSecret(savedRegistryRecord.environmentId)
.pipe(Effect.flip);
assert.instanceOf(
secretError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
);
const mutationError = yield* savedEnvironments
.setRegistry([savedRegistryRecord])
.pipe(Effect.flip);
assert.instanceOf(
mutationError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
);
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
}),
),
);
it.effect("reports saved environment filesystem reads separately from document decoding", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-saved-environments-test-",
});
const registryPath = `${baseDir}/userdata/saved-environments.json`;
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: registryPath,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments.pipe(
Effect.provide(makeLayer(baseDir, undefined, fileSystemLayer)),
);
const error = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
assert.equal(error.registryPath, registryPath);
assert.strictEqual(error.cause, permissionError);
assert.equal(error.message, `Failed to read desktop saved environments at ${registryPath}.`);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("reports the failed saved environment write operation and path", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-saved-environments-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: `${baseDir}/userdata`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: baseFileSystem.readFileString,
makeDirectory: () => Effect.fail(permissionError),
}),
);
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments.pipe(
Effect.provide(makeLayer(baseDir, undefined, fileSystemLayer)),
);
const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);
assert.equal(error.operation, "create-directory");
assert.equal(error.path, `${baseDir}/userdata`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("returns false when writing a secret without metadata", () =>
withSavedEnvironments(
Effect.gen(function* () {
@@ -2,12 +2,14 @@ import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/co
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
@@ -70,118 +72,70 @@ const encodeSavedEnvironmentRegistryDocumentJson = Schema.encodeEffect(
SavedEnvironmentRegistryDocumentJson,
);
const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
"create-temporary-file-name",
"encode-registry",
"create-directory",
"write-temporary-file",
"replace-registry-file",
]);
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
"DesktopSavedEnvironmentsWriteError",
{
operation: DesktopSavedEnvironmentsWriteOperation,
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop saved-environment write failed during ${this.operation} at ${this.path}.`;
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop saved environments: ${this.cause.message}`;
}
}
const writeError = (
operation: DesktopSavedEnvironmentsWriteOperation,
path: string,
cause: unknown,
): DesktopSavedEnvironmentsWriteError =>
new DesktopSavedEnvironmentsWriteError({
operation,
path,
cause,
});
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
"DesktopSavedEnvironmentsReadError",
{
registryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read desktop saved environments at ${this.registryPath}.`;
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop saved environments: ${this.cause.message}`;
}
}
export class DesktopSavedEnvironmentsDocumentDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsDocumentDecodeError>()(
"DesktopSavedEnvironmentsDocumentDecodeError",
{
registryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode desktop saved environments at ${this.registryPath}.`;
}
}
export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretDecodeError>()(
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
"DesktopSavedEnvironmentSecretDecodeError",
{
environmentId: Schema.String,
registryPath: Schema.String,
field: Schema.Literal("encryptedBearerToken"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode ${this.field} for environment ${this.environmentId} at ${this.registryPath}.`;
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode desktop saved environment secret.";
}
}
export type DesktopSavedEnvironmentsReadRegistryError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentsDocumentDecodeError;
export type DesktopSavedEnvironmentsMutationError =
| DesktopSavedEnvironmentsReadRegistryError
| DesktopSavedEnvironmentsWriteError;
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadRegistryError
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageError;
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
export type DesktopSavedEnvironmentsSetSecretError =
| DesktopSavedEnvironmentsMutationError
| ElectronSafeStorage.ElectronSafeStorageError;
| DesktopSavedEnvironmentsWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
export interface DesktopSavedEnvironmentsShape {
readonly getRegistry: Effect.Effect<
readonly PersistedSavedEnvironmentRecord[],
DesktopSavedEnvironmentsReadError
>;
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly getSecret: (
environmentId: string,
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
readonly setSecret: (input: {
readonly environmentId: string;
readonly secret: string;
}) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
readonly removeSecret: (
environmentId: string,
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
}
export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments,
{
readonly getRegistry: Effect.Effect<
readonly PersistedSavedEnvironmentRecord[],
DesktopSavedEnvironmentsReadRegistryError
>;
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
readonly removeEnvironment: (
environmentId: string,
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
readonly getSecret: (
environmentId: string,
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
readonly setSecret: (input: {
readonly environmentId: string;
readonly secret: string;
}) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
readonly removeSecret: (
environmentId: string,
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
}
DesktopSavedEnvironmentsShape
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
function toPersistedSavedEnvironmentRecord(
@@ -236,30 +190,19 @@ function normalizeSavedEnvironmentRegistryDocument(
function readRegistryDocument(
fileSystem: FileSystem.FileSystem,
registryPath: string,
): Effect.Effect<SavedEnvironmentRegistryDocument, DesktopSavedEnvironmentsReadRegistryError> {
): Effect.Effect<
SavedEnvironmentRegistryDocument,
PlatformError.PlatformError | Schema.SchemaError
> {
return fileSystem.readFileString(registryPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound"
? Effect.succeed<string | null>(null)
: Effect.fail(
new DesktopSavedEnvironmentsReadError({
registryPath,
cause: error,
}),
),
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed({ version: 1, records: [] })
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsDocumentDecodeError({
registryPath,
cause,
}),
),
),
),
);
@@ -272,23 +215,13 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
readonly registryPath: string;
readonly document: SavedEnvironmentRegistryDocument;
readonly suffix: string;
}): Effect.fn.Return<void, DesktopSavedEnvironmentsWriteError> {
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.registryPath);
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
Effect.mapError((cause) => writeError("encode-registry", input.registryPath, cause)),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.registryPath)
.pipe(
Effect.mapError((cause) => writeError("replace-registry-file", input.registryPath, cause)),
);
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.registryPath);
},
);
@@ -314,159 +247,130 @@ function preserveExistingSecrets(
}
function decodeSecretBytes(
environmentId: string,
registryPath: string,
encoded: string,
): Effect.Effect<Uint8Array, DesktopSavedEnvironmentSecretDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretDecodeError({
environmentId,
registryPath,
field: "encryptedBearerToken",
cause,
}),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentSecretDecodeError({ cause })),
);
}
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
export const layer = Layer.effect(
DesktopSavedEnvironments,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
),
Effect.flatMap((suffix) =>
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
suffix,
}),
),
);
return DesktopSavedEnvironments.of({
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
Effect.map((document) =>
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
),
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
),
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
const currentDocument = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
suffix,
}),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })),
);
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
function* (environmentId) {
return DesktopSavedEnvironments.of({
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
Effect.map((document) =>
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
),
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
const currentDocument = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
const encoded = Option.fromNullishOr(
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
);
if (!document.records.some((record) => record.environmentId === environmentId)) {
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(encoded.value);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}),
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
const { environmentId, secret } = input;
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedBearerToken = Encoding.encodeBase64(
yield* safeStorage.encryptString(secret),
);
let found = false;
const nextDocument: SavedEnvironmentRegistryDocument = {
version: document.version,
records: document.records.map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
found = true;
return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));
}),
};
if (found) {
yield* writeDocument(nextDocument);
}
return found;
}),
removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (
!document.records.some(
(record) =>
record.environmentId === environmentId && record.encryptedBearerToken !== undefined,
)
) {
return;
}
yield* writeDocument({
version: document.version,
records: document.records.filter((record) => record.environmentId !== environmentId),
records: document.records.map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
});
},
),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
const encoded = Option.fromNullishOr(
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
);
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(
environmentId,
environment.savedEnvironmentRegistryPath,
encoded.value,
);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}),
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
const { environmentId, secret } = input;
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
let found = false;
const nextDocument: SavedEnvironmentRegistryDocument = {
version: document.version,
records: document.records.map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
found = true;
return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));
}),
};
if (found) {
yield* writeDocument(nextDocument);
}
return found;
}),
removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
if (
!document.records.some(
(record) =>
record.environmentId === environmentId && record.encryptedBearerToken !== undefined,
)
) {
return;
}
yield* writeDocument({
version: document.version,
records: document.records.map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
});
}),
});
});
export const layer = Layer.effect(DesktopSavedEnvironments, make);
}),
});
}),
);
export const layerTest = (input?: {
readonly records?: readonly PersistedSavedEnvironmentRecord[];
@@ -481,18 +385,6 @@ export const layerTest = (input?: {
return DesktopSavedEnvironments.of({
getRegistry: Ref.get(recordsRef),
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) =>
Ref.get(secretsRef).pipe(
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
@@ -64,7 +64,7 @@ function runShellEnvironment(input: {
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of({
platform: input.platform,
} as DesktopEnvironment.DesktopEnvironment["Service"]),
} as DesktopEnvironment.DesktopEnvironmentShape),
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
@@ -3,8 +3,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -20,11 +19,13 @@ interface WindowsProbeOptions {
readonly loadProfile: boolean;
}
export interface DesktopShellEnvironmentShape {
readonly installIntoProcess: Effect.Effect<void, never>;
}
export class DesktopShellEnvironment extends Context.Service<
DesktopShellEnvironment,
{
readonly installIntoProcess: Effect.Effect<void>;
}
DesktopShellEnvironmentShape
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
const LOGIN_SHELL_ENV_NAMES = [
@@ -211,7 +212,11 @@ const readLoginShellEnvironment = (
timeout: LOGIN_SHELL_TIMEOUT,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath = runCommandOutput({
const readLaunchctlPath: Effect.Effect<
Option.Option<string>,
never,
ChildProcessSpawner.ChildProcessSpawner
> = runCommandOutput({
command: "/bin/launchctl",
args: ["getenv", "PATH"],
timeout: LAUNCHCTL_TIMEOUT,
@@ -331,20 +336,20 @@ const installShellEnvironment = (
return Effect.void;
};
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
installShellEnvironment({
env: process.env,
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
);
return DesktopShellEnvironment.of({ installIntoProcess });
});
export const layer = Layer.effect(DesktopShellEnvironment, make);
export const layer = Layer.effect(
DesktopShellEnvironment,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return DesktopShellEnvironment.of({
installIntoProcess: installShellEnvironment({
env: process.env,
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
),
});
}),
);
@@ -19,20 +19,6 @@ function makeTempHomeDir() {
}
describe("sshEnvironment", () => {
it("keeps prompt presentation diagnostics distinct from the legacy wrapper message", () => {
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
requestId: "prompt-1",
destination: "devbox",
cause: new Error("renderer send failed"),
});
assert.equal(cause.message, "Failed to present SSH password prompt for devbox.");
assert.equal(
DesktopSshEnvironment.toSshPasswordPromptError(cause).message,
"T3 Code window is not available for SSH authentication.",
);
});
it("treats password prompt timeouts as cancellable authentication prompts", () => {
assert.equal(
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(
@@ -118,6 +104,7 @@ describe("sshEnvironment", () => {
Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {
request: () => Effect.die("unexpected password prompt request"),
resolve: () => Effect.die("unexpected password prompt resolution"),
cancelPending: () => Effect.void,
}),
),
Layer.provideMerge(NodeServices.layer),
+41 -61
View File
@@ -4,7 +4,11 @@ import type {
DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import * as SshAuth from "@t3tools/ssh/auth";
import {
SshPasswordPrompt,
type SshPasswordPromptShape,
type SshPasswordRequest,
} from "@t3tools/ssh/auth";
import { discoverSshHosts } from "@t3tools/ssh/config";
import {
SshCommandError,
@@ -15,14 +19,14 @@ import {
SshPasswordPromptError,
SshReadinessError,
} from "@t3tools/ssh/errors";
import * as SshTunnel from "@t3tools/ssh/tunnel";
import { SshEnvironmentManager, type RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
@@ -48,25 +52,27 @@ export type DesktopSshEnvironmentError =
| DesktopSshEnvironmentDiscoverError
| DesktopSshEnvironmentOperationError;
export interface DesktopSshEnvironmentShape {
readonly discoverHosts: (input?: {
readonly homeDir?: string;
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) => Effect.Effect<DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentOperationError>;
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
}
export class DesktopSshEnvironment extends Context.Service<
DesktopSshEnvironment,
{
readonly discoverHosts: (input?: {
readonly homeDir?: string;
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) => Effect.Effect<DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentOperationError>;
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
}
DesktopSshEnvironmentShape
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
export interface DesktopSshEnvironmentLayerOptions {
readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: Effect.Effect<SshTunnel.RemoteT3RunnerOptions>;
readonly resolveCliRunner?: Effect.Effect<RemoteT3RunnerOptions>;
}
function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
@@ -82,53 +88,27 @@ export function isDesktopSshPasswordPromptCancellation(
);
}
function unexpectedPasswordPromptError(error: never): never {
throw new Error(`Unhandled desktop SSH password prompt error: ${String(error)}`);
}
export function toSshPasswordPromptError(
cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptRequestError,
): SshPasswordPromptError {
let message: string;
switch (cause._tag) {
case "DesktopSshPromptRequestIdGenerationError":
message = "Secure randomness is unavailable.";
break;
case "DesktopSshPromptWindowUnavailableError":
case "DesktopSshPromptPresentationError":
message = "T3 Code window is not available for SSH authentication.";
break;
case "DesktopSshPromptTimedOutError":
message = `SSH authentication timed out for ${cause.destination}.`;
break;
case "DesktopSshPromptCancelledError":
message = `SSH authentication cancelled for ${cause.destination}.`;
break;
case "DesktopSshPromptWindowClosedError":
message = "SSH authentication was cancelled because the app window closed.";
break;
case "DesktopSshPromptServiceStoppedError":
message = "SSH password prompt service stopped.";
break;
default:
return unexpectedPasswordPromptError(cause);
}
return new SshPasswordPromptError({ message, cause });
}
const makePasswordPrompt = (
prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPrompts["Service"],
): SshAuth.SshPasswordPrompt["Service"] => ({
prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPromptsShape,
): SshPasswordPromptShape => ({
isAvailable: true,
request: (request: SshAuth.SshPasswordRequest) =>
prompts.request(request).pipe(Effect.mapError(toSshPasswordPromptError)),
request: (request: SshPasswordRequest) =>
prompts.request(request).pipe(
Effect.mapError(
(cause) =>
new SshPasswordPromptError({
message: cause.message,
cause,
}),
),
),
});
export const make = Effect.gen(function* () {
const manager = yield* SshTunnel.SshEnvironmentManager;
const make = Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>();
const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts));
const passwordPrompt = SshPasswordPrompt.of(makePasswordPrompt(prompts));
return DesktopSshEnvironment.of({
discoverHosts: (input) =>
@@ -140,7 +120,7 @@ export const make = Effect.gen(function* () {
manager
.ensureEnvironment(target, ensureOptions)
.pipe(
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
Effect.provideService(SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.ensureEnvironment"),
),
@@ -148,7 +128,7 @@ export const make = Effect.gen(function* () {
manager
.disconnectEnvironment(target)
.pipe(
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
Effect.provideService(SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
),
@@ -158,7 +138,7 @@ export const make = Effect.gen(function* () {
export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) =>
Layer.effect(DesktopSshEnvironment, make).pipe(
Layer.provide(
SshTunnel.SshEnvironmentManager.layer({
SshEnvironmentManager.layer({
...(options.resolveCliPackageSpec === undefined
? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
@@ -9,7 +9,7 @@ import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { SSH_PASSWORD_PROMPT_CHANNEL } from "../ipc/channels.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
interface SentMessage {
@@ -111,7 +111,7 @@ describe("DesktopSshPasswordPrompts", () => {
assert.equal(testWindow.sentMessages.length, 1);
const sent = testWindow.sentMessages[0];
assert.ok(sent);
assert.equal(sent.channel, SSH_PASSWORD_PROMPT_CHANNEL);
assert.equal(sent.channel, IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL);
const request = sent.args[0] as { readonly requestId: string; readonly destination: string };
assert.equal(request.destination, "devbox");
assert.equal(testWindow.isRestored(), true);
+95 -143
View File
@@ -3,6 +3,7 @@ import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contract
import type { SshPasswordRequest } from "@t3tools/ssh/auth";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
@@ -10,134 +11,93 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as IpcChannels from "../ipc/channels.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { SSH_PASSWORD_PROMPT_CHANNEL } from "../ipc/channels.ts";
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
type DesktopSshPasswordPromptResolutionInput =
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
"DesktopSshPromptRequestIdGenerationError",
{
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Secure randomness is unavailable.";
export class DesktopSshPromptUnavailableError extends Data.TaggedError(
"DesktopSshPromptUnavailableError",
)<{
readonly reason: string;
}> {
override get message() {
return this.reason;
}
}
export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorClass<DesktopSshPromptWindowUnavailableError>()(
export class DesktopSshPromptWindowUnavailableError extends Data.TaggedError(
"DesktopSshPromptWindowUnavailableError",
{
destination: Schema.String,
},
) {
override get message(): string {
)<{
readonly destination: string;
}> {
override get message() {
return WINDOW_UNAVAILABLE_MESSAGE;
}
}
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
"DesktopSshPromptPresentationError",
{
requestId: Schema.String,
destination: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to present SSH password prompt for ${this.destination}.`;
export class DesktopSshPromptSendError extends Data.TaggedError("DesktopSshPromptSendError")<{
readonly requestId: string;
readonly destination: string;
readonly cause: unknown;
}> {
override get message() {
return WINDOW_UNAVAILABLE_MESSAGE;
}
}
export class DesktopSshPromptTimedOutError extends Schema.TaggedErrorClass<DesktopSshPromptTimedOutError>()(
export class DesktopSshPromptTimedOutError extends Data.TaggedError(
"DesktopSshPromptTimedOutError",
{
requestId: Schema.String,
destination: Schema.String,
},
) {
override get message(): string {
)<{
readonly requestId: string;
readonly destination: string;
}> {
override get message() {
return `SSH authentication timed out for ${this.destination}.`;
}
}
export class DesktopSshPromptCancelledError extends Schema.TaggedErrorClass<DesktopSshPromptCancelledError>()(
export class DesktopSshPromptCancelledError extends Data.TaggedError(
"DesktopSshPromptCancelledError",
{
requestId: Schema.String,
destination: Schema.String,
},
) {
override get message(): string {
return `SSH authentication cancelled for ${this.destination}.`;
)<{
readonly requestId: string;
readonly destination: string;
readonly reason: string;
}> {
override get message() {
return this.reason;
}
}
export class DesktopSshPromptWindowClosedError extends Schema.TaggedErrorClass<DesktopSshPromptWindowClosedError>()(
"DesktopSshPromptWindowClosedError",
{
requestId: Schema.String,
destination: Schema.String,
},
) {
override get message(): string {
return "SSH authentication was cancelled because the app window closed.";
}
}
export class DesktopSshPromptServiceStoppedError extends Schema.TaggedErrorClass<DesktopSshPromptServiceStoppedError>()(
"DesktopSshPromptServiceStoppedError",
{
requestId: Schema.String,
destination: Schema.String,
},
) {
override get message(): string {
return "SSH password prompt service stopped.";
}
}
export class DesktopSshPromptInvalidRequestIdError extends Schema.TaggedErrorClass<DesktopSshPromptInvalidRequestIdError>()(
export class DesktopSshPromptInvalidRequestIdError extends Data.TaggedError(
"DesktopSshPromptInvalidRequestIdError",
{
requestId: Schema.String,
},
) {
override get message(): string {
)<{
readonly requestId: string;
}> {
override get message() {
return "Invalid SSH password prompt id.";
}
}
export class DesktopSshPromptExpiredError extends Schema.TaggedErrorClass<DesktopSshPromptExpiredError>()(
"DesktopSshPromptExpiredError",
{
requestId: Schema.String,
},
) {
override get message(): string {
export class DesktopSshPromptExpiredError extends Data.TaggedError("DesktopSshPromptExpiredError")<{
readonly requestId: string;
}> {
override get message() {
return "SSH password prompt expired. Try connecting again.";
}
}
export type DesktopSshPasswordPromptRequestError =
| DesktopSshPromptRequestIdGenerationError
| DesktopSshPromptUnavailableError
| DesktopSshPromptWindowUnavailableError
| DesktopSshPromptPresentationError
| DesktopSshPromptSendError
| DesktopSshPromptTimedOutError
| DesktopSshPromptCancelledError
| DesktopSshPromptWindowClosedError
| DesktopSshPromptServiceStoppedError;
| DesktopSshPromptCancelledError;
export type DesktopSshPasswordPromptResolveError =
| DesktopSshPromptInvalidRequestIdError
@@ -147,28 +107,28 @@ export type DesktopSshPasswordPromptError =
| DesktopSshPasswordPromptRequestError
| DesktopSshPasswordPromptResolveError;
export const DesktopSshPasswordPromptCancellation = Schema.Union([
DesktopSshPromptCancelledError,
DesktopSshPromptWindowClosedError,
DesktopSshPromptServiceStoppedError,
DesktopSshPromptTimedOutError,
]);
export type DesktopSshPasswordPromptCancellation = typeof DesktopSshPasswordPromptCancellation.Type;
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is DesktopSshPromptCancelledError | DesktopSshPromptTimedOutError {
return (
error instanceof DesktopSshPromptCancelledError ||
error instanceof DesktopSshPromptTimedOutError
);
}
export const isDesktopSshPasswordPromptCancellation = Schema.is(
DesktopSshPasswordPromptCancellation,
);
export interface DesktopSshPasswordPromptsShape {
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
readonly resolve: (
input: DesktopSshPasswordPromptResolutionInput,
) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
readonly cancelPending: (reason: string) => Effect.Effect<void>;
}
export class DesktopSshPasswordPrompts extends Context.Service<
DesktopSshPasswordPrompts,
{
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
readonly resolve: (
input: DesktopSshPasswordPromptResolutionInput,
) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
}
DesktopSshPasswordPromptsShape
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
interface PendingSshPasswordPrompt {
@@ -177,7 +137,7 @@ interface PendingSshPasswordPrompt {
readonly deferred: Deferred.Deferred<string, DesktopSshPasswordPromptRequestError>;
}
export interface DesktopSshPasswordPromptsOptions {
interface LayerOptions {
readonly passwordPromptTimeoutMs?: number;
}
@@ -201,16 +161,14 @@ const failPending = (
error: DesktopSshPasswordPromptRequestError,
) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid);
export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
options: DesktopSshPasswordPromptsOptions = {},
) {
const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const crypto = yield* Crypto.Crypto;
const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
const passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
const cancelPending = () =>
const cancelPending = (reason: string): Effect.Effect<void> =>
Ref.getAndSet(pendingRef, new Map()).pipe(
Effect.flatMap((pending) =>
Effect.forEach(
@@ -218,9 +176,10 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
(entry) =>
failPending(
entry,
new DesktopSshPromptServiceStoppedError({
new DesktopSshPromptCancelledError({
requestId: entry.requestId,
destination: entry.destination,
reason,
}),
),
{ discard: true },
@@ -229,11 +188,13 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
Effect.asVoid,
);
yield* Effect.addFinalizer(() => cancelPending().pipe(Effect.ignore));
yield* Effect.addFinalizer(() =>
cancelPending("SSH password prompt service stopped.").pipe(Effect.ignore),
);
const resolve: DesktopSshPasswordPrompts["Service"]["resolve"] = Effect.fn(
"desktop.sshPasswordPrompts.resolve",
)(function* (input) {
const resolve = Effect.fn("desktop.sshPasswordPrompts.resolve")(function* (
input: DesktopSshPasswordPromptResolutionInput,
): Effect.fn.Return<void, DesktopSshPasswordPromptResolveError> {
const requestId = input.requestId.trim();
if (requestId.length === 0) {
return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId });
@@ -251,6 +212,7 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
new DesktopSshPromptCancelledError({
requestId,
destination: entry.destination,
reason: `SSH authentication cancelled for ${entry.destination}.`,
}),
);
return;
@@ -259,9 +221,9 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid);
});
const request: DesktopSshPasswordPrompts["Service"]["request"] = Effect.fn(
"desktop.sshPasswordPrompts.request",
)(function* (input) {
const request = Effect.fn("desktop.sshPasswordPrompts.request")(function* (
input: SshPasswordRequest,
): Effect.fn.Return<string, DesktopSshPasswordPromptRequestError> {
const window = yield* electronWindow.main;
if (Option.isNone(window) || window.value.isDestroyed()) {
return yield* new DesktopSshPromptWindowUnavailableError({
@@ -271,11 +233,7 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
const requestId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new DesktopSshPromptRequestIdGenerationError({
destination: input.destination,
cause,
}),
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
),
);
const now = yield* DateTime.now;
@@ -309,9 +267,10 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
onSome: (pending) =>
failPending(
pending,
new DesktopSshPromptWindowClosedError({
new DesktopSshPromptCancelledError({
requestId,
destination: input.destination,
reason: "SSH authentication was cancelled because the app window closed.",
}),
),
}),
@@ -343,43 +302,36 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
return yield* Effect.try({
try: () => {
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
}
window.value.once("closed", cancelOnWindowClosed);
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
window.value.webContents.send(IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
}
if (window.value.isMinimized()) {
window.value.restore();
}
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
}
window.value.focus();
},
catch: (cause) =>
isDesktopSshPromptWindowUnavailableError(cause)
? cause
: new DesktopSshPromptPresentationError({
requestId,
destination: input.destination,
cause,
}),
new DesktopSshPromptSendError({
requestId,
destination: input.destination,
cause,
}),
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
});
return DesktopSshPasswordPrompts.of({
request,
resolve,
cancelPending,
});
});
export const layer = (options: DesktopSshPasswordPromptsOptions = {}) =>
export const layer = (options: LayerOptions = {}) =>
Layer.effect(DesktopSshPasswordPrompts, make(options));
@@ -83,7 +83,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
}),
).pipe(Effect.asVoid),
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
} satisfies ElectronUpdater.ElectronUpdaterShape);
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
create: () => Effect.die("unexpected BrowserWindow creation"),
@@ -99,7 +99,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
}),
destroyAll: Effect.void,
syncAllAppearance: () => Effect.void,
} satisfies ElectronWindow.ElectronWindow["Service"]);
} satisfies ElectronWindow.ElectronWindowShape);
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
+30 -31
View File
@@ -7,6 +7,7 @@ import type {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -59,26 +60,23 @@ const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressIn
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<DesktopUpdateActionInProgressError>()(
export class DesktopUpdateActionInProgressError extends Data.TaggedError(
"DesktopUpdateActionInProgressError",
{
action: Schema.Literals(["check", "download", "install"]),
},
) {
override get message(): string {
)<{
readonly action: "check" | "download" | "install";
}> {
override get message() {
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
}
}
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
export class DesktopUpdatePersistenceError extends Data.TaggedError(
"DesktopUpdatePersistenceError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
return `Failed to persist desktop update settings: ${detail}`;
)<{
readonly cause: DesktopAppSettings.DesktopSettingsWriteError;
}> {
override get message() {
return "Failed to persist desktop update settings.";
}
}
@@ -88,21 +86,22 @@ export type DesktopUpdateSetChannelError =
| DesktopUpdateActionInProgressError
| DesktopUpdatePersistenceError;
export class DesktopUpdates extends Context.Service<
DesktopUpdates,
{
readonly getState: Effect.Effect<DesktopUpdateState>;
readonly emitState: Effect.Effect<void>;
readonly disabledReason: Effect.Effect<Option.Option<string>>;
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
readonly setChannel: (
channel: DesktopUpdateChannel,
) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
readonly download: Effect.Effect<DesktopUpdateActionResult>;
readonly install: Effect.Effect<DesktopUpdateActionResult>;
}
>()("@t3tools/desktop/updates/DesktopUpdates") {}
export interface DesktopUpdatesShape {
readonly getState: Effect.Effect<DesktopUpdateState>;
readonly emitState: Effect.Effect<void>;
readonly disabledReason: Effect.Effect<Option.Option<string>>;
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
readonly setChannel: (
channel: DesktopUpdateChannel,
) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
readonly download: Effect.Effect<DesktopUpdateActionResult>;
readonly install: Effect.Effect<DesktopUpdateActionResult>;
}
export class DesktopUpdates extends Context.Service<DesktopUpdates, DesktopUpdatesShape>()(
"@t3tools/desktop/updates/DesktopUpdates",
) {}
const {
logInfo: logUpdaterInfo,
@@ -128,7 +127,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
function createBaseUpdateState(
channel: DesktopUpdateChannel,
enabled: boolean,
environment: DesktopEnvironment.DesktopEnvironment["Service"],
environment: DesktopEnvironment.DesktopEnvironmentShape,
): DesktopUpdateState {
return {
...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
@@ -186,7 +185,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
}
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const desktopState = yield* DesktopState.DesktopState;
@@ -46,14 +46,14 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
} satisfies ElectronApp.ElectronAppShape);
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
} satisfies ElectronDialog.ElectronDialogShape);
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
getState: Effect.die("unexpected getState"),
@@ -64,7 +64,7 @@ const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
check: () => Effect.die("unexpected check"),
download: Effect.die("unexpected download"),
install: Effect.die("unexpected install"),
} satisfies DesktopUpdates.DesktopUpdates["Service"]);
} satisfies DesktopUpdates.DesktopUpdatesShape);
const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
Layer.succeed(DesktopWindow.DesktopWindow, {
@@ -76,7 +76,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
handleBackendReady: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
} satisfies DesktopWindow.DesktopWindowShape);
const makeElectronMenuLayer = (
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
@@ -86,7 +86,7 @@ const makeElectronMenuLayer = (
Deferred.succeed(applicationMenuTemplate, template).pipe(Effect.asVoid),
popupTemplate: () => Effect.void,
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
} satisfies ElectronMenu.ElectronMenuShape);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
import type * as Electron from "electron";
import { makeComponentLogger } from "../app/DesktopObservability.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
@@ -14,11 +14,13 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
export interface DesktopApplicationMenuShape {
readonly configure: Effect.Effect<void>;
}
export class DesktopApplicationMenu extends Context.Service<
DesktopApplicationMenu,
{
readonly configure: Effect.Effect<void>;
}
DesktopApplicationMenuShape
>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
type DesktopApplicationMenuRuntimeServices =
@@ -26,9 +28,9 @@ type DesktopApplicationMenuRuntimeServices =
| DesktopWindow.DesktopWindow
| ElectronDialog.ElectronDialog;
const { logInfo: logUpdaterInfo } = makeComponentLogger("desktop-updater");
const { logInfo: logUpdaterInfo } = DesktopObservability.makeComponentLogger("desktop-updater");
const { logError: logMenuError } = makeComponentLogger("desktop-menu");
const { logError: logMenuError } = DesktopObservability.makeComponentLogger("desktop-menu");
const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function* (
action: string,
@@ -37,7 +39,11 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
yield* desktopWindow.dispatchMenuAction(action);
});
const checkForUpdatesFromMenu = Effect.gen(function* () {
const checkForUpdatesFromMenu: Effect.Effect<
void,
never,
DesktopUpdates.DesktopUpdates | ElectronDialog.ElectronDialog
> = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
const result = yield* updates.check("menu");
@@ -61,7 +67,11 @@ const checkForUpdatesFromMenu = Effect.gen(function* () {
}
}).pipe(Effect.withSpan("desktop.menu.checkForUpdates"));
const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
const handleCheckForUpdatesMenuClick: Effect.Effect<
void,
DesktopWindow.DesktopWindowError,
DesktopUpdates.DesktopUpdates | ElectronDialog.ElectronDialog | DesktopWindow.DesktopWindow
> = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
const disabledReason = yield* updates.disabledReason;
@@ -84,7 +94,7 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
yield* checkForUpdatesFromMenu;
}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronMenu = yield* ElectronMenu.ElectronMenu;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
+11 -11
View File
@@ -91,7 +91,7 @@ const desktopAssetsLayer = Layer.succeed(DesktopAssets.DesktopAssets, {
png: Option.none<string>(),
}),
resolveResourcePath: () => Effect.succeed(Option.none<string>()),
} satisfies DesktopAssets.DesktopAssets["Service"]);
} satisfies DesktopAssets.DesktopAssetsShape);
const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"),
@@ -106,19 +106,19 @@ const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopSe
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.die("unexpected getAdvertisedEndpoints"),
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
} satisfies DesktopServerExposure.DesktopServerExposureShape);
const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
setApplicationMenu: () => Effect.void,
popupTemplate: () => Effect.void,
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
} satisfies ElectronMenu.ElectronMenuShape);
const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
shouldUseDarkColors: Effect.succeed(false),
setSource: () => Effect.void,
onUpdated: () => Effect.void,
} satisfies ElectronTheme.ElectronTheme["Service"]);
} satisfies ElectronTheme.ElectronThemeShape);
const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(
@@ -156,7 +156,7 @@ function makeTestLayer(input: {
sendAll: () => Effect.void,
destroyAll: Effect.void,
syncAllAppearance: (sync) => sync(input.window),
} satisfies ElectronWindow.ElectronWindow["Service"]);
} satisfies ElectronWindow.ElectronWindowShape);
return DesktopWindow.layer.pipe(
Layer.provide(
@@ -173,7 +173,7 @@ function makeTestLayer(input: {
return true;
}),
copyText: () => Effect.void,
} satisfies ElectronShell.ElectronShell["Service"]),
} satisfies ElectronShell.ElectronShellShape),
electronThemeLayer,
electronWindowLayer,
Layer.mock(PreviewManager.PreviewManager)({
@@ -191,19 +191,19 @@ describe("DesktopWindow", () => {
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "t3code://app/",
navigationUrl: "t3code://app/settings/connections",
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/connections",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "t3code://app/",
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "https://accounts.microsoft.com/oauth",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "t3code://app/",
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "not a url",
}),
);
@@ -231,7 +231,7 @@ describe("DesktopWindow", () => {
assert.equal(yield* Ref.get(createCount), 1);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["http://127.0.0.1:5733/"]);
assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
}).pipe(Effect.provide(layer));
}),
+50 -26
View File
@@ -1,4 +1,5 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -8,15 +9,15 @@ import type * as Electron from "electron";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { makeComponentLogger } from "../app/DesktopObservability.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as PreviewManager from "../preview/Manager.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import * as PreviewManager from "../preview/Manager.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
@@ -31,6 +32,7 @@ type WindowTitleBarOptions = Pick<
type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
| DesktopServerExposure.DesktopServerExposure
| DesktopState.DesktopState
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
@@ -38,26 +40,45 @@ type DesktopWindowRuntimeServices =
| ElectronWindow.ElectronWindow
| PreviewManager.PreviewManager;
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
"DesktopWindowDevServerUrlMissingError",
)<{}> {
override get message() {
return "VITE_DEV_SERVER_URL is required in desktop development.";
}
}
export type DesktopWindowError =
| DesktopWindowDevServerUrlMissingError
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
export class DesktopWindow extends Context.Service<
DesktopWindow,
{
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly activate: Effect.Effect<void, DesktopWindowError>;
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
>()("@t3tools/desktop/window/DesktopWindow") {}
export interface DesktopWindowShape {
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly activate: Effect.Effect<void, DesktopWindowError>;
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowShape>()(
"@t3tools/desktop/window/DesktopWindow",
) {}
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
makeComponentLogger("desktop-window");
DesktopObservability.makeComponentLogger("desktop-window");
function resolveDesktopDevServerUrl(
environment: DesktopEnvironment.DesktopEnvironmentShape,
): Effect.Effect<string, DesktopWindowDevServerUrlMissingError> {
return Option.match(environment.devServerUrl, {
onNone: () => Effect.fail(new DesktopWindowDevServerUrlMissingError()),
onSome: (url) => Effect.succeed(url.href),
});
}
function getIconOption(
iconPaths: DesktopAssets.DesktopIconPaths,
@@ -142,7 +163,7 @@ function bindFirstRevealTrigger(
}
}
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const assets = yield* DesktopAssets.DesktopAssets;
const electronMenu = yield* ElectronMenu.ElectronMenu;
@@ -150,16 +171,18 @@ export const make = Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runPromise = Effect.runPromiseWith(context);
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
Electron.BrowserWindow,
DesktopWindowError
> {
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
backendHttpUrl: URL,
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
yield* previewManager.getBrowserSession();
const applicationUrl = getDesktopUrl(environment.isDevelopment);
const applicationUrl = environment.isDevelopment
? yield* resolveDesktopDevServerUrl(environment)
: backendHttpUrl.href;
const iconPaths = yield* assets.iconPaths;
const iconOption = getIconOption(iconPaths, environment.platform);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
@@ -327,7 +350,8 @@ export const make = Effect.gen(function* () {
});
const createMain = Effect.gen(function* () {
const window = yield* createWindow();
const backendConfig = yield* serverExposure.backendConfig;
const window = yield* createWindow(backendConfig.httpBaseUrl);
yield* electronWindow.setMain(window);
yield* logWindowInfo("main window created");
return window;
@@ -380,7 +404,7 @@ export const make = Effect.gen(function* () {
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
targetWindow.webContents.send(IpcChannels.MENU_ACTION_CHANNEL, action);
void runPromise(electronWindow.reveal(targetWindow));
};
-6
View File
@@ -56,12 +56,6 @@ export default defineConfig({
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/preload.ts"],
deps: {
// Sandboxed Electron preloads cannot reliably resolve package imports
// from inside the packaged ASAR. Bundle Clerk's preload bridge into the
// preload artifact instead of leaving a runtime require() behind.
alwaysBundle: (id) => id === "@clerk/electron" || id.startsWith("@clerk/electron/"),
},
},
{
format: "cjs",
-1
View File
@@ -1,6 +1,5 @@
included:
- ios/T3Code
- modules/t3-composer-editor/ios
- modules/t3-terminal/ios
- modules/t3-review-diff/ios
+1 -21
View File
@@ -192,31 +192,11 @@
}
}
/* ─── Typography ────────────────────────────────────────────────────── */
/* ─── Font family ───────────────────────────────────────────────────── */
@theme {
--font-sans: "DMSans_400Regular";
--font-medium: "DMSans_500Medium";
--font-bold: "DMSans_700Bold";
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
--text-3xs: 10px;
--text-3xs--line-height: 13px;
--text-2xs: 11px;
--text-2xs--line-height: 15px;
--text-xs: 12px;
--text-xs--line-height: 16px;
--text-sm: 13px;
--text-sm--line-height: 18px;
--text-base: 15px;
--text-base--line-height: 22px;
--text-lg: 17px;
--text-lg--line-height: 22px;
--text-xl: 20px;
--text-xl--line-height: 26px;
--text-2xl: 24px;
--text-2xl--line-height: 30px;
--text-3xl: 28px;
--text-3xl--line-height: 34px;
}
/* ─── Custom utilities ──────────────────────────────────────────────── */
@@ -275,8 +275,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
fileTint: "#737373"
)
private var fontFamily = "DMSans_400Regular"
private var fontSize: CGFloat = 14
private var lineHeight: CGFloat = 20
private var fontSize: CGFloat = 15
private var lineHeight: CGFloat = 22
private var contentInsetVertical: CGFloat = 0
private var shouldAutoFocus = false
private var didAutoFocus = false
@@ -460,19 +460,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
guard !isApplyingControlledValue else {
return
}
restoreBaseTypingAttributes()
emitSelection()
}
public func textView(
_ textView: UITextView,
shouldChangeTextIn range: NSRange,
replacementText text: String
) -> Bool {
restoreBaseTypingAttributes()
return true
}
public func textViewDidBeginEditing(_ textView: UITextView) {
onComposerFocus()
}
@@ -494,7 +484,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
let targetSelection = requestedSelection ?? previousSelection
requestedSelection = nil
textView.selectedRange = displayRange(for: targetSelection)
restoreBaseTypingAttributes()
isApplyingControlledValue = false
updatePlaceholderVisibility()
emitContentSizeIfNeeded()
@@ -567,12 +556,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
size: image.size,
baselineOffset: baselineOffset
)
let attributedAttachment = NSMutableAttributedString(attachment: attachment)
attributedAttachment.addAttributes(
baseAttributes(),
range: NSRange(location: 0, length: attributedAttachment.length)
)
return attributedAttachment
return NSAttributedString(attachment: attachment)
}
private func renderChip(
@@ -676,18 +660,11 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
let font = UIFont(name: fontFamily, size: fontSize)
?? UIFont.systemFont(ofSize: fontSize)
textView.font = font
restoreBaseTypingAttributes()
textView.typingAttributes = baseAttributes()
placeholderLabel.font = font
setNeedsLayout()
}
private func restoreBaseTypingAttributes() {
guard textView.markedTextRange == nil else {
return
}
textView.typingAttributes = baseAttributes()
}
private func applyTheme() {
textView.textColor = UIColor(composerHex: theme.text) ?? .label
placeholderLabel.textColor = UIColor(composerHex: theme.placeholder) ?? .placeholderText
@@ -70,12 +70,7 @@ static void T3MarkdownTextApplyAttachments(
renderingMode:UIImageRenderingModeAlwaysOriginal];
}
attachment.image = image ?: [[UIImage alloc] init];
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
@@ -85,6 +80,104 @@ static void T3MarkdownTextApplyAttachments(
}
}
static NSArray<NSDictionary<NSString *, id> *> *T3MarkdownTextExtractChipBackgrounds(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextChipRange> &chipRanges)
{
NSMutableArray<NSDictionary<NSString *, id> *> *backgrounds = [NSMutableArray array];
for (const auto &chipRange : chipRanges) {
if (chipRange.length == 0 || chipRange.location >= attributedString.length) {
continue;
}
const NSRange range = NSMakeRange(
chipRange.location,
MIN(chipRange.length, attributedString.length - chipRange.location));
UIColor *color = [attributedString attribute:NSBackgroundColorAttributeName
atIndex:range.location
effectiveRange:nil];
UIColor *foregroundColor = [attributedString attribute:NSForegroundColorAttributeName
atIndex:range.location
effectiveRange:nil];
if (color == nil) {
continue;
}
[backgrounds addObject:@{
@"range": [NSValue valueWithRange:range],
@"color": color,
@"strokeColor": [foregroundColor
colorWithAlphaComponent:chipRange.isSkill ? 0.25 : 0.1] ?: UIColor.clearColor,
}];
[attributedString removeAttribute:NSBackgroundColorAttributeName range:range];
}
return backgrounds;
}
@interface T3MarkdownTextBackingView : UITextView
@property(nonatomic, copy) NSArray<NSDictionary<NSString *, id> *> *chipBackgrounds;
@end
@implementation T3MarkdownTextBackingView
- (void)drawRect:(CGRect)rect
{
[self.layoutManager ensureLayoutForTextContainer:self.textContainer];
CGContextRef context = UIGraphicsGetCurrentContext();
if (context != nil) {
CGContextSaveGState(context);
CGContextResetClip(context);
CGContextClipToRect(context, self.bounds);
}
for (NSDictionary<NSString *, id> *background in self.chipBackgrounds) {
const NSRange characterRange = [background[@"range"] rangeValue];
UIColor *color = background[@"color"];
UIColor *strokeColor = background[@"strokeColor"];
if (characterRange.length == 0 || NSMaxRange(characterRange) > self.textStorage.length) {
continue;
}
const NSRange glyphRange =
[self.layoutManager glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
[color setFill];
[self.layoutManager
enumerateEnclosingRectsForGlyphRange:glyphRange
withinSelectedGlyphRange:NSMakeRange(NSNotFound, 0)
inTextContainer:self.textContainer
usingBlock:^(CGRect glyphRect, BOOL *stop) {
const CGFloat chipHeight = 22;
CGRect chipRect = CGRectMake(
glyphRect.origin.x - 4,
CGRectGetMidY(glyphRect) - chipHeight / 2,
glyphRect.size.width + 8,
chipHeight);
chipRect.origin.x += self.textContainerInset.left;
chipRect.origin.y += self.textContainerInset.top;
const CGFloat minimumX = self.textContainerInset.left + 0.5;
const CGFloat maximumX =
CGRectGetWidth(self.bounds) - self.textContainerInset.right - 0.5;
if (chipRect.origin.x < minimumX) {
chipRect.size.width -= minimumX - chipRect.origin.x;
chipRect.origin.x = minimumX;
}
if (CGRectGetMaxX(chipRect) > maximumX) {
chipRect.size.width = MAX(0, maximumX - chipRect.origin.x);
}
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:chipRect cornerRadius:6];
[path fill];
[strokeColor setStroke];
path.lineWidth = 1;
[path stroke];
}];
}
if (context != nil) {
CGContextRestoreGState(context);
}
[super drawRect:rect];
}
@end
@protocol T3MarkdownOutsideTapTarget <NSObject>
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
@end
@@ -192,7 +285,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
@implementation T3MarkdownText {
UIView * _view;
UITextView * _textView;
T3MarkdownTextBackingView * _textView;
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
__weak UIWindow * _outsideTapWindow;
BOOL _suppressSelectionChange;
@@ -215,7 +308,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
self.contentView = _view;
self.clipsToBounds = true;
_textView = [[UITextView alloc] init];
_textView = [[T3MarkdownTextBackingView alloc] init];
_attachmentImages = [[NSMutableDictionary alloc] init];
_pendingAttachmentUris = [[NSMutableSet alloc] init];
_textView.scrollEnabled = false;
@@ -312,6 +405,9 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
convertedAttrString,
_state->getData().attachmentRanges,
_attachmentImages);
_textView.chipBackgrounds = T3MarkdownTextExtractChipBackgrounds(
convertedAttrString,
_state->getData().chipRanges);
[self loadAttachmentImages:_state->getData().attachmentRanges];
// Setting attributedText clears any active text selection, and re-assigning
@@ -28,20 +28,18 @@ struct T3MarkdownTextAttachmentRange {
std::string imageUri;
};
inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
return 14;
}
inline Float T3MarkdownTextAttachmentBaselineOffset(
const T3MarkdownTextAttachmentRange &) {
return -2;
}
struct T3MarkdownTextChipRange {
size_t location;
size_t length;
bool isSkill;
};
class T3MarkdownTextStateReal final {
public:
AttributedString attributedString;
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
std::vector<T3MarkdownTextChipRange> chipRanges;
};
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
@@ -74,5 +72,6 @@ private:
mutable AttributedString _attributedString;
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
mutable std::vector<T3MarkdownTextChipRange> _chipRanges;
};
} // namespace facebook::React
@@ -9,8 +9,9 @@
namespace facebook::react {
static constexpr Float ParagraphStyleEncodingOffset = 1000;
static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
static constexpr auto ChipNativeIdPrefix = "t3-chip-";
static constexpr auto FileChipNativeIdPrefix = "t3-chip-file:";
static constexpr auto SkillChipNativeIdPrefix = "t3-chip-skill:";
static void applyParagraphStyles(
NSMutableAttributedString *attributedString,
@@ -57,12 +58,7 @@ static void applyAttachments(
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [[UIImage alloc] init];
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
@@ -95,6 +91,7 @@ Size T3MarkdownTextShadowNode::measureContent(
auto baseAttributedString = AttributedString{};
auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
auto chipRanges = std::vector<T3MarkdownTextChipRange>{};
size_t utf16Offset = 0;
const auto &children = getChildren();
for (size_t i = 0; i < children.size(); i++) {
@@ -187,19 +184,25 @@ Size T3MarkdownTextShadowNode::measureContent(
props.shadowRadius - ParagraphStyleEncodingOffset,
});
}
if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
if (props.nativeId.rfind(ChipNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
chipRanges.push_back(T3MarkdownTextChipRange{
utf16Offset,
fragmentLength,
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0,
});
}
if (props.nativeId.rfind(FileChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset + 1,
1,
props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
props.nativeId.substr(std::char_traits<char>::length(FileChipNativeIdPrefix)),
});
} else if (
props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset,
utf16Offset + 1,
1,
props.nativeId.substr(
std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
props.nativeId.substr(std::char_traits<char>::length(SkillChipNativeIdPrefix)),
});
}
utf16Offset += fragmentLength;
@@ -210,6 +213,7 @@ Size T3MarkdownTextShadowNode::measureContent(
_attributedString = baseAttributedString;
_paragraphStyleRanges = paragraphStyleRanges;
_attachmentRanges = attachmentRanges;
_chipRanges = chipRanges;
NSMutableAttributedString *convertedAttributedString =
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
@@ -259,6 +263,7 @@ void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
_attributedString,
_paragraphStyleRanges,
_attachmentRanges,
_chipRanges,
});
}
}
@@ -1,19 +1,16 @@
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { execFileSync } from "node:child_process";
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { getBuiltInSpriteSheet } from "@pierre/trees";
const scriptDirectory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const moduleDirectory = NodePath.resolve(scriptDirectory, "..");
const repositoryRoot = NodePath.resolve(moduleDirectory, "../../../..");
const outputDirectory = NodePath.join(moduleDirectory, "assets/file-icons");
const generatedModulePath = NodePath.join(moduleDirectory, "src/markdownFileIcons.generated.ts");
const webIconSource = NodeFS.readFileSync(
NodePath.join(repositoryRoot, "apps/web/src/pierre-icons.ts"),
"utf8",
);
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const moduleDirectory = resolve(scriptDirectory, "..");
const repositoryRoot = resolve(moduleDirectory, "../../../..");
const outputDirectory = join(moduleDirectory, "assets/file-icons");
const generatedModulePath = join(moduleDirectory, "src/markdownFileIcons.generated.ts");
const webIconSource = readFileSync(join(repositoryRoot, "apps/web/src/pierre-icons.ts"), "utf8");
const customSprite = webIconSource.match(/const T3_FILE_ICON_SPRITE = `([\s\S]*?)`;/)?.[1];
if (!customSprite) {
@@ -98,20 +95,20 @@ function symbolFromSprite(sprite, id) {
}
function renderIcon(token, symbol, color) {
const svgPath = NodePath.join(outputDirectory, `.pierre-${token}.svg`);
const pngPath = NodePath.join(outputDirectory, `pierre_${token}.png`);
NodeFS.writeFileSync(
const svgPath = join(outputDirectory, `.pierre-${token}.svg`);
const pngPath = join(outputDirectory, `pierre_${token}.png`);
writeFileSync(
svgPath,
`<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="${symbol.viewBox}" style="color:${color}">${symbol.body}</svg>`,
);
NodeChildProcess.execFileSync("sips", ["-s", "format", "png", svgPath, "--out", pngPath], {
execFileSync("sips", ["-s", "format", "png", svgPath, "--out", pngPath], {
stdio: "ignore",
});
NodeFS.rmSync(svgPath);
rmSync(svgPath);
}
NodeFS.rmSync(outputDirectory, { recursive: true, force: true });
NodeFS.mkdirSync(outputDirectory, { recursive: true });
rmSync(outputDirectory, { recursive: true, force: true });
mkdirSync(outputDirectory, { recursive: true });
const builtInSprite = getBuiltInSpriteSheet("complete");
const builtInTokens = [...builtInSprite.matchAll(/<symbol id="file-tree-builtin-([^"]+)"/g)]
@@ -133,4 +130,4 @@ const tokens = [...new Set([...builtInTokens, ...Object.keys(customIcons)])].sor
const generatedSource = `import type { ImageSourcePropType } from "react-native";\n\nexport const MARKDOWN_FILE_ICON_SOURCES = {\n${tokens
.map((token) => ` ${token}: require("../assets/file-icons/pierre_${token}.png"),`)
.join("\n")}\n} as const satisfies Readonly<Record<string, ImageSourcePropType>>;\n`;
NodeFS.writeFileSync(generatedModulePath, generatedSource);
writeFileSync(generatedModulePath, generatedSource);
@@ -40,13 +40,11 @@ function documentFor(node: MarkdownNode): MarkdownNode {
function SelectableNode(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<NativeMarkdownSelectableText
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
}
@@ -314,7 +312,6 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
function NativeTable(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const rows = collectTableRows(props.node);
return (
@@ -354,7 +351,6 @@ function NativeTable(props: {
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
)}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
</View>
))}
@@ -368,17 +364,10 @@ function NativeTable(props: {
function NativeMarkdownImage(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const href = props.node.href;
if (!href) {
return (
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
}
return (
@@ -437,7 +426,6 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
function NativeMixedParagraph(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<View style={{ gap: 8 }}>
@@ -447,15 +435,9 @@ function NativeMixedParagraph(props: {
key={nodeKey(child, index)}
node={child}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
) : (
<SelectableNode
key={nodeKey(child, index)}
node={child}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
<SelectableNode key={nodeKey(child, index)} node={child} textStyle={props.textStyle} />
),
)}
</View>
@@ -466,7 +448,6 @@ function NativeList(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
readonly depth: number;
}) {
const ordered = props.node.ordered ?? false;
@@ -527,7 +508,6 @@ function NativeList(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={props.depth + 1}
compact
/>
@@ -544,7 +524,6 @@ export function NativeMarkdownBlock(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
readonly depth?: number;
readonly compact?: boolean;
}) {
@@ -559,7 +538,6 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
/>
))}
@@ -575,21 +553,9 @@ export function NativeMarkdownBlock(props: {
/>
);
case "table":
return (
<NativeTable
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
return <NativeTable node={props.node} textStyle={props.textStyle} />;
case "image":
return (
<NativeMarkdownImage
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
return <NativeMarkdownImage node={props.node} textStyle={props.textStyle} />;
case "horizontal_rule":
return (
<View
@@ -617,7 +583,6 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
@@ -630,23 +595,14 @@ export function NativeMarkdownBlock(props: {
node={props.node}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
/>
);
case "paragraph":
return (props.node.children ?? []).some((child) => child.type === "image") ? (
<NativeMixedParagraph
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
<NativeMixedParagraph node={props.node} textStyle={props.textStyle} />
) : (
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
<SelectableNode node={props.node} textStyle={props.textStyle} />
);
case "html_block":
case "math_block":
@@ -662,11 +618,7 @@ export function NativeMarkdownBlock(props: {
: "transparent",
}}
>
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
<SelectableNode node={props.node} textStyle={props.textStyle} />
</View>
);
case "table_head":
@@ -683,7 +635,6 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
@@ -691,12 +642,6 @@ export function NativeMarkdownBlock(props: {
</View>
);
default:
return (
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
}
}
@@ -1,15 +1,61 @@
import { useEffect, useMemo, useState } from "react";
import { Asset } from "expo-asset";
import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import { markdownFileIconSource } from "./markdownFileIcons";
import type { MarkdownFileIcon } from "./markdownLinks";
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
const EXTERNAL_LINK_PREFIX = "◉ ";
const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
const FILE_LINK_PREFIX = "\u00A0\uFFFC\u00A0";
const CHIP_SUFFIX = "\u00A0";
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
function useFileIconUris(runs: ReadonlyArray<NativeMarkdownTextRun>) {
const iconSignature = JSON.stringify(
[...new Set(runs.flatMap((run) => (run.fileIcon ? [run.fileIcon] : [])))].sort(),
);
const icons = useMemo(
() => JSON.parse(iconSignature) as ReadonlyArray<MarkdownFileIcon>,
[iconSignature],
);
const [uris, setUris] = useState<ReadonlyMap<string, string>>(() => new Map());
useEffect(() => {
let cancelled = false;
void Promise.all(
icons.map(async (icon) => {
const source = markdownFileIconSource(icon);
const fallbackUri = Image.resolveAssetSource(source).uri;
if (typeof source !== "number" && typeof source !== "string") {
return [icon, fallbackUri] as const;
}
try {
const asset = Asset.fromModule(source);
await asset.downloadAsync();
return [icon, asset.localUri ?? fallbackUri] as const;
} catch {
return [icon, fallbackUri] as const;
}
}),
).then((entries) => {
if (!cancelled) {
setUris(new Map(entries));
}
});
return () => {
cancelled = true;
};
}, [icons]);
return uris;
}
function runKeySignature(run: NativeMarkdownTextRun): string {
return [
run.text,
@@ -35,16 +81,13 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
const isFile = run.fileIcon != null;
const isSkill = run.skillName != null;
const isChip = isFile || isSkill;
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
const isHeading = run.role === "heading";
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
const hasParagraphStyle = run.headIndent !== undefined;
const textDecorationLine = run.strikethrough
? "line-through"
: run.href && !isFile
? "underline"
: "none";
const textDecorationLine = run.strikethrough ? "line-through" : run.href ? "underline" : "none";
return {
color: isFile
@@ -63,23 +106,20 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? textStyle.mutedColor
: run.role === "list-marker"
? textStyle.mutedColor
: isCodeBlock
: run.code || isFile
? textStyle.codeColor
: run.code
? textStyle.inlineCodeColor
: run.bold
? textStyle.strongColor
: textStyle.color,
fontFamily:
isFile || isSkill
? textStyle.boldFontFamily
: run.code || isCodeBlock
? "ui-monospace"
: isHeading
? textStyle.headingFontFamily
: run.bold
? textStyle.boldFontFamily
: textStyle.fontFamily,
: run.bold
? textStyle.strongColor
: textStyle.color,
fontFamily: isChip
? "DMSans_500Medium"
: run.code || isCodeBlock
? "ui-monospace"
: isHeading
? textStyle.headingFontFamily
: run.bold
? textStyle.boldFontFamily
: textStyle.fontFamily,
fontSize:
run.role === "spacer"
? (run.spacing ?? 10)
@@ -89,7 +129,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? headingFontSize
: run.role === "code-language"
? 11
: run.code || isCodeBlock
: run.code || isChip || isCodeBlock
? Math.max(12, textStyle.fontSize - 2)
: textStyle.fontSize,
lineHeight:
@@ -103,9 +143,17 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? 18
: textStyle.lineHeight,
fontStyle: run.italic ? "italic" : "normal",
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
fontWeight: isHeading || run.bold ? "700" : isChip ? "500" : "400",
textDecorationLine,
backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
backgroundColor: isCodeBlock
? textStyle.codeBlockBackgroundColor
: isSkill
? textStyle.skillBackgroundColor
: run.code
? textStyle.codeBackgroundColor
: isFile
? textStyle.fileBackgroundColor
: undefined,
...(hasParagraphStyle
? {
shadowColor: "transparent",
@@ -122,9 +170,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
export function NativeMarkdownSelectableText(props: {
readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const colorScheme = useColorScheme();
const fileIconUris = useFileIconUris(props.runs);
const occurrences = new Map<string, number>();
const prefixedExternalLinks = new Set<string>();
const keyedRuns = props.runs.map((run) => {
@@ -134,9 +182,9 @@ export function NativeMarkdownSelectableText(props: {
let text = run.text;
if (run.fileIcon) {
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
text = `${FILE_LINK_PREFIX}${text}${CHIP_SUFFIX}`;
} else if (run.skillName && run.skillLabel) {
text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
text = `\u00A0${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}${CHIP_SUFFIX}`;
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
prefixedExternalLinks.add(run.href);
text = `${EXTERNAL_LINK_PREFIX}${text}`;
@@ -152,11 +200,12 @@ export function NativeMarkdownSelectableText(props: {
props.textStyle.strongColor,
props.textStyle.mutedColor,
props.textStyle.linkColor,
props.textStyle.inlineCodeColor,
props.textStyle.codeColor,
props.textStyle.codeBackgroundColor,
props.textStyle.codeBlockBackgroundColor,
props.textStyle.fileBackgroundColor,
props.textStyle.fileTextColor,
props.textStyle.skillBackgroundColor,
props.textStyle.skillTextColor,
props.textStyle.quoteMarkerColor,
props.textStyle.dividerColor,
@@ -168,8 +217,7 @@ export function NativeMarkdownSelectableText(props: {
uiTextView
selectable
style={{
flexShrink: 1,
minWidth: 0,
width: "100%",
color: props.textStyle.color,
fontFamily: props.textStyle.fontFamily,
fontSize: props.textStyle.fontSize,
@@ -183,20 +231,19 @@ export function NativeMarkdownSelectableText(props: {
key={key}
nativeID={
run.fileIcon
? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
? `t3-chip-file:${
fileIconUris.get(run.fileIcon) ??
Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
}`
: run.skillName
? "t3-skill:sf:cube"
? "t3-chip-skill:sf:cube"
: undefined
}
style={runStyle(run, props.textStyle)}
onPress={
href
? () => {
if (props.onLinkPress) {
props.onLinkPress(href);
} else {
void Linking.openURL(href);
}
void Linking.openURL(href);
}
: undefined
}
@@ -6,7 +6,6 @@ import {
nativeMarkdownChunkSpacing,
nativeMarkdownDocumentChunks,
nativeMarkdownDocumentRuns,
nativeMarkdownWithPreservedSoftBreaks,
} from "./nativeMarkdownText";
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
@@ -34,20 +33,15 @@ export function SelectableMarkdownText({
skills = EMPTY_SKILLS,
textStyle,
highlightCode,
preserveSoftBreaks = false,
onLinkPress,
marginTop = 0,
marginBottom = 0,
}: SelectableMarkdownTextProps) {
const chunks = useMemo(() => {
const parsedDocument = parseMarkdownWithOptions(markdown, {
const document = parseMarkdownWithOptions(markdown, {
gfm: true,
html: true,
math: false,
});
const document = preserveSoftBreaks
? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
: parsedDocument;
return nativeMarkdownDocumentChunks(document).map((chunk) =>
chunk.kind === "selectable"
? {
@@ -56,14 +50,10 @@ export function SelectableMarkdownText({
}
: chunk,
);
}, [markdown, preserveSoftBreaks, skills]);
}, [markdown, skills]);
return (
// A percentage width here creates a cyclic intrinsic measurement inside
// shrink-to-fit containers such as user-message bubbles. Yoga then gives
// the native text node an unbounded second pass and the parent only clips
// the resulting single-line width instead of reflowing it.
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
<View style={{ width: "100%", marginTop, marginBottom }}>
{chunks.map((chunk, index) => {
const content =
chunk.kind === "rich" ? (
@@ -71,14 +61,9 @@ export function SelectableMarkdownText({
node={chunk.node}
textStyle={textStyle}
highlightCode={highlightCode}
onLinkPress={onLinkPress}
/>
) : (
<NativeMarkdownSelectableText
runs={chunk.runs}
textStyle={textStyle}
onLinkPress={onLinkPress}
/>
<NativeMarkdownSelectableText runs={chunk.runs} textStyle={textStyle} />
);
return (
@@ -3,11 +3,12 @@ export interface NativeMarkdownTextStyle {
readonly strongColor: string;
readonly mutedColor: string;
readonly linkColor: string;
readonly inlineCodeColor: string;
readonly codeColor: string;
readonly codeBackgroundColor: string;
readonly codeBlockBackgroundColor: string;
readonly fileBackgroundColor: string;
readonly fileTextColor: string;
readonly skillBackgroundColor: string;
readonly skillTextColor: string;
readonly quoteMarkerColor: string;
readonly dividerColor: string;
@@ -40,8 +41,6 @@ export interface SelectableMarkdownTextProps {
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
readonly preserveSoftBreaks?: boolean;
readonly onLinkPress?: (href: string) => void;
readonly marginTop?: number;
readonly marginBottom?: number;
}
Loaded 100 of 732 files, more files were not shown because too many files have changed in this diff. Show more