Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4945aad27 | ||
|
|
cebbe6ff19 | ||
|
|
e4a84a348e | ||
|
|
61e6d89d69 | ||
|
|
1b2f39d018 | ||
|
|
8c2d33abde | ||
|
|
60dc4af916 | ||
|
|
d389cfd4e3 | ||
|
|
6fc79737c3 | ||
|
|
cdd03591ef | ||
|
|
2fbb0565d7 | ||
|
|
a3dadc04bf | ||
|
|
1a59277dc8 | ||
|
|
6424197a19 | ||
|
|
8d4a8b4f31 | ||
|
|
23ab75e84a | ||
|
|
0488e47d9c | ||
|
|
0eba548282 | ||
|
|
68c0dd3b70 | ||
|
|
4cd958445f | ||
|
|
9f7861aadd | ||
|
|
9243ead1c3 | ||
|
|
803c2b7738 | ||
|
|
28e7c9ae17 | ||
|
|
a9460bb772 | ||
|
|
5edf7c56ba | ||
|
|
90dc76b11e | ||
|
|
57d25c934b | ||
|
|
a26f0dc89f | ||
|
|
6ff6c13fc8 | ||
|
|
60c9ca0e33 | ||
|
|
ad2cb1dd57 | ||
|
|
674590e009 | ||
|
|
f2cb14e774 | ||
|
|
e042c25f56 | ||
|
|
90f1936fad | ||
|
|
42ff43915a | ||
|
|
834e5db458 | ||
|
|
8ce627ba91 | ||
|
|
9a78c6f2ba | ||
|
|
aab72f10c1 | ||
|
|
a76b7bbfb5 | ||
|
|
a51691a9b0 | ||
|
|
97de7d7e15 | ||
|
|
d7718e81e0 | ||
|
|
b88873508e | ||
|
|
58053d146b | ||
|
|
50767683b3 | ||
|
|
d1339f3846 | ||
|
|
faccdd4ca9 | ||
|
|
dd48bfd98c | ||
|
|
6d8d995621 | ||
|
|
b6c590af38 | ||
|
|
b51aef10c4 | ||
|
|
fc2cdeceb9 | ||
|
|
c637dfc454 | ||
|
|
6e9b43cb84 | ||
|
|
be56fa43b0 | ||
|
|
eb5eb0d9fa | ||
|
|
621616268a | ||
|
|
630df6b986 | ||
|
|
569b3e5959 | ||
|
|
d7ff7e7333 | ||
|
|
bd8e3ee008 | ||
|
|
c1d8a22f07 | ||
|
|
7b791895ad | ||
|
|
4c16c66368 | ||
|
|
4407a5a6b7 | ||
|
|
c7b375e9b0 | ||
|
|
abc253d97d | ||
|
|
ce11e6facd | ||
|
|
f1052dd8b1 | ||
|
|
e85144a58c | ||
|
|
defd9dfe20 | ||
|
|
8c03188c1c | ||
|
|
3e5f9f2cdd | ||
|
|
6888276f19 | ||
|
|
e06c33c38d | ||
|
|
5f860439e9 | ||
|
|
c9159b67b3 | ||
|
|
a1b727f62d | ||
|
|
fdc1e8b3a2 | ||
|
|
c8454ad88a | ||
|
|
336d176027 | ||
|
|
204984bf8c | ||
|
|
be4a38e578 | ||
|
|
f50a7cddc1 | ||
|
|
97487d9959 | ||
|
|
d2e38c5373 | ||
|
|
90bd5ee0c1 | ||
|
|
430ece4c0a | ||
|
|
4238a0e769 | ||
|
|
ff0f702c7c | ||
|
|
1cbe8a7a90 | ||
|
|
46fdc769d9 | ||
|
|
0cd0ed1a3d | ||
|
|
d53237cbd1 | ||
|
|
0e718855b8 | ||
|
|
731b1a67ac | ||
|
|
cdfecb36a6 | ||
|
|
f4ef356215 | ||
|
|
d60f5c6101 | ||
|
|
eacceb9e7b | ||
|
|
13a4789a5d | ||
|
|
b6e384fb27 | ||
|
|
d8bf307d22 | ||
|
|
d512deac84 | ||
|
|
32c7f90d9e | ||
|
|
2c16edd0cb | ||
|
|
708bc7091d | ||
|
|
7eb7b4f4a3 | ||
|
|
e01b1903de | ||
|
|
1dc36cef73 | ||
|
|
833c8ab7c6 | ||
|
|
5b1b35c773 | ||
|
|
ee3e2dae78 | ||
|
|
9c98cd60e8 | ||
|
|
48f88d5220 | ||
|
|
2910d9ff01 | ||
|
|
2b8e012924 | ||
|
|
49c23221d8 | ||
|
|
5ca7676661 | ||
|
|
c3e3e26844 | ||
|
|
1486a4a2b9 | ||
|
|
1e5f62801b | ||
|
|
ed6ba7439d | ||
|
|
f98448e872 | ||
|
|
bfe61741b8 | ||
|
|
4d3fcacd84 | ||
|
|
4d790f0064 | ||
|
|
3ecf3685ba | ||
|
|
716ae73c40 | ||
|
|
300d4d566a | ||
|
|
53a477c2e9 | ||
|
|
d84ebe8319 | ||
|
|
5a2c92e86d | ||
|
|
61aade9ea4 | ||
|
|
04f82ae1f3 | ||
|
|
ce0c20b840 | ||
|
|
fccecd8749 | ||
|
|
30a084c463 | ||
|
|
9d5ca2cb7c | ||
|
|
ac77fe452b | ||
|
|
4fbc4f9b20 | ||
|
|
779c237487 | ||
|
|
350e229f7a | ||
|
|
8112aff7c2 | ||
|
|
b9e22de6a3 | ||
|
|
f3b43a148b | ||
|
|
8331511b97 | ||
|
|
08650a7424 | ||
|
|
40d14647db | ||
|
|
cc69aef4dd | ||
|
|
71608142c2 | ||
|
|
bf1a6501c7 | ||
|
|
f7867addbe | ||
|
|
7a8bab5d9d | ||
|
|
06752526b3 | ||
|
|
d87ec967bf | ||
|
|
e55dd0067d | ||
|
|
8c3755aecc | ||
|
|
b4fe8faa1d | ||
|
|
515303edf2 | ||
|
|
20734d4a78 | ||
|
|
86db35ca61 | ||
|
|
97e5cd3bf7 | ||
|
|
b19fc1b87b | ||
|
|
2fa37ec183 | ||
|
|
db27502aff | ||
|
|
6c5fb7930d | ||
|
|
30acfa9c51 | ||
|
|
f58b6da230 | ||
|
|
9a1c4875a3 | ||
|
|
7eda6ba5fc | ||
|
|
c00e721c04 | ||
|
|
b0a3a50448 | ||
|
|
79c57170c7 | ||
|
|
3900c45f25 | ||
|
|
8d61172f8b | ||
|
|
dc82f792c3 | ||
|
|
335e0b59ea | ||
|
|
2fbbe68c24 | ||
|
|
65385c0281 | ||
|
|
6d2dae0627 | ||
|
|
10a8d3fbd9 | ||
|
|
0ad1e9d9e4 | ||
|
|
2f8d3baa88 | ||
|
|
6b74476322 | ||
|
|
d9e9539862 | ||
|
|
7118e43d16 | ||
|
|
4e8ee13d8f | ||
|
|
b17b6d50c5 | ||
|
|
ccf8331600 | ||
|
|
ffae12f329 | ||
|
|
01cd564557 | ||
|
|
4ee719a094 | ||
|
|
01492ebd3b | ||
|
|
93fd972108 | ||
|
|
df1540f3ac | ||
|
|
d5a72d5be1 | ||
|
|
742dd7af0d | ||
|
|
5c1ac92257 | ||
|
|
8bfdacf206 | ||
|
|
b6302784f8 | ||
|
|
9544e72d08 | ||
|
|
938b19a6bb | ||
|
|
3b56dc17a5 | ||
|
|
d2c0a6a48f | ||
|
|
1cf3647da6 | ||
|
|
53d0107759 | ||
|
|
60b16d1f28 | ||
|
|
ab0baaa886 | ||
|
|
753bc4672d | ||
|
|
e29ad7604b | ||
|
|
cdaba7fa8b | ||
|
|
fbf6263876 | ||
|
|
c08b968f4e | ||
|
|
d9f59be704 | ||
|
|
a4446e263d | ||
|
|
494350cc0b | ||
|
|
7dc182337c | ||
|
|
13917df1fe | ||
|
|
5d4e2fae01 | ||
|
|
3e01c4bc57 | ||
|
|
20f37f367a | ||
|
|
804d44cfb1 | ||
|
|
0651af92b8 | ||
|
|
52a24c8902 | ||
|
|
30034ecedc | ||
|
|
1fcc57af13 | ||
|
|
e95b57dc26 | ||
|
|
3bdaa6e100 | ||
|
|
b7b00bfb9d | ||
|
|
ae2b523503 | ||
|
|
75b3b3c48a | ||
|
|
b489ea52a8 | ||
|
|
3a5ec9464b | ||
|
|
e56bb200fa | ||
|
|
c2ca9de33a | ||
|
|
60b546cf01 | ||
|
|
4b73827334 | ||
|
|
a5efb7cb6b | ||
|
|
8f9911f79d | ||
|
|
689a882045 | ||
|
|
85fe62d402 | ||
|
|
708d5383a9 | ||
|
|
5cd2744100 | ||
|
|
d12da198ad | ||
|
|
d0a7d18cdb | ||
|
|
71ea5fa1ab | ||
|
|
9d5e632d4d | ||
|
|
c2d44a312c | ||
|
|
de8bdc10fa | ||
|
|
477795697d | ||
|
|
a23b83314e | ||
|
|
ce90563709 | ||
|
|
31e68229d6 | ||
|
|
1db585878e | ||
|
|
56e57de947 | ||
|
|
3a0623f1cd | ||
|
|
cd91ec75f3 | ||
|
|
d4ba9e9618 | ||
|
|
c1792bc9a6 | ||
|
|
1b4317ec35 | ||
|
|
f452d63fef | ||
|
|
18a49abcec | ||
|
|
85d5df6256 | ||
|
|
b5b769dddf | ||
|
|
3c7862edd7 | ||
|
|
d8fe3d72c8 | ||
|
|
70ec39ae80 | ||
|
|
3d9e8dea7d | ||
|
|
f7c422d581 | ||
|
|
dd739c880d | ||
|
|
6c6740e381 | ||
|
|
29150b5736 | ||
|
|
07c6d70b91 | ||
|
|
50bc18b208 | ||
|
|
63d42a5e58 | ||
|
|
9b43123ba2 | ||
|
|
17fb0e4a9a | ||
|
|
43e8bbd7ae | ||
|
|
52c77c1ec4 | ||
|
|
d6eb386e3d | ||
|
|
d25090cf6d | ||
|
|
ae39bacf0e | ||
|
|
1ea17026ee | ||
|
|
649f4328ea | ||
|
|
7db034905b | ||
|
|
57f6bf7edb | ||
|
|
0baf1986e8 | ||
|
|
ae7e88b0e0 | ||
|
|
1916ac6d55 | ||
|
|
343061a053 | ||
|
|
0b40ea62e1 | ||
|
|
a4757c2656 | ||
|
|
3efabdcd3a | ||
|
|
c5f7cd40ba | ||
|
|
e2db800f7c | ||
|
|
31533466b0 | ||
|
|
7f741a56d1 | ||
|
|
cc9e81ac93 | ||
|
|
238715fd6f | ||
|
|
b03bc4b52d | ||
|
|
aca14507f7 | ||
|
|
04f7f32ace | ||
|
|
a3422a9bb5 | ||
|
|
22f9f3058b | ||
|
|
983a8c7fa6 | ||
|
|
de58ec8e24 | ||
|
|
8e6f4229da | ||
|
|
38ea6d483e | ||
|
|
0e4a43519f | ||
|
|
3ea6adf17d | ||
|
|
a56496c7f2 | ||
|
|
b76f161d55 | ||
|
|
75257d64e9 | ||
|
|
e1ce9f8500 | ||
|
|
602148f8fe | ||
|
|
92be60e7c1 | ||
|
|
0d6e9e9add | ||
|
|
8ab58a0b26 | ||
|
|
6f42bd9c88 | ||
|
|
5b26bd408b | ||
|
|
c04d15d3be | ||
|
|
9da430c828 | ||
|
|
a084fbbc0a | ||
|
|
b870a6e349 | ||
|
|
e1cb19b55b | ||
|
|
94fc117561 | ||
|
|
113b9d84c7 | ||
|
|
f60def2054 | ||
|
|
eda163ca17 | ||
|
|
3579005114 | ||
|
|
af3dfd229e | ||
|
|
969e6d274c | ||
|
|
769bdd251d | ||
|
|
295b9db113 | ||
|
|
b5a62504d4 | ||
|
|
ec18938bf9 | ||
|
|
5ae77c0d63 | ||
|
|
300f7fd11d | ||
|
|
53042f47f8 | ||
|
|
6ce6f678b5 | ||
|
|
a74dfd4f3c | ||
|
|
49c1b64687 | ||
|
|
dfdb5a46db | ||
|
|
b0fa60a121 | ||
|
|
348a9140e9 | ||
|
|
9fc485afaf |
No files matched your search
@@ -1,6 +0,0 @@
|
||||
# CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
@@ -0,0 +1,24 @@
|
||||
# Optional: T3 Connect source builds
|
||||
# Leave these unset to disable optional T3 Connect features in local source builds.
|
||||
# Release builds inject their public values at build time. Do not add server-side
|
||||
# secrets to this file.
|
||||
|
||||
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
|
||||
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
|
||||
# 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
|
||||
|
||||
# Public, ingest-only mobile OpenTelemetry configuration.
|
||||
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
|
||||
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
|
||||
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
|
||||
@@ -38,6 +38,7 @@ 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
|
||||
@@ -60,52 +61,6 @@ jobs:
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
test_browser:
|
||||
name: Test Browser
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: vp run --filter @t3tools/web test:browser:install
|
||||
|
||||
- name: Browser test / Chat view
|
||||
working-directory: apps/web
|
||||
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
|
||||
|
||||
- name: Browser test / Chat markdown
|
||||
working-directory: apps/web
|
||||
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
|
||||
|
||||
- name: Browser test / Components
|
||||
working-directory: apps/web
|
||||
run: |
|
||||
vp test run --mode browser --browser=chromium \
|
||||
src/components/GitActionsControl.browser.tsx \
|
||||
src/components/KeybindingsToast.browser.tsx \
|
||||
src/components/ThreadTerminalDrawer.browser.tsx \
|
||||
src/components/chat/MessagesTimeline.browser.tsx \
|
||||
src/components/chat/ProviderModelPicker.browser.tsx \
|
||||
src/components/chat/CompactComposerControlsMenu.browser.tsx \
|
||||
src/components/settings/SettingsPanels.browser.tsx
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
name: Deploy T3 Connect relay
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: none
|
||||
statuses: write
|
||||
|
||||
concurrency:
|
||||
group: relay-production
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy_relay:
|
||||
name: Deploy production relay
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
environment:
|
||||
name: production
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
|
||||
AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
|
||||
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
|
||||
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
|
||||
RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
|
||||
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
|
||||
CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
|
||||
APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}
|
||||
APNS_TEAM_ID: ${{ vars.APNS_TEAM_ID }}
|
||||
APNS_KEY_ID: ${{ vars.APNS_KEY_ID }}
|
||||
APNS_BUNDLE_ID: ${{ vars.APNS_BUNDLE_ID }}
|
||||
ALCHEMY_TELEMETRY_DISABLED: "1"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Deploy production relay stage
|
||||
id: deploy
|
||||
run: vp run --filter t3code-relay deploy --stage prod --yes --github-output
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
|
||||
PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
|
||||
AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
|
||||
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
|
||||
APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
|
||||
|
||||
- name: Publish relay deploy commit status
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const result = "${{ steps.deploy.outputs.result }}";
|
||||
const changed = "${{ steps.deploy.outputs.changed }}" === "true";
|
||||
const description = changed
|
||||
? "Relay production deploy applied infrastructure changes."
|
||||
: result === "noop"
|
||||
? "Relay production deploy was a no-op."
|
||||
: `Relay production deploy completed with result: ${result}.`;
|
||||
|
||||
await github.rest.repos.createCommitStatus({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
sha: context.sha,
|
||||
state: "success",
|
||||
context: "Relay deploy / production",
|
||||
description,
|
||||
target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,
|
||||
});
|
||||
@@ -2,10 +2,12 @@ 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
|
||||
|
||||
@@ -166,12 +166,103 @@ jobs:
|
||||
--current-tag "${{ steps.release_meta.outputs.tag }}" \
|
||||
--github-output
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
relay_public_config:
|
||||
name: Resolve T3 Connect public config
|
||||
needs: preflight
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 5
|
||||
environment:
|
||||
name: production
|
||||
outputs:
|
||||
clerk_publishable_key: ${{ steps.public_config.outputs.clerk_publishable_key }}
|
||||
clerk_jwt_template: ${{ steps.public_config.outputs.clerk_jwt_template }}
|
||||
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
relay_url: ${{ steps.public_config.outputs.relay_url }}
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
|
||||
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
|
||||
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
|
||||
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
|
||||
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3code-relay...
|
||||
|
||||
- id: relay_state
|
||||
name: Read production relay tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
vp run --filter t3code-relay deploy \
|
||||
--stage prod \
|
||||
--read-state \
|
||||
--github-output \
|
||||
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
|
||||
|
||||
- name: Upload relay client tracing config
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing.env
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- id: public_config
|
||||
name: Resolve production relay public config
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
relay_domain="${RELAY_DOMAIN:-}"
|
||||
if [[ -z "$relay_domain" && -n "${RELAY_API_ZONE_NAME:-}" ]]; then
|
||||
relay_domain="relay.$RELAY_API_ZONE_NAME"
|
||||
fi
|
||||
required=(
|
||||
relay_domain
|
||||
CLERK_PUBLISHABLE_KEY
|
||||
CLERK_JWT_TEMPLATE
|
||||
CLERK_CLI_OAUTH_CLIENT_ID
|
||||
)
|
||||
missing=()
|
||||
for name in "${required[@]}"; do
|
||||
if [[ -z "${!name:-}" ]]; then
|
||||
missing+=("$name")
|
||||
fi
|
||||
done
|
||||
if (( ${#missing[@]} > 0 )); then
|
||||
printf 'Missing required relay deployment configuration: %s\n' "${missing[*]}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "clerk_publishable_key=$CLERK_PUBLISHABLE_KEY" >> "$GITHUB_OUTPUT"
|
||||
echo "clerk_jwt_template=$CLERK_JWT_TEMPLATE" >> "$GITHUB_OUTPUT"
|
||||
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: [preflight, relay_public_config]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -215,6 +306,20 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -320,6 +425,9 @@ 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 }}
|
||||
@@ -347,9 +455,21 @@ 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
|
||||
@@ -422,13 +542,18 @@ jobs:
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
|
||||
needs: [preflight, relay_public_config, build]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -446,6 +571,20 @@ jobs:
|
||||
- --filter=@t3tools/web...
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -577,11 +716,14 @@ jobs:
|
||||
|
||||
deploy_web:
|
||||
name: Deploy hosted web app
|
||||
needs: [preflight, release]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
|
||||
needs: [preflight, relay_public_config, release]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.release.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
|
||||
@@ -605,6 +747,20 @@ jobs:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/web...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -648,6 +804,12 @@ jobs:
|
||||
--token "$VERCEL_TOKEN" \
|
||||
"${vercel_scope_args[@]}" \
|
||||
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
|
||||
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
|
||||
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
|
||||
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
|
||||
--build-env "VITE_HOSTED_APP_URL=$router_url" \
|
||||
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
|
||||
)"
|
||||
@@ -705,6 +867,7 @@ jobs:
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/oxlint-plugin-t3code...
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
@@ -743,10 +906,11 @@ jobs:
|
||||
if: |
|
||||
always() && !cancelled() &&
|
||||
needs.preflight.result == 'success' &&
|
||||
needs.relay_public_config.result == 'success' &&
|
||||
needs.release.result == 'success' &&
|
||||
needs.deploy_web.result == 'success' &&
|
||||
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
|
||||
needs: [preflight, release, deploy_web, finalize]
|
||||
needs: [preflight, relay_public_config, release, deploy_web, finalize]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
|
||||
@@ -5,6 +5,7 @@ node_modules
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
apps/*/dist
|
||||
infra/*/dist
|
||||
.astro
|
||||
packages/*/dist
|
||||
.env
|
||||
@@ -26,3 +27,8 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
.env*
|
||||
!.env.example
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/**/*.ts"
|
||||
- "apps/**/*.tsx"
|
||||
- "packages/**/*.ts"
|
||||
- "packages/**/*.tsx"
|
||||
- "infra/**/*.ts"
|
||||
- "infra/**/*.tsx"
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# Effect service review
|
||||
|
||||
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
|
||||
|
||||
## Imports and module namespaces
|
||||
|
||||
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
|
||||
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
|
||||
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
|
||||
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
|
||||
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
|
||||
|
||||
## Service definition
|
||||
|
||||
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
|
||||
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
|
||||
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
|
||||
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
|
||||
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
|
||||
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
|
||||
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
|
||||
## Errors and predicates
|
||||
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
|
||||
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
|
||||
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
|
||||
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Preserve useful comments, invariants, and specification documentation while moving code.
|
||||
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
|
||||
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
|
||||
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
@@ -1,2 +0,0 @@
|
||||
[tools]
|
||||
node = "24.13.1"
|
||||
@@ -1 +0,0 @@
|
||||
vp staged
|
||||
Vendored
+1
@@ -6,6 +6,7 @@
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn",
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib",
|
||||
"typescript.native-preview.tsdk": "node_modules/@typescript/native-preview",
|
||||
"typescript.preferences.autoImportFileExcludePatterns": [".repos/**"],
|
||||
"javascript.preferences.autoImportFileExcludePatterns": [".repos/**"],
|
||||
"files.watcherExclude": {
|
||||
|
||||
@@ -29,22 +29,8 @@ Long term maintainability is a core priority. If you add new functionality, firs
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
|
||||
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||
|
||||
## Codex App Server (Important)
|
||||
|
||||
T3 Code is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages.
|
||||
|
||||
How we use it in this codebase:
|
||||
|
||||
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
|
||||
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
|
||||
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
|
||||
- Web app consumes orchestration domain events via WebSocket push on channel `orchestration.domainEvent` (provider runtime activity is projected into orchestration events server-side).
|
||||
|
||||
Docs:
|
||||
|
||||
- Codex App Server docs: https://developers.openai.com/codex/sdk/#app-server
|
||||
- `packages/shared`: Shared runtime utilities consumed by both server and client applications. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||
- `packages/client-runtime`: Shared runtime package for sharing client code across web and mobile.
|
||||
|
||||
## Reference Repos
|
||||
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
|
||||
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> T3 Code currently supports Codex, Claude, and OpenCode.
|
||||
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
|
||||
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
|
||||
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
|
||||
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
```bash
|
||||
npx t3
|
||||
npx t3@latest
|
||||
```
|
||||
|
||||
Tip: Use `npx t3@latest --help` for the full CLI reference.
|
||||
|
||||
### Desktop app
|
||||
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
@@ -46,16 +49,40 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Getting started](./docs/getting-started/quick-start.md)
|
||||
- [Architecture overview](./docs/architecture/overview.md)
|
||||
- [Provider guides](./docs/providers/codex.md)
|
||||
- [Operations](./docs/operations/ci.md)
|
||||
- [Reference](./docs/reference/encyclopedia.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Before local development, prepare the environment and install dependencies:
|
||||
### Install `vp`
|
||||
|
||||
T3 Code uses Vite+ so you'll need to install the global `vp` command-line tool.
|
||||
|
||||
#### macOS / Linux
|
||||
|
||||
```bash
|
||||
# Optional: only needed if you use mise for dev tool management.
|
||||
mise install
|
||||
vp install
|
||||
curl -fsSL https://vite.plus | bash
|
||||
```
|
||||
|
||||
#### Windows
|
||||
|
||||
```bash
|
||||
irm https://vite.plus/ps1 | iex
|
||||
```
|
||||
|
||||
Checkout their getting started guide for more information: https://viteplus.dev/guide/
|
||||
|
||||
### Install dependencies
|
||||
|
||||
```bash
|
||||
vp i
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.24",
|
||||
"version": "0.0.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
@@ -12,6 +12,8 @@
|
||||
"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:*",
|
||||
@@ -20,15 +22,18 @@
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"electron": "41.5.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
"electron-store": "^8.2.0",
|
||||
"electron-updater": "^6.6.2",
|
||||
"playwright-core": "1.60.0",
|
||||
"react-grab": "^0.1.32"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"electron-builder": "26.8.1",
|
||||
"vite-plus": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
"tailwindcss": "^4.0.0",
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
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 { 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 [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"),
|
||||
]);
|
||||
|
||||
const candidates = new Set(
|
||||
Array.from(preloadSource.matchAll(/!?-?[A-Za-z0-9_:@/.[\]()%,-]+/g), (match) => match[0]),
|
||||
);
|
||||
const compilerInput = [
|
||||
themeSource,
|
||||
preflightSource,
|
||||
annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"),
|
||||
].join("\n");
|
||||
const compiler = await compile(compilerInput, { base: appRoot });
|
||||
const css = compiler.build([...candidates]);
|
||||
const encodedCss = `'${css
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("'", "\\'")
|
||||
.replaceAll("\r", "\\r")
|
||||
.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);
|
||||
@@ -1,8 +1,13 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import {
|
||||
desktopDir,
|
||||
resolveDevProtocolClient,
|
||||
resolveElectronLaunchCommand,
|
||||
} from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
@@ -28,6 +33,9 @@ const watchedDirectories = [
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
@@ -38,6 +46,11 @@ await waitForResources({
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
const devProtocolClient = resolveDevProtocolClient();
|
||||
if (devProtocolClient) {
|
||||
childEnv.T3CODE_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId;
|
||||
childEnv.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1";
|
||||
}
|
||||
|
||||
let shuttingDown = false;
|
||||
let restartTimer = null;
|
||||
@@ -47,19 +60,21 @@ const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
if (hostPlatform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
@@ -67,15 +82,18 @@ function startApp() {
|
||||
return;
|
||||
}
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
const electronArgs = remoteDebuggingPort
|
||||
? [`--remote-debugging-port=${remoteDebuggingPort}`]
|
||||
: [];
|
||||
const launchArgs = devProtocolClient
|
||||
? electronArgs
|
||||
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
|
||||
const electronCommand = resolveElectronLaunchCommand(launchArgs);
|
||||
const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
currentApp = app;
|
||||
|
||||
@@ -125,6 +143,7 @@ async function stopApp() {
|
||||
app.once("exit", finish);
|
||||
app.kill("SIGTERM");
|
||||
killChildTreeByPid(app.pid, "TERM");
|
||||
cleanupStaleDevApps();
|
||||
|
||||
setTimeout(() => {
|
||||
if (settled) {
|
||||
@@ -133,6 +152,7 @@ async function stopApp() {
|
||||
|
||||
app.kill("SIGKILL");
|
||||
killChildTreeByPid(app.pid, "KILL");
|
||||
cleanupStaleDevApps();
|
||||
finish();
|
||||
}, forcedShutdownTimeoutMs).unref();
|
||||
});
|
||||
@@ -162,8 +182,8 @@ function scheduleRestart() {
|
||||
|
||||
function startWatchers() {
|
||||
for (const { directory, files } of watchedDirectories) {
|
||||
const watcher = watch(
|
||||
join(desktopDir, directory),
|
||||
const watcher = NodeFS.watch(
|
||||
NodePath.join(desktopDir, directory),
|
||||
{ persistent: true },
|
||||
(_eventType, filename) => {
|
||||
if (typeof filename !== "string" || !files.has(filename)) {
|
||||
@@ -179,12 +199,14 @@ function startWatchers() {
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
}
|
||||
|
||||
async function shutdown(exitCode) {
|
||||
|
||||
@@ -1,44 +1,83 @@
|
||||
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
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 NodeURL from "node:url";
|
||||
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 2;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
const repoRoot = resolve(desktopDir, "..", "..");
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
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)
|
||||
.toLowerCase()
|
||||
.replaceAll(/[^a-z0-9]+/g, "");
|
||||
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
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",
|
||||
);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
const replaceResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-replace", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
const insertResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-insert", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
|
||||
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function setPlistJson(plistPath, key, value) {
|
||||
const serialized = JSON.stringify(value);
|
||||
const replaceResult = NodeChildProcess.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",
|
||||
},
|
||||
);
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -48,7 +87,7 @@ function setPlistString(plistPath, key, value) {
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = spawnSync(command, args, { encoding: "utf8" });
|
||||
const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -57,22 +96,78 @@ function runChecked(command, args) {
|
||||
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
if (!existsSync(developmentMacIconPngPath)) {
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
["T3CODE_HOME", process.env.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
NodeFS.writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
|
||||
function registerMacLauncherBundle(appBundlePath) {
|
||||
runChecked(
|
||||
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
|
||||
["-f", appBundlePath],
|
||||
);
|
||||
|
||||
if (!isDevelopment) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const scheme of APP_PROTOCOL_SCHEMES) {
|
||||
runChecked("osascript", [
|
||||
"-l",
|
||||
"JavaScript",
|
||||
"-e",
|
||||
[
|
||||
'ObjC.import("CoreServices");',
|
||||
`const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`,
|
||||
`const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`,
|
||||
"const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);",
|
||||
"if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);",
|
||||
].join(" "),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
|
||||
NodeFS.mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
|
||||
return defaultIconPath;
|
||||
}
|
||||
|
||||
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
|
||||
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (
|
||||
NodeFS.existsSync(generatedIconPath) &&
|
||||
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
|
||||
) {
|
||||
return generatedIconPath;
|
||||
}
|
||||
|
||||
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = join(iconsetRoot, "icon.iconset");
|
||||
mkdirSync(iconsetDir, { recursive: true });
|
||||
const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
|
||||
NodeFS.mkdirSync(iconsetDir, { recursive: true });
|
||||
|
||||
try {
|
||||
for (const size of [16, 32, 128, 256, 512]) {
|
||||
@@ -82,7 +177,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
String(size),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
]);
|
||||
|
||||
const retinaSize = size * 2;
|
||||
@@ -92,7 +187,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
String(retinaSize),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -105,79 +200,172 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
);
|
||||
return defaultIconPath;
|
||||
} finally {
|
||||
rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
|
||||
{
|
||||
CFBundleURLName: APP_BUNDLE_ID,
|
||||
CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
|
||||
},
|
||||
]);
|
||||
|
||||
const resourcesDir = join(appBundlePath, "Contents", "Resources");
|
||||
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
|
||||
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
|
||||
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const helperBundleNames = [
|
||||
["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
|
||||
["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
|
||||
["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
|
||||
["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
|
||||
];
|
||||
|
||||
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
|
||||
const infoPlistPath = NodePath.join(
|
||||
appBundlePath,
|
||||
"Contents",
|
||||
"Frameworks",
|
||||
bundleName,
|
||||
"Contents",
|
||||
"Info.plist",
|
||||
);
|
||||
if (!NodeFS.existsSync(infoPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
|
||||
setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
|
||||
setPlistString(
|
||||
infoPlistPath,
|
||||
"CFBundleIdentifier",
|
||||
`${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
return JSON.parse(NodeFS.readFileSync(path, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
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 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 iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
NodeFS.mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
const expectedMetadata = {
|
||||
launcherVersion: LAUNCHER_VERSION,
|
||||
sourceAppBundlePath,
|
||||
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: statSync(iconPath).mtimeMs,
|
||||
sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
|
||||
appBundleId: APP_BUNDLE_ID,
|
||||
appProtocolSchemes: APP_PROTOCOL_SCHEMES,
|
||||
};
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
existsSync(targetBinaryPath) &&
|
||||
NodeFS.existsSync(targetBinaryPath) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
NodeFS.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,
|
||||
});
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
if (hostPlatform !== "linux") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
|
||||
try {
|
||||
const sandboxStat = NodeFS.statSync(sandboxPath);
|
||||
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveLinuxSandboxArgs(electronBinaryPath) {
|
||||
if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
console.warn(
|
||||
"[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
|
||||
);
|
||||
return ["--no-sandbox"];
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
ensureElectronRuntime();
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
// Dev launches do not need a renamed app bundle badly enough to risk breaking
|
||||
// Electron helper resource lookup on macOS.
|
||||
if (isDevelopment) {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
|
||||
export function resolveElectronLaunchCommand(args = []) {
|
||||
const electronPath = resolveElectronPath();
|
||||
return {
|
||||
electronPath,
|
||||
args: [...resolveLinuxSandboxArgs(electronPath), ...args],
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
|
||||
return {
|
||||
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
appBundleId: APP_BUNDLE_ID,
|
||||
};
|
||||
}
|
||||
@@ -1,13 +1,17 @@
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
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";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostArch = NodeOS.arch();
|
||||
|
||||
function getPlatformPath() {
|
||||
switch (process.platform) {
|
||||
switch (hostPlatform) {
|
||||
case "darwin":
|
||||
return "Electron.app/Contents/MacOS/Electron";
|
||||
case "freebsd":
|
||||
@@ -17,32 +21,34 @@ function getPlatformPath() {
|
||||
case "win32":
|
||||
return "electron.exe";
|
||||
default:
|
||||
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
|
||||
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureExecutable(filePath) {
|
||||
if (process.platform !== "win32") {
|
||||
chmodSync(filePath, 0o755);
|
||||
if (hostPlatform !== "win32") {
|
||||
NodeFS.chmodSync(filePath, 0o755);
|
||||
}
|
||||
}
|
||||
|
||||
function repairPathFile(electronDir, platformPath) {
|
||||
const pathFile = join(electronDir, "path.txt");
|
||||
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
|
||||
const pathFile = NodePath.join(electronDir, "path.txt");
|
||||
const currentPath = NodeFS.existsSync(pathFile)
|
||||
? NodeFS.readFileSync(pathFile, "utf8")
|
||||
: undefined;
|
||||
|
||||
if (currentPath !== platformPath) {
|
||||
writeFileSync(pathFile, platformPath);
|
||||
NodeFS.writeFileSync(pathFile, platformPath);
|
||||
}
|
||||
}
|
||||
|
||||
function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
const paths = [join(electronDir, "dist", platformPath)];
|
||||
const paths = [NodePath.join(electronDir, "dist", platformPath)];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
if (hostPlatform === "darwin") {
|
||||
paths.push(
|
||||
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
join(
|
||||
NodePath.join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
NodePath.join(
|
||||
electronDir,
|
||||
"dist",
|
||||
"Electron.app",
|
||||
@@ -58,11 +64,11 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function isMachO(filePath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const result = spawnSync("file", ["-b", filePath], {
|
||||
const result = NodeChildProcess.spawnSync("file", ["-b", filePath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
@@ -71,18 +77,18 @@ function isMachO(filePath) {
|
||||
|
||||
function missingRuntimePaths(electronDir, platformPath) {
|
||||
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
|
||||
return !existsSync(runtimePath);
|
||||
return !NodeFS.existsSync(runtimePath);
|
||||
});
|
||||
}
|
||||
|
||||
function invalidRuntimePaths(electronDir, platformPath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
join(electronDir, "dist", platformPath),
|
||||
join(
|
||||
NodePath.join(electronDir, "dist", platformPath),
|
||||
NodePath.join(
|
||||
electronDir,
|
||||
"dist",
|
||||
"Electron.app",
|
||||
@@ -91,11 +97,11 @@ function invalidRuntimePaths(electronDir, platformPath) {
|
||||
"Electron Framework.framework",
|
||||
"Electron Framework",
|
||||
),
|
||||
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
|
||||
].filter((runtimePath) => NodeFS.existsSync(runtimePath) && !isMachO(runtimePath));
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = spawnSync(command, args, {
|
||||
const result = NodeChildProcess.spawnSync(command, args, {
|
||||
encoding: "utf8",
|
||||
stdio: "inherit",
|
||||
});
|
||||
@@ -110,45 +116,45 @@ function runChecked(command, args) {
|
||||
}
|
||||
|
||||
function installElectronRuntime(electronDir, version) {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
|
||||
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-"));
|
||||
const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
|
||||
|
||||
try {
|
||||
runChecked("curl", [
|
||||
"-fsSL",
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
|
||||
"-o",
|
||||
zipPath,
|
||||
]);
|
||||
if (process.platform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
|
||||
if (hostPlatform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, NodePath.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,
|
||||
join(electronDir, "dist"),
|
||||
NodePath.join(electronDir, "dist"),
|
||||
]);
|
||||
}
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureElectronRuntime() {
|
||||
const electronPackageJsonPath = require.resolve("electron/package.json");
|
||||
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
|
||||
const electronDir = dirname(electronPackageJsonPath);
|
||||
const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8"));
|
||||
const electronDir = NodePath.dirname(electronPackageJsonPath);
|
||||
const platformPath = getPlatformPath();
|
||||
const electronPath = join(electronDir, "dist", platformPath);
|
||||
const electronPath = NodePath.join(electronDir, "dist", platformPath);
|
||||
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
|
||||
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
|
||||
|
||||
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
|
||||
if (existsSync(join(electronDir, "dist"))) {
|
||||
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
|
||||
if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) {
|
||||
NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true });
|
||||
}
|
||||
rmSync(join(electronDir, "path.txt"), { force: true });
|
||||
NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true });
|
||||
installElectronRuntime(electronDir, electronPackageJson.version);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const desktopDir = NodePath.resolve(__dirname, "..");
|
||||
const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
const child = spawn(electronBin, [mainJs], {
|
||||
const electronCommand = resolveElectronLaunchCommand([mainJs]);
|
||||
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
|
||||
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
|
||||
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
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";
|
||||
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";
|
||||
|
||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
||||
|
||||
async function fileExists(filePath) {
|
||||
try {
|
||||
await FileSystem.access(filePath);
|
||||
await NodeFSP.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 = Net.createConnection({ host, port });
|
||||
const socket = NodeNet.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(Path.resolve(baseDir, relativeFilePath));
|
||||
const ready = await fileExists(NodePath.resolve(baseDir, relativeFilePath));
|
||||
if (!ready) {
|
||||
pendingFiles.push(relativeFilePath);
|
||||
}
|
||||
@@ -114,6 +114,6 @@ export async function waitForResources({
|
||||
);
|
||||
}
|
||||
|
||||
await Timers.setTimeout(intervalMs);
|
||||
await NodeTimersPromises.setTimeout(intervalMs);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,23 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
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 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";
|
||||
@@ -31,22 +33,24 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
|
||||
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
|
||||
);
|
||||
|
||||
class DesktopBackendPortUnavailableError extends Data.TaggedError(
|
||||
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
|
||||
"DesktopBackendPortUnavailableError",
|
||||
)<{
|
||||
readonly startPort: number;
|
||||
readonly maxPort: number;
|
||||
readonly hosts: readonly string[];
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
startPort: Schema.Int,
|
||||
maxPort: Schema.Int,
|
||||
hosts: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
|
||||
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
|
||||
"DesktopDevelopmentBackendPortRequiredError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "T3CODE_PORT is required in desktop development.";
|
||||
}
|
||||
}
|
||||
@@ -99,12 +103,12 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
| DesktopLifecycle.DesktopShutdown
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
| DesktopState.DesktopState
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronDialog.ElectronDialog
|
||||
> {
|
||||
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
@@ -162,6 +166,16 @@ 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,
|
||||
});
|
||||
@@ -175,7 +189,7 @@ const bootstrap = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
yield* installDesktopIpcHandlers;
|
||||
yield* installDesktopIpcHandlers();
|
||||
yield* logBootstrapInfo("bootstrap ipc handlers registered");
|
||||
|
||||
if (!(yield* Ref.get(state.quitting))) {
|
||||
@@ -188,8 +202,8 @@ 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 shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
@@ -207,6 +221,7 @@ const startup = Effect.gen(function* () {
|
||||
|
||||
yield* appIdentity.configure;
|
||||
yield* lifecycle.register;
|
||||
yield* clerk.configure;
|
||||
|
||||
yield* electronApp.whenReady.pipe(
|
||||
Effect.withSpan("desktop.electron.whenReady"),
|
||||
@@ -215,7 +230,6 @@ 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"));
|
||||
@@ -226,7 +240,7 @@ const scopedProgram = Effect.scoped(
|
||||
yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
|
||||
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
|
||||
|
||||
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
DesktopBackendPortUnavailableError,
|
||||
DesktopDevelopmentBackendPortRequiredError,
|
||||
} from "./DesktopApp.ts";
|
||||
|
||||
describe("DesktopApp errors", () => {
|
||||
it("preserves unavailable backend port context", () => {
|
||||
const error = new DesktopBackendPortUnavailableError({
|
||||
startPort: 3_773,
|
||||
maxPort: 65_535,
|
||||
hosts: ["127.0.0.1", "0.0.0.0", "::"],
|
||||
});
|
||||
|
||||
assert.equal(error.startPort, 3_773);
|
||||
assert.equal(error.maxPort, 65_535);
|
||||
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports the required development port", () => {
|
||||
const error = new DesktopDevelopmentBackendPortRequiredError();
|
||||
|
||||
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
@@ -53,6 +54,9 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
calls.setAboutPanelOptions.push(options);
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: (iconPath) =>
|
||||
Effect.sync(() => {
|
||||
@@ -60,7 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronAppShape);
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
const makeAssetsLayer = (png: Option.Option<string>) =>
|
||||
Layer.succeed(DesktopAssets.DesktopAssets, {
|
||||
@@ -70,7 +74,7 @@ const makeAssetsLayer = (png: Option.Option<string>) =>
|
||||
png,
|
||||
}),
|
||||
resolveResourcePath: () => Effect.succeed(Option.none()),
|
||||
} satisfies DesktopAssets.DesktopAssetsShape);
|
||||
} satisfies DesktopAssets.DesktopAssets["Service"]);
|
||||
|
||||
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
|
||||
const { env, ...environmentOverrides } = overrides;
|
||||
@@ -102,6 +106,7 @@ const withIdentity = <A, E, R>(
|
||||
readonly calls?: ElectronAppCalls;
|
||||
readonly environment?: TestEnvironmentInput;
|
||||
readonly legacyPathExists?: boolean;
|
||||
readonly legacyPathProbeError?: PlatformError.PlatformError;
|
||||
readonly packageJson?: string;
|
||||
readonly pngIconPath?: Option.Option<string>;
|
||||
} = {},
|
||||
@@ -118,7 +123,11 @@ const withIdentity = <A, E, R>(
|
||||
Layer.provideMerge(
|
||||
FileSystem.layerNoop({
|
||||
exists: (path) =>
|
||||
Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
|
||||
input.legacyPathProbeError
|
||||
? Effect.fail(input.legacyPathProbeError)
|
||||
: Effect.succeed(
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
|
||||
),
|
||||
readFileString: () =>
|
||||
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
|
||||
}),
|
||||
@@ -144,6 +153,33 @@ describe("DesktopAppIdentity", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves failures while inspecting the legacy userData path", () => {
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "exists",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: legacyPath,
|
||||
});
|
||||
|
||||
return withIdentity(
|
||||
Effect.gen(function* () {
|
||||
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const error = yield* identity.resolveUserDataPath.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopAppIdentity.DesktopUserDataPathResolutionError);
|
||||
assert.equal(error.legacyPath, legacyPath);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to inspect legacy desktop user-data path at "${legacyPath}".`,
|
||||
);
|
||||
}),
|
||||
{ legacyPathProbeError: cause },
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("configures app identity from the environment commit override", () => {
|
||||
const calls: ElectronAppCalls = {
|
||||
setAboutPanelOptions: [],
|
||||
|
||||
@@ -18,14 +18,24 @@ 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 DesktopUserDataPathResolutionError extends Schema.TaggedErrorClass<DesktopUserDataPathResolutionError>()(
|
||||
"DesktopUserDataPathResolutionError",
|
||||
{
|
||||
legacyPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to inspect legacy desktop user-data path at "${this.legacyPath}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAppIdentity extends Context.Service<
|
||||
DesktopAppIdentity,
|
||||
DesktopAppIdentityShape
|
||||
{
|
||||
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
|
||||
|
||||
const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
@@ -35,7 +45,7 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
: Option.none();
|
||||
};
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const assets = yield* DesktopAssets.DesktopAssets;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -52,7 +62,7 @@ const make = Effect.gen(function* () {
|
||||
Effect.map((parsed) =>
|
||||
Option.fromNullishOr(parsed.t3codeCommitHash).pipe(Option.flatMap(normalizeCommitHash)),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none<string>())),
|
||||
Effect.orElseSucceed(() => Option.none<string>()),
|
||||
),
|
||||
});
|
||||
});
|
||||
@@ -85,9 +95,15 @@ const make = Effect.gen(function* () {
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem
|
||||
.exists(legacyPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopAssets from "./DesktopAssets.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
describe("DesktopAssets", () => {
|
||||
it.effect("preserves the failed asset candidate and filesystem cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileName = "custom.bin";
|
||||
const candidatePath = "/repo/apps/desktop/resources/custom.bin";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "exists",
|
||||
pathOrDescriptor: candidatePath,
|
||||
description: "private filesystem diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
exists: (path) => (path === candidatePath ? Effect.fail(cause) : Effect.succeed(false)),
|
||||
});
|
||||
const assetsLayer = DesktopAssets.layer.pipe(
|
||||
Layer.provide(Layer.merge(fileSystemLayer, environmentLayer)),
|
||||
);
|
||||
const assets = yield* DesktopAssets.DesktopAssets.pipe(Effect.provide(assetsLayer));
|
||||
|
||||
const error = yield* assets.resolveResourcePath(fileName).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopAssets.DesktopAssetProbeError);
|
||||
assert.equal(error.fileName, fileName);
|
||||
assert.equal(error.candidatePath, candidatePath);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to probe desktop asset "${fileName}" at ${candidatePath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private filesystem diagnostic");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
@@ -12,27 +13,47 @@ export interface DesktopIconPaths {
|
||||
readonly png: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface DesktopAssetsShape {
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
|
||||
export class DesktopAssetProbeError extends Schema.TaggedErrorClass<DesktopAssetProbeError>()(
|
||||
"DesktopAssetProbeError",
|
||||
{
|
||||
fileName: Schema.String,
|
||||
candidatePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to probe desktop asset "${this.fileName}" at ${this.candidatePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
|
||||
"@t3tools/desktop/app/DesktopAssets",
|
||||
) {}
|
||||
export class DesktopAssets extends Context.Service<
|
||||
DesktopAssets,
|
||||
{
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (
|
||||
fileName: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAssets") {}
|
||||
|
||||
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
|
||||
fileName: string,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
DesktopAssetProbeError,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const candidates = environment.resolveResourcePathCandidates(fileName);
|
||||
for (const candidate of candidates) {
|
||||
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
|
||||
const exists = yield* fileSystem
|
||||
.exists(candidate)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new DesktopAssetProbeError({ fileName, candidatePath: candidate, cause }),
|
||||
),
|
||||
);
|
||||
if (exists) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
@@ -44,16 +65,23 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
ext: keyof DesktopIconPaths,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
DesktopAssetProbeError,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
|
||||
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = environment.developmentDockIconPath;
|
||||
const developmentDockIconExists = yield* fileSystem
|
||||
.exists(developmentDockIconPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopAssetProbeError({
|
||||
fileName: "icon.png",
|
||||
candidatePath: developmentDockIconPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (developmentDockIconExists) {
|
||||
return Option.some(developmentDockIconPath);
|
||||
}
|
||||
@@ -62,7 +90,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
return yield* resolveResourcePath(`icon.${ext}`);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const context = yield* Effect.context<
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
>();
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
const withOutputLog = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
|
||||
messages: Array<ReadonlyArray<unknown>>,
|
||||
) => {
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
|
||||
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
return effect.pipe(Effect.provide(outputLogLayer));
|
||||
};
|
||||
|
||||
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
|
||||
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
|
||||
?.error;
|
||||
|
||||
describe("DesktopBackendOutputLog", () => {
|
||||
it.effect("logs setup failures with the log path and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
|
||||
description: "private setup diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private setup diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("logs record write failures with the operation and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const missingCause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
});
|
||||
const writeCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFile",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
description: "private write diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.void,
|
||||
stat: () => Effect.fail(missingCause),
|
||||
readDirectory: () => Effect.succeed([]),
|
||||
writeFile: () => Effect.fail(writeCause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
|
||||
assert.equal(error.operation, "write-record");
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, writeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private write diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,385 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly filePath: string;
|
||||
readonly writeBytes: (
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
readonly writeText: (
|
||||
chunk: string,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
|
||||
"DesktopLogFileWriterRecoveryError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
recoveryCause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
|
||||
"DesktopBackendOutputLogSetupError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
|
||||
"DesktopBackendOutputLogWriteError",
|
||||
{
|
||||
operation: Schema.Literals(["encode-record", "write-record"]),
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
|
||||
"DesktopBackendConsoleWriteError",
|
||||
{
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to mirror desktop backend output to ${this.streamName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
{
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, PlatformError.PlatformError> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const recoverCurrentSize = (
|
||||
cause: PlatformError.PlatformError,
|
||||
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: (recoveryCause) =>
|
||||
Effect.fail(
|
||||
new DesktopLogFileWriterRecoveryError({
|
||||
logFilePath: input.filePath,
|
||||
cause,
|
||||
recoveryCause,
|
||||
}),
|
||||
),
|
||||
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
|
||||
}),
|
||||
);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory);
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source);
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem.exists(input.filePath);
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
});
|
||||
|
||||
const writeBytes = (
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: recoverCurrentSize,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
filePath: input.filePath,
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
},
|
||||
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "encode-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* logFile.writeText(`${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "write-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: logFilePath,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogSetupError: (error) =>
|
||||
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
|
||||
}),
|
||||
);
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLog.of(service);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendOutputLog, make);
|
||||
@@ -0,0 +1,149 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
|
||||
createClerkBridgeMock: vi.fn(),
|
||||
storageAdapter: {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
},
|
||||
storageMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/electron", () => ({
|
||||
createClerkBridge: createClerkBridgeMock,
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/electron/storage", () => ({
|
||||
storage: storageMock,
|
||||
}));
|
||||
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const makeDesktopClerkLayer = (isDevelopment = true) => {
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
return DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
);
|
||||
};
|
||||
|
||||
describe("DesktopClerk", () => {
|
||||
beforeEach(() => {
|
||||
createClerkBridgeMock.mockReset();
|
||||
storageMock.mockReset();
|
||||
});
|
||||
|
||||
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
|
||||
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
|
||||
|
||||
assert.equal(
|
||||
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
|
||||
"clerk.t3.codes",
|
||||
);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
|
||||
});
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
const cleanup = vi.fn();
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
{
|
||||
storage: storageAdapter,
|
||||
passkeys: true,
|
||||
renderer: { scheme: "t3code-dev", host: "app" },
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(cleanup.mock.calls.length, 1);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("preserves bridge initialization failures", () => {
|
||||
const cause = new Error("bridge initialization failed");
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
|
||||
assert.equal(error.stateDir, "/tmp/t3-state");
|
||||
assert.equal(error.isDevelopment, true);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("preserves bridge cleanup failures", () => {
|
||||
const cause = new Error("bridge cleanup failed");
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({
|
||||
cleanup: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
|
||||
assert.equal(error.stateDir, "/tmp/t3-state");
|
||||
assert.equal(error.isDevelopment, false);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isDevelopment: true, scheme: "t3code-dev" },
|
||||
{ isDevelopment: false, scheme: "t3code" },
|
||||
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
|
||||
const bridge = { cleanup: vi.fn() };
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
|
||||
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
{
|
||||
storage: storageAdapter,
|
||||
passkeys: true,
|
||||
renderer: { scheme, host: "app" },
|
||||
},
|
||||
],
|
||||
]);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { createClerkBridge } from "@clerk/electron";
|
||||
import { storage } from "@clerk/electron/storage";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(
|
||||
"DesktopClerkBridgeInitializationError",
|
||||
{
|
||||
stateDir: Schema.String,
|
||||
isDevelopment: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(
|
||||
"DesktopClerkBridgeCleanupError",
|
||||
{
|
||||
stateDir: Schema.String,
|
||||
isDevelopment: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopClerk extends Context.Service<
|
||||
DesktopClerk,
|
||||
{
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopClerk") {}
|
||||
|
||||
export function resolveDesktopClerkFrontendApiHostname(
|
||||
publishableKey: string | undefined,
|
||||
): string | undefined {
|
||||
const normalizedKey = publishableKey?.trim();
|
||||
if (!normalizedKey) return undefined;
|
||||
|
||||
try {
|
||||
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
|
||||
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
|
||||
? undefined
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
|
||||
);
|
||||
|
||||
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
|
||||
return createClerkBridge({
|
||||
storage: storage({ path: stateDir }),
|
||||
passkeys: true,
|
||||
renderer: {
|
||||
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
|
||||
host: ElectronProtocol.DESKTOP_HOST,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
|
||||
catch: (cause) =>
|
||||
new DesktopClerkBridgeInitializationError({
|
||||
stateDir: environment.stateDir,
|
||||
isDevelopment: environment.isDevelopment,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
(bridge) =>
|
||||
Effect.try({
|
||||
try: () => bridge.cleanup(),
|
||||
catch: (cause) =>
|
||||
new DesktopClerkBridgeCleanupError({
|
||||
stateDir: environment.stateDir,
|
||||
isDevelopment: environment.isDevelopment,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
|
||||
return DesktopClerk.of({
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
if (!(yield* electronApp.requestSingleInstanceLock)) {
|
||||
yield* electronApp.quit;
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
|
||||
yield* electronApp.on("second-instance", () => {
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.clerk.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopClerk, make);
|
||||
@@ -37,6 +37,7 @@ export const DesktopConfig = Config.all({
|
||||
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
|
||||
t3Home: trimmedString("T3CODE_HOME"),
|
||||
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
|
||||
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
|
||||
devRemoteT3ServerEntryPath: trimmedString("T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH"),
|
||||
configuredBackendPort: Config.port("T3CODE_PORT").pipe(Config.option),
|
||||
commitHashOverride: trimmedString("T3CODE_COMMIT_HASH"),
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
|
||||
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
const decodeConnectionCatalog = Schema.decodeEffect(
|
||||
Schema.fromJsonString(ConnectionCatalogDocument),
|
||||
);
|
||||
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(available),
|
||||
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
|
||||
decryptString: (value) => {
|
||||
return Effect.gen(function* () {
|
||||
const decoded = textDecoder.decode(value);
|
||||
if (
|
||||
!decoded.startsWith("encrypted:") ||
|
||||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
|
||||
) {
|
||||
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
|
||||
cause: new Error("invalid encrypted catalog"),
|
||||
});
|
||||
}
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
baseDir: string,
|
||||
encryptionAvailable = true,
|
||||
failDecrypt: Ref.Ref<boolean> | null = null,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
|
||||
) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
|
||||
const dependencies = Layer.mergeAll(
|
||||
environmentLayer,
|
||||
safeStorageLayer,
|
||||
NodeServices.layer,
|
||||
fileSystemLayer,
|
||||
);
|
||||
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
|
||||
Layer.provideMerge(dependencies),
|
||||
);
|
||||
|
||||
return DesktopConnectionCatalogStore.layer.pipe(
|
||||
Layer.provideMerge(savedEnvironmentsLayer),
|
||||
Layer.provideMerge(dependencies),
|
||||
);
|
||||
}
|
||||
|
||||
const withStore = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
|
||||
encryptionAvailable = true,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopConnectionCatalogStore", () => {
|
||||
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalog = '{"schemaVersion":1,"targets":[]}';
|
||||
|
||||
assert.isTrue(yield* store.set(catalog));
|
||||
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
|
||||
|
||||
yield* store.clear;
|
||||
assert.deepStrictEqual(yield* store.get, Option.none());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist when secure storage is unavailable", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
assert.isFalse(yield* store.set("{}"));
|
||||
assert.deepStrictEqual(yield* store.get, Option.none());
|
||||
}),
|
||||
false,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const records: readonly PersistedSavedEnvironmentRecord[] = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("relay-environment"),
|
||||
label: "Relay",
|
||||
httpBaseUrl: "https://relay.example.com/",
|
||||
wsBaseUrl: "wss://relay.example.com/",
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
relayManaged: { relayUrl: "https://relay-control.example.com/" },
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
httpBaseUrl: "http://127.0.0.1:41773/",
|
||||
wsBaseUrl: "ws://127.0.0.1:41773/",
|
||||
createdAt: "2026-06-02T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
httpBaseUrl: "https://bearer.example.com/",
|
||||
wsBaseUrl: "wss://bearer.example.com/",
|
||||
createdAt: "2026-06-03T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
},
|
||||
];
|
||||
yield* savedEnvironments.setRegistry(records);
|
||||
assert.isTrue(
|
||||
yield* savedEnvironments.setSecret({
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
secret: "legacy-token",
|
||||
}),
|
||||
);
|
||||
|
||||
const migrated = yield* store.get;
|
||||
assert.isTrue(Option.isSome(migrated));
|
||||
if (Option.isNone(migrated)) {
|
||||
return;
|
||||
}
|
||||
const catalog = yield* decodeConnectionCatalog(migrated.value);
|
||||
|
||||
assert.deepInclude(catalog.targets[0], {
|
||||
_tag: "RelayConnectionTarget",
|
||||
environmentId: EnvironmentId.make("relay-environment"),
|
||||
label: "Relay",
|
||||
});
|
||||
assert.deepInclude(catalog.targets[1], {
|
||||
_tag: "SshConnectionTarget",
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
connectionId: "ssh:ssh-environment",
|
||||
});
|
||||
assert.deepInclude(catalog.targets[2], {
|
||||
_tag: "BearerConnectionTarget",
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
connectionId: "bearer:bearer-environment",
|
||||
});
|
||||
assert.deepInclude(catalog.profiles[0], {
|
||||
_tag: "SshConnectionProfile",
|
||||
connectionId: "ssh:ssh-environment",
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
target: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
});
|
||||
assert.deepInclude(catalog.profiles[1], {
|
||||
_tag: "BearerConnectionProfile",
|
||||
connectionId: "bearer:bearer-environment",
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
httpBaseUrl: "https://bearer.example.com/",
|
||||
wsBaseUrl: "wss://bearer.example.com/",
|
||||
});
|
||||
assert.equal(catalog.credentials.length, 1);
|
||||
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
|
||||
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
|
||||
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
|
||||
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
|
||||
}
|
||||
|
||||
yield* savedEnvironments.setRegistry([]);
|
||||
assert.deepEqual(yield* store.get, migrated);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces malformed catalog documents without deleting them", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, "{not-json");
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
|
||||
);
|
||||
assert.equal(error.catalogPath, catalogPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the failed catalog write operation and path", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
makeDirectory: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* store.set("{}").pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
|
||||
);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the legacy migration stage", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError,
|
||||
);
|
||||
assert.equal(error.operation, "read-legacy-registry");
|
||||
assert.equal(error.catalogPath, `${environment.stateDir}/connection-catalog.json`);
|
||||
assert.instanceOf(
|
||||
error.cause,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
const registryError =
|
||||
error.cause as DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
assert.exists(registryError.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${environment.stateDir}/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, registryError.message);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports invalid encrypted catalog data without exposing it", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n');
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError,
|
||||
);
|
||||
assert.equal(error.resource, "encryptedCatalog");
|
||||
assert.equal(error.catalogPath, catalogPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to decode encryptedCatalog for the desktop connection catalog at ${catalogPath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "%%%");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const failDecrypt = yield* Ref.make(false);
|
||||
const layer = makeLayer(baseDir, true, failDecrypt);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
|
||||
yield* Ref.set(failDecrypt, true);
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,516 @@
|
||||
import {
|
||||
BearerConnectionCredential,
|
||||
BearerConnectionProfile,
|
||||
BearerConnectionTarget,
|
||||
RelayConnectionTarget,
|
||||
SshConnectionProfile,
|
||||
SshConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
|
||||
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const EncryptedConnectionCatalogDocument = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
encryptedCatalog: Schema.String,
|
||||
});
|
||||
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
|
||||
|
||||
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
|
||||
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
|
||||
EncryptedConnectionCatalogDocumentJson,
|
||||
);
|
||||
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
EncryptedConnectionCatalogDocumentJson,
|
||||
);
|
||||
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
|
||||
RuntimeConnectionCatalogDocument,
|
||||
);
|
||||
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
RuntimeConnectionCatalogDocumentJson,
|
||||
);
|
||||
|
||||
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-catalog-file",
|
||||
]);
|
||||
|
||||
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"read-legacy-registry",
|
||||
"read-legacy-secret",
|
||||
"encode-catalog",
|
||||
"persist-catalog",
|
||||
]);
|
||||
|
||||
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-catalog",
|
||||
"decrypt-catalog",
|
||||
]);
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
{
|
||||
resource: Schema.Literal("encryptedCatalog"),
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
|
||||
"DesktopConnectionCatalogStoreReadError",
|
||||
{
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDocumentDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDocumentDecodeError",
|
||||
{
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreMigrationError>()(
|
||||
"DesktopConnectionCatalogStoreMigrationError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: Schema.String,
|
||||
environmentId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const environment =
|
||||
this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
|
||||
return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
|
||||
"DesktopConnectionCatalogStoreProtectionError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreProtectionOperation,
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
DesktopConnectionCatalogStore,
|
||||
{
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopConnectionCatalogStoreReadError
|
||||
| DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
catalogPath: string,
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreDecodeError({
|
||||
resource: "encryptedCatalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
catalogPath: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<EncryptedConnectionCatalogDocument>,
|
||||
DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
> =>
|
||||
fileSystem.readFileString(catalogPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound"
|
||||
? Effect.succeed<string | null>(null)
|
||||
: Effect.fail(
|
||||
new DesktopConnectionCatalogStoreReadError({
|
||||
catalogPath,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
|
||||
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreDocumentDecodeError({
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly catalogPath: string;
|
||||
readonly document: EncryptedConnectionCatalogDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "replace-catalog-file",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
input.fileSystem.remove(tempPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not remove a temporary connection catalog file.", {
|
||||
tempPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
|
||||
return `${prefix}:${environmentId}`;
|
||||
}
|
||||
|
||||
const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
|
||||
)(function* (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
|
||||
catalogPath: string,
|
||||
): Effect.fn.Return<
|
||||
RuntimeConnectionCatalogDocumentType,
|
||||
DesktopConnectionCatalogStoreMigrationError
|
||||
> {
|
||||
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
|
||||
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
|
||||
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
|
||||
|
||||
for (const record of records) {
|
||||
if (record.relayManaged !== undefined) {
|
||||
targets.push(
|
||||
new RelayConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (record.desktopSsh !== undefined) {
|
||||
const id = connectionId("ssh", record.environmentId);
|
||||
targets.push(
|
||||
new SshConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
connectionId: id,
|
||||
}),
|
||||
);
|
||||
profiles.push(
|
||||
new SshConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
target: record.desktopSsh,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = connectionId("bearer", record.environmentId);
|
||||
targets.push(
|
||||
new BearerConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
connectionId: id,
|
||||
}),
|
||||
);
|
||||
profiles.push(
|
||||
new BearerConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-secret",
|
||||
catalogPath,
|
||||
environmentId: record.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(token)) {
|
||||
credentials.push({
|
||||
connectionId: id,
|
||||
credential: new BearerConnectionCredential({ token: token.value }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
targets,
|
||||
profiles,
|
||||
credentials,
|
||||
remoteDpopTokens: [],
|
||||
};
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(catalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "encrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
catalogPath,
|
||||
document: { version: 1, encryptedCatalog },
|
||||
suffix,
|
||||
});
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-registry",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "encode-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* writeCatalog(encoded).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "persist-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Option.some(encoded);
|
||||
});
|
||||
|
||||
return DesktopConnectionCatalogStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, catalogPath);
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap((encryptedCatalog) =>
|
||||
safeStorage.decryptString(encryptedCatalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "decrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear the desktop connection catalog.", {
|
||||
catalogPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.connectionCatalogStore.clear"),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopConnectionCatalogStore, make);
|
||||
@@ -0,0 +1,37 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
|
||||
import { DesktopLifecycleRelaunchError } from "./DesktopLifecycle.ts";
|
||||
import { DesktopApplicationMenuActionError } from "../window/DesktopApplicationMenu.ts";
|
||||
|
||||
describe("desktop detached action errors", () => {
|
||||
it("preserves the complete relaunch failure cause and reason", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("shutdown failed")),
|
||||
Cause.die(new Error("relaunch defect")),
|
||||
);
|
||||
const error = new DesktopLifecycleRelaunchError({
|
||||
reason: "apply update",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.reason, "apply update");
|
||||
assert.equal(error.message, 'Desktop relaunch failed for reason "apply update".');
|
||||
});
|
||||
|
||||
it("preserves the complete menu action failure cause and action", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("window unavailable")),
|
||||
Cause.die(new Error("dispatch defect")),
|
||||
);
|
||||
const error = new DesktopApplicationMenuActionError({
|
||||
action: "open-settings",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.action, "open-settings");
|
||||
assert.equal(error.message, 'Desktop menu action "open-settings" failed.');
|
||||
});
|
||||
});
|
||||
@@ -59,6 +59,7 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
|
||||
assert.equal(environment.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
@@ -89,10 +90,25 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.isDevelopment, false);
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses a configured app user model id override", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
{},
|
||||
{
|
||||
T3CODE_DESKTOP_APP_USER_MODEL_ID: " com.t3tools.t3code.dev.local ",
|
||||
VITE_DEV_SERVER_URL: "http://localhost:5173",
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev.local");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves picker defaults without nullish sentinels", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment();
|
||||
|
||||
@@ -11,10 +11,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import {
|
||||
type DesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
} from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
|
||||
|
||||
@@ -30,54 +27,53 @@ 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 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,
|
||||
DesktopEnvironmentShape
|
||||
{
|
||||
readonly path: Path.Path;
|
||||
readonly dirname: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly processArch: string;
|
||||
readonly isPackaged: boolean;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
readonly appPath: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly homeDirectory: string;
|
||||
readonly appDataDirectory: string;
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: string;
|
||||
readonly desktopSettingsPath: string;
|
||||
readonly clientSettingsPath: string;
|
||||
readonly savedEnvironmentRegistryPath: string;
|
||||
readonly serverSettingsPath: string;
|
||||
readonly logDir: string;
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
readonly appUpdateYmlPath: string;
|
||||
readonly devServerUrl: Option.Option<URL>;
|
||||
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
|
||||
readonly configuredBackendPort: Option.Option<number>;
|
||||
readonly commitHashOverride: Option.Option<string>;
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
readonly branding: DesktopAppBranding;
|
||||
readonly displayName: string;
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
readonly runtimeInfo: DesktopRuntimeInfo;
|
||||
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
|
||||
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
|
||||
readonly developmentDockIconPath: string;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopEnvironment") {}
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
@@ -135,9 +131,9 @@ function resolveDesktopRuntimeInfo(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
const make = Effect.fn("desktop.environment.make")(function* (
|
||||
input: MakeDesktopEnvironmentInput,
|
||||
): Effect.fn.Return<DesktopEnvironmentShape, Config.ConfigError, Path.Path> {
|
||||
): Effect.fn.Return<DesktopEnvironment["Service"], Config.ConfigError, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const homeDirectory = input.homeDirectory;
|
||||
@@ -183,6 +179,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
|
||||
serverSettingsPath: path.join(stateDir, "settings.json"),
|
||||
logDir: path.join(stateDir, "logs"),
|
||||
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
|
||||
rootDir,
|
||||
appRoot,
|
||||
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
|
||||
@@ -199,12 +196,14 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
otlpExportIntervalMs: config.otlpExportIntervalMs,
|
||||
branding,
|
||||
displayName,
|
||||
appUserModelId: isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code",
|
||||
appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () =>
|
||||
isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code",
|
||||
),
|
||||
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
runtimeInfo: resolveDesktopRuntimeInfo({
|
||||
platform: input.platform,
|
||||
processArch: input.processArch,
|
||||
@@ -246,4 +245,4 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
});
|
||||
|
||||
export const layer = (input: MakeDesktopEnvironmentInput) =>
|
||||
Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
|
||||
Layer.effect(DesktopEnvironment, make(input));
|
||||
@@ -1,75 +1,55 @@
|
||||
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 Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.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 DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()(
|
||||
"DesktopLifecycleRelaunchError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop relaunch failed for reason "${this.reason}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export 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, DesktopLifecycleShape>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle",
|
||||
) {}
|
||||
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") {}
|
||||
|
||||
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-lifecycle");
|
||||
makeComponentLogger("desktop-lifecycle");
|
||||
|
||||
function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
target: unknown,
|
||||
@@ -93,8 +73,8 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
}
|
||||
|
||||
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdown;
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
yield* shutdown.request;
|
||||
yield* shutdown.awaitComplete;
|
||||
},
|
||||
@@ -154,83 +134,81 @@ function quitFromSignal(
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
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;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
|
||||
yield* electronApp.relaunch({
|
||||
execPath: process.execPath,
|
||||
args: process.argv.slice(1),
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
const error = new DesktopLifecycleRelaunchError({ reason, cause });
|
||||
return logLifecycleError(error.message, { error });
|
||||
}),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
);
|
||||
register: Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
|
||||
const runEffect = Effect.runPromiseWith(context);
|
||||
let quitAllowed = false;
|
||||
yield* electronTheme.onUpdated(() => {
|
||||
void runEffect(
|
||||
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("before-quit", (event: Electron.Event) => {
|
||||
handleBeforeQuit(
|
||||
event,
|
||||
runEffect,
|
||||
() => quitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("activate", () => {
|
||||
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
|
||||
});
|
||||
yield* electronApp.on("window-all-closed", () => {
|
||||
void runEffect(
|
||||
Effect.gen(function* () {
|
||||
const app = yield* ElectronApp.ElectronApp;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
|
||||
yield* app.quit;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
|
||||
);
|
||||
});
|
||||
|
||||
if (environment.platform !== "win32") {
|
||||
yield* addScopedListener(process, "SIGINT", () => {
|
||||
quitFromSignal("SIGINT", runEffect);
|
||||
});
|
||||
yield* addScopedListener(process, "SIGTERM", () => {
|
||||
quitFromSignal("SIGTERM", runEffect);
|
||||
});
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(DesktopLifecycle, make);
|
||||
@@ -1,52 +1,20 @@
|
||||
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 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 { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
|
||||
|
||||
export type DesktopLogAnnotations = Record<string, unknown>;
|
||||
|
||||
@@ -82,165 +50,7 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
|
||||
};
|
||||
}
|
||||
|
||||
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 readPersistedOtlpTracesUrl = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
|
||||
@@ -260,90 +70,6 @@ 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"),
|
||||
@@ -356,8 +82,8 @@ const tracerLayer = Layer.unwrap(
|
||||
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
const sink = yield* makeTraceSink({
|
||||
filePath: tracePath,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
});
|
||||
const delegate = Option.isNone(otlpTracesUrl)
|
||||
@@ -375,8 +101,8 @@ const tracerLayer = Layer.unwrap(
|
||||
});
|
||||
const tracer = yield* makeLocalFileTracer({
|
||||
filePath: tracePath,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
sink,
|
||||
...(delegate ? { delegate } : {}),
|
||||
@@ -387,7 +113,7 @@ const tracerLayer = Layer.unwrap(
|
||||
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
|
||||
|
||||
export const layer = Layer.mergeAll(
|
||||
backendOutputLogLayer,
|
||||
DesktopBackendOutputLogModule.layer,
|
||||
desktopLoggerLayer,
|
||||
tracerLayer,
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
export class DesktopShutdown extends Context.Service<
|
||||
DesktopShutdown,
|
||||
{
|
||||
readonly request: Effect.Effect<void>;
|
||||
readonly awaitRequest: Effect.Effect<void>;
|
||||
readonly markComplete: Effect.Effect<void>;
|
||||
readonly awaitComplete: Effect.Effect<void>;
|
||||
readonly isComplete: Effect.Effect<boolean>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopShutdown") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<void>();
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const completedRef = yield* Ref.make(false);
|
||||
|
||||
return DesktopShutdown.of({
|
||||
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
|
||||
awaitRequest: Deferred.await(requested),
|
||||
markComplete: Ref.set(completedRef, true).pipe(
|
||||
Effect.andThen(Deferred.succeed(completed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
awaitComplete: Deferred.await(completed),
|
||||
isComplete: Ref.get(completedRef),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopShutdown, make);
|
||||
@@ -3,19 +3,17 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
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(
|
||||
export class DesktopState extends Context.Service<
|
||||
DesktopState,
|
||||
Effect.all({
|
||||
backendReady: Ref.make(false),
|
||||
quitting: Ref.make(false),
|
||||
}),
|
||||
);
|
||||
{
|
||||
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);
|
||||
@@ -3,6 +3,8 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
@@ -21,6 +23,10 @@ const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
|
||||
Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
|
||||
);
|
||||
|
||||
const isDesktopBackendObservabilitySettingsReadError = Schema.is(
|
||||
DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
|
||||
);
|
||||
|
||||
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
backendConfig: Effect.succeed({
|
||||
@@ -34,7 +40,7 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.succeed([]),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposureShape);
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
|
||||
function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
@@ -166,6 +172,62 @@ describe("DesktopBackendConfiguration", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("logs structured context when persisted observability settings cannot be read", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const settingsPath = `${baseDir}/userdata/settings.json`;
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: settingsPath,
|
||||
});
|
||||
const messages: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
});
|
||||
const failingFileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(cause),
|
||||
}),
|
||||
);
|
||||
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolve;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
Layer.provideMerge(failingFileSystemLayer),
|
||||
),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.isUndefined(config.bootstrap.otlpTracesUrl);
|
||||
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
|
||||
|
||||
const error = messages
|
||||
.flatMap((message) => (Array.isArray(message) ? message : [message]))
|
||||
.find(isDesktopBackendObservabilitySettingsReadError);
|
||||
assert.isDefined(error);
|
||||
assert.equal(error.settingsPath, settingsPath);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read persisted backend observability settings at ${settingsPath}.`,
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("captures backend output in development so child process logs can be persisted", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -8,22 +8,32 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
|
||||
export interface DesktopBackendConfigurationShape {
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
|
||||
"DesktopBackendObservabilitySettingsReadError",
|
||||
{
|
||||
settingsPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
DesktopBackendConfigurationShape
|
||||
{
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
interface BackendObservabilitySettings {
|
||||
@@ -52,29 +62,34 @@ const DESKTOP_BACKEND_ENV_NAMES = [
|
||||
const backendChildEnvPatch = (): Record<string, string | undefined> =>
|
||||
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
|
||||
|
||||
const { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
|
||||
"desktop-backend-configuration",
|
||||
);
|
||||
const logBackendObservabilitySettingsReadFailure = (
|
||||
settingsPath: string,
|
||||
cause: PlatformError.PlatformError,
|
||||
) => {
|
||||
const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
|
||||
return Effect.logWarning(error).pipe(
|
||||
Effect.annotateLogs({
|
||||
component: "desktop-backend-configuration",
|
||||
error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const readPersistedBackendObservabilitySettings: Effect.Effect<
|
||||
BackendObservabilitySettings,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const exists = yield* fileSystem
|
||||
.exists(environment.serverSettingsPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return emptyBackendObservabilitySettings;
|
||||
}
|
||||
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none())
|
||||
: logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
|
||||
Effect.as(Option.none()),
|
||||
),
|
||||
}),
|
||||
);
|
||||
if (Option.isNone(raw)) {
|
||||
yield* logBackendConfigurationWarning(
|
||||
"failed to read persisted backend observability settings",
|
||||
);
|
||||
return emptyBackendObservabilitySettings;
|
||||
}
|
||||
|
||||
@@ -130,40 +145,39 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
},
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
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")),
|
||||
});
|
||||
}),
|
||||
);
|
||||
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);
|
||||
@@ -3,12 +3,15 @@ import {
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -28,6 +31,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -55,9 +59,9 @@ const configWithObservability: DesktopBackendBootstrapValue = {
|
||||
};
|
||||
|
||||
function makeProcess(options?: {
|
||||
readonly stdout?: Stream.Stream<Uint8Array>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
@@ -104,9 +108,9 @@ function decodeBootstrap(raw: string) {
|
||||
function makeManagerLayer(input: {
|
||||
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
|
||||
readonly desktopState?: DesktopState.DesktopStateShape;
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
|
||||
readonly desktopState?: DesktopState.DesktopState["Service"];
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
@@ -127,7 +131,7 @@ function makeManagerLayer(input: {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
...input.backendOutputLog,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected createMain"),
|
||||
ensureMain: Effect.die("unexpected ensureMain"),
|
||||
@@ -138,13 +142,30 @@ function makeManagerLayer(input: {
|
||||
dispatchMenuAction: () => Effect.void,
|
||||
syncAppearance: Effect.void,
|
||||
...input.desktopWindow,
|
||||
} satisfies DesktopWindow.DesktopWindowShape),
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("DesktopBackendManager", () => {
|
||||
it("preserves the complete restart cause and schedule context", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("start failed")),
|
||||
Cause.die(new Error("restart defect")),
|
||||
);
|
||||
const error = new DesktopBackendManager.DesktopBackendRestartError({
|
||||
reason: "backend exited with code 1",
|
||||
delayMs: 500,
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.reason, "backend exited with code 1");
|
||||
assert.equal(error.delayMs, 500);
|
||||
assert.equal(error.message, "Desktop backend restart failed after a scheduled 500ms delay.");
|
||||
});
|
||||
|
||||
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.Command | undefined;
|
||||
@@ -218,6 +239,243 @@ describe("DesktopBackendManager", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves the readiness timeout cause and process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
|
||||
const layer = Layer.merge(
|
||||
TestClock.layer(),
|
||||
httpClientLayer((request) =>
|
||||
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const readiness = yield* DesktopBackendManager.waitForHttpReady({
|
||||
executablePath: baseConfig.executablePath,
|
||||
entryPath: baseConfig.entryPath,
|
||||
cwd: baseConfig.cwd,
|
||||
httpBaseUrl: baseConfig.httpBaseUrl,
|
||||
timeout: Duration.millis(50),
|
||||
}).pipe(Effect.flip, Effect.forkChild);
|
||||
|
||||
const request = yield* Deferred.await(requested);
|
||||
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const error = yield* Fiber.join(readiness);
|
||||
|
||||
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
assert.equal(error.timeoutMs, 50);
|
||||
assert.isTrue(Cause.isTimeoutError(error.cause));
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports bootstrap encoding failures with stable process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
bootstrap: {
|
||||
...baseConfig.bootstrap,
|
||||
port: 0,
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessBootstrapEncodeError") {
|
||||
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.isDefined(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
|
||||
);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves spawn failures without deriving their message from the cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcessSpawner",
|
||||
method: "spawn",
|
||||
pathOrDescriptor: baseConfig.executablePath,
|
||||
description: "low-level detail that must not become the public message",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessSpawnError") {
|
||||
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, spawnCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
|
||||
);
|
||||
assert.notInclude(error.message, spawnCause.message);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves exit-status failures without copying their detail into the message", () =>
|
||||
Effect.gen(function* () {
|
||||
const exitCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcess",
|
||||
method: "exitCode",
|
||||
description: "exit-status-secret-sentinel",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
exitCode: Effect.fail(exitCause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessExitStatusError") {
|
||||
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, exitCause);
|
||||
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
|
||||
assert.notInclude(error.message, "exit-status-secret-sentinel");
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output stream failures with process and stream context", () =>
|
||||
Effect.gen(function* () {
|
||||
const outputCause = PlatformError.systemError({
|
||||
_tag: "BadResource",
|
||||
module: "ChildProcess",
|
||||
method: "stdout",
|
||||
description: "output-stream-secret-sentinel",
|
||||
});
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fail(outputCause),
|
||||
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputReadError") {
|
||||
return assert.fail(`Expected output read error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
|
||||
assert.notInclude(error.message, "output-stream-secret-sentinel");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output handler failures separately from stream read failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const chunk = new TextEncoder().encode("backend output");
|
||||
const outputCause = new Error("output-handler-secret-sentinel");
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.make(chunk),
|
||||
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
onOutput: () => Effect.fail(outputCause),
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputHandlingError") {
|
||||
return assert.fail(`Expected output handling error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.equal(error.chunkByteLength, chunk.byteLength);
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
|
||||
);
|
||||
assert.notInclude(error.message, "output-handler-secret-sentinel");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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";
|
||||
@@ -10,14 +9,14 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
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 {
|
||||
DesktopBackendBootstrap,
|
||||
@@ -43,59 +42,145 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export interface DesktopBackendStartConfig {
|
||||
export interface BackendProcessContext {
|
||||
readonly executablePath: string;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly httpBaseUrl: URL;
|
||||
}
|
||||
|
||||
export interface DesktopBackendStartConfig extends BackendProcessContext {
|
||||
readonly env: Record<string, string | undefined>;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly httpBaseUrl: URL;
|
||||
readonly captureOutput: boolean;
|
||||
}
|
||||
|
||||
interface BackendProcessExit {
|
||||
readonly code: Option.Option<number>;
|
||||
readonly reason: string;
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
|
||||
readonly url: URL;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
const backendProcessContextSchema = {
|
||||
executablePath: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cwd: Schema.String,
|
||||
httpBaseUrl: Schema.URL,
|
||||
};
|
||||
|
||||
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
|
||||
"BackendReadinessTimeoutError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
readinessUrl: Schema.URL,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessBootstrapEncodeError extends Data.TaggedError(
|
||||
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
)<{
|
||||
readonly cause: Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
|
||||
readonly cause: PlatformError.PlatformError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to spawn desktop backend process: ${this.cause.message}`;
|
||||
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
|
||||
"BackendProcessOutputReadError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
|
||||
"BackendProcessOutputHandlingError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
chunkByteLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type BackendProcessOutputError =
|
||||
| BackendProcessOutputReadError
|
||||
| BackendProcessOutputHandlingError;
|
||||
|
||||
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
|
||||
"BackendProcessExitStatusError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
|
||||
"DesktopBackendRestartError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
delayMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BackendProcessError = Schema.Union([
|
||||
BackendProcessBootstrapEncodeError,
|
||||
BackendProcessSpawnError,
|
||||
BackendProcessExitStatusError,
|
||||
]);
|
||||
export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
|
||||
readonly onOutput?: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void, Error>;
|
||||
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendSnapshot {
|
||||
@@ -106,16 +191,14 @@ 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,
|
||||
DesktopBackendManagerShape
|
||||
{
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
@@ -176,11 +259,10 @@ const closeRun = (
|
||||
).pipe(Effect.ignore);
|
||||
};
|
||||
|
||||
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
options: BackendProcessContext & { readonly timeout: Duration.Duration },
|
||||
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
|
||||
const client = (yield* HttpClient.HttpClient).pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
|
||||
@@ -189,48 +271,78 @@ const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(fu
|
||||
|
||||
yield* client.get(readinessUrl).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.timeout(timeout),
|
||||
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
|
||||
Effect.timeout(options.timeout),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendReadinessTimeoutError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
readinessUrl,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function describeProcessExit(
|
||||
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
): BackendProcessExit {
|
||||
if (Result.isSuccess(result)) {
|
||||
return {
|
||||
code: Option.some(result.success),
|
||||
reason: `code=${result.success}`,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
code: Option.none(),
|
||||
reason: result.failure.message,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
function drainBackendOutput(
|
||||
context: BackendProcessContext & { readonly pid: number },
|
||||
streamName: BackendProcessOutputStream,
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
|
||||
onOutput: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>,
|
||||
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
|
||||
): Effect.Effect<void> {
|
||||
return stream.pipe(
|
||||
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
|
||||
Effect.ignore,
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputReadError({
|
||||
...context,
|
||||
streamName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Stream.runForEach((chunk) =>
|
||||
onOutput(streamName, chunk).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputHandlingError({
|
||||
...context,
|
||||
streamName,
|
||||
chunkByteLength: chunk.byteLength,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BackendProcessOutputReadError: onOutputFailure,
|
||||
BackendProcessOutputHandlingError: onOutputFailure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
|
||||
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const command = ChildProcess.make(
|
||||
@@ -256,28 +368,78 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
).pipe(
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
const exitCode = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessExitStatusError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
code: Option.some(exitCode),
|
||||
reason: `code=${exitCode}`,
|
||||
} satisfies BackendProcessExit;
|
||||
});
|
||||
|
||||
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
@@ -332,7 +494,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
const config = yield* configuration.resolve.pipe(
|
||||
Effect.tapError((error) =>
|
||||
logBackendManagerError("failed to generate desktop backend configuration", {
|
||||
cause: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.option,
|
||||
@@ -470,22 +632,26 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
yield* desktopWindow.handleBackendReady.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendManagerError("failed to open main window after backend readiness", {
|
||||
message: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
error,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Scope.provide(runScope),
|
||||
Effect.matchEffect({
|
||||
onFailure: (error) => finalizeRun(error.message),
|
||||
onFailure: (error) =>
|
||||
logBackendManagerError(error.message, { error }).pipe(
|
||||
Effect.andThen(finalizeRun(error.message)),
|
||||
),
|
||||
onSuccess: (exit) => finalizeRun(exit.reason),
|
||||
}),
|
||||
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
|
||||
@@ -540,11 +706,17 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerError("desktop backend restart fiber failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopBackendRestartError({
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
cause,
|
||||
});
|
||||
return logBackendManagerError(error.message, { error });
|
||||
}),
|
||||
),
|
||||
parentScope,
|
||||
);
|
||||
@@ -603,4 +775,4 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());
|
||||
export const layer = Layer.effect(DesktopBackendManager, make);
|
||||
@@ -0,0 +1,83 @@
|
||||
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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
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);
|
||||
@@ -0,0 +1,65 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { networkInterfacesMock } = vi.hoisted(() => ({
|
||||
networkInterfacesMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:os", () => ({
|
||||
networkInterfaces: networkInterfacesMock,
|
||||
}));
|
||||
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
|
||||
const TestLayer = DesktopNetworkInterfaces.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
describe("DesktopNetworkInterfaces", () => {
|
||||
beforeEach(() => {
|
||||
networkInterfacesMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("reads network interfaces through the service", () => {
|
||||
const interfaces = {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.10",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
networkInterfacesMock.mockReturnValueOnce(interfaces);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
assert.strictEqual(yield* service.read, interfaces);
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
});
|
||||
|
||||
it.effect("preserves network interface read failures as structured defects", () => {
|
||||
const cause = new Error("network interface probe failed");
|
||||
networkInterfacesMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
const exit = yield* Effect.exit(service.read);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopNetworkInterfaces.DesktopNetworkInterfacesReadError);
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, "Failed to read desktop network interfaces on linux.");
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export interface DesktopNetworkInterfaceInfo {
|
||||
readonly address: string;
|
||||
readonly family: string | number;
|
||||
readonly internal: boolean;
|
||||
readonly netmask?: string;
|
||||
readonly mac?: string;
|
||||
readonly cidr?: string | null;
|
||||
readonly scopeid?: number;
|
||||
}
|
||||
|
||||
export type NetworkInterfaces = Readonly<
|
||||
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
|
||||
>;
|
||||
|
||||
export class DesktopNetworkInterfacesReadError extends Schema.TaggedErrorClass<DesktopNetworkInterfacesReadError>()(
|
||||
"DesktopNetworkInterfacesReadError",
|
||||
{
|
||||
platform: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read desktop network interfaces on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopNetworkInterfaces extends Context.Service<
|
||||
DesktopNetworkInterfaces,
|
||||
{
|
||||
readonly read: Effect.Effect<NetworkInterfaces>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return DesktopNetworkInterfaces.of({
|
||||
read: Effect.try({
|
||||
try: () => NodeOS.networkInterfaces(),
|
||||
catch: (cause) => new DesktopNetworkInterfacesReadError({ platform, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
|
||||
@@ -7,21 +7,18 @@ 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 { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
DesktopEnvironment,
|
||||
layer as makeDesktopEnvironmentLayer,
|
||||
} from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopEnvironment 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 = {};
|
||||
const lanNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {};
|
||||
const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.20",
|
||||
@@ -31,7 +28,7 @@ const lanNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
],
|
||||
};
|
||||
|
||||
const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
tailscale0: [
|
||||
{
|
||||
address: "100.90.1.2",
|
||||
@@ -64,8 +61,15 @@ function mockSpawnerLayer(statusJson = "{}") {
|
||||
);
|
||||
}
|
||||
|
||||
function dieOnSpawnLayer() {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
|
||||
);
|
||||
}
|
||||
|
||||
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
|
||||
return makeDesktopEnvironmentLayer({
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
@@ -84,20 +88,22 @@ function makeEnvironmentLayer(baseDir: string, env: Record<string, string | unde
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly baseDir: string;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
|
||||
}) {
|
||||
const env = { T3CODE_HOME: input.baseDir, ...input.env };
|
||||
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
|
||||
const networkLayer = Layer.succeed(DesktopServerExposure.DesktopNetworkInterfacesService, {
|
||||
const networkLayer = Layer.succeed(DesktopNetworkInterfaces.DesktopNetworkInterfaces, {
|
||||
read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
|
||||
});
|
||||
|
||||
return DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppSettings.layer),
|
||||
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
|
||||
Layer.provideMerge(NodeFileSystem.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(mockSpawnerLayer()),
|
||||
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
|
||||
Layer.provideMerge(networkLayer),
|
||||
Layer.provideMerge(DesktopConfig.layerTest(env)),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
@@ -105,24 +111,36 @@ function makeLayer(input: {
|
||||
}
|
||||
|
||||
const withHarness = <A, E, R>(
|
||||
networkInterfaces: DesktopNetworkInterfaces,
|
||||
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
| R
|
||||
| DesktopEnvironment
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| FileSystem.FileSystem
|
||||
| DesktopServerExposure.DesktopServerExposure
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
>,
|
||||
env: Record<string, string | undefined> = {},
|
||||
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
|
||||
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-server-exposure-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
|
||||
return yield* effect.pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
baseDir,
|
||||
networkInterfaces,
|
||||
env,
|
||||
...(spawnerLayer ? { spawnerLayer } : {}),
|
||||
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopServerExposure", () => {
|
||||
@@ -222,6 +240,67 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves persistence request context and the settings failure chain", () => {
|
||||
const diskFailure = new Error("disk exploded");
|
||||
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: "/tmp/desktop-settings.json",
|
||||
cause: diskFailure,
|
||||
});
|
||||
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setServerExposureMode: () => Effect.fail(settingsFailure),
|
||||
setTailscaleServe: () => Effect.fail(settingsFailure),
|
||||
setUpdateChannel: () => Effect.die("unexpected update channel change"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
|
||||
|
||||
return withHarness(
|
||||
lanNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
|
||||
const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
modeError,
|
||||
DesktopServerExposure.DesktopServerExposureModePersistenceError,
|
||||
);
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
|
||||
assert.equal(modeError.mode, "network-accessible");
|
||||
assert.strictEqual(modeError.cause, settingsFailure);
|
||||
assert.strictEqual(modeError.cause.cause, diskFailure);
|
||||
assert.equal(
|
||||
modeError.message,
|
||||
"Failed to persist desktop server exposure mode network-accessible.",
|
||||
);
|
||||
assert.notInclude(modeError.message, diskFailure.message);
|
||||
|
||||
const tailscaleError = yield* serverExposure
|
||||
.setTailscaleServeEnabled({ enabled: true, port: 8443 })
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
tailscaleError,
|
||||
DesktopServerExposure.DesktopTailscaleServePersistenceError,
|
||||
);
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
|
||||
assert.equal(tailscaleError.enabled, true);
|
||||
assert.equal(tailscaleError.port, 8443);
|
||||
assert.strictEqual(tailscaleError.cause, settingsFailure);
|
||||
assert.strictEqual(tailscaleError.cause.cause, diskFailure);
|
||||
assert.equal(
|
||||
tailscaleError.message,
|
||||
"Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).",
|
||||
);
|
||||
assert.notInclude(tailscaleError.message, diskFailure.message);
|
||||
}),
|
||||
{},
|
||||
undefined,
|
||||
settingsLayer,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("resolves advertised endpoints from the scoped runtime state", () =>
|
||||
withHarness(
|
||||
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
|
||||
@@ -239,6 +318,27 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
// mode stays at default "local-only", tailscaleServeEnabled stays false.
|
||||
|
||||
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
|
||||
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
|
||||
// would have crashed the test if the gate was missing.
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["http://127.0.0.1:4173/"],
|
||||
);
|
||||
}),
|
||||
{},
|
||||
dieOnSpawnLayer(),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses ConfigProvider desktop exposure overrides", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
|
||||
@@ -1,46 +1,35 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/shared/advertisedEndpoint";
|
||||
import type {
|
||||
AdvertisedEndpoint,
|
||||
AdvertisedEndpointProvider,
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
import {
|
||||
DesktopServerExposureModeSchema,
|
||||
type AdvertisedEndpoint,
|
||||
type AdvertisedEndpointProvider,
|
||||
type DesktopServerExposureMode,
|
||||
type DesktopServerExposureState,
|
||||
} from "@t3tools/contracts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as Context from "effect/Context";
|
||||
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 { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
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;
|
||||
@@ -87,7 +76,7 @@ const isHttpsEndpointUrl = (value: string): boolean => {
|
||||
};
|
||||
|
||||
const resolveLanAdvertisedHost = (
|
||||
networkInterfaces: DesktopNetworkInterfaces,
|
||||
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
|
||||
explicitHost: string | undefined,
|
||||
): string | null => {
|
||||
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
|
||||
@@ -112,7 +101,7 @@ const resolveLanAdvertisedHost = (
|
||||
const resolveDesktopServerExposure = (input: {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly advertisedHostOverride?: string;
|
||||
}): ResolvedDesktopServerExposure => {
|
||||
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
||||
@@ -214,34 +203,56 @@ const resolveDesktopCoreAdvertisedEndpoints = (
|
||||
return endpoints;
|
||||
};
|
||||
|
||||
type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
|
||||
|
||||
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
|
||||
export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErrorClass<DesktopServerExposureNoNetworkAddressError>()(
|
||||
"DesktopServerExposureNoNetworkAddressError",
|
||||
)<{
|
||||
readonly port: number;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
port: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `No reachable network address is available for desktop network access on port ${this.port}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopServerExposurePersistenceError extends Data.TaggedError(
|
||||
"DesktopServerExposurePersistenceError",
|
||||
)<{
|
||||
readonly operation: DesktopServerExposurePersistenceOperation;
|
||||
readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to persist desktop ${this.operation} settings.`;
|
||||
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
|
||||
"DesktopServerExposureModePersistenceError",
|
||||
{
|
||||
mode: DesktopServerExposureModeSchema,
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist desktop server exposure mode ${this.mode}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopServerExposureSetModeError =
|
||||
| DesktopServerExposureNoNetworkAddressError
|
||||
| DesktopServerExposurePersistenceError;
|
||||
export class DesktopTailscaleServePersistenceError extends Schema.TaggedErrorClass<DesktopTailscaleServePersistenceError>()(
|
||||
"DesktopTailscaleServePersistenceError",
|
||||
{
|
||||
enabled: Schema.Boolean,
|
||||
port: Schema.NullOr(Schema.Number),
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist desktop Tailscale Serve settings (enabled: ${this.enabled}, port: ${this.port ?? "unchanged"}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopServerExposureError = DesktopServerExposureSetModeError;
|
||||
export const DesktopServerExposureSetModeError = Schema.Union([
|
||||
DesktopServerExposureNoNetworkAddressError,
|
||||
DesktopServerExposureModePersistenceError,
|
||||
]);
|
||||
export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
|
||||
export const isDesktopServerExposureSetModeError = Schema.is(DesktopServerExposureSetModeError);
|
||||
|
||||
export const DesktopServerExposureError = Schema.Union([
|
||||
DesktopServerExposureNoNetworkAddressError,
|
||||
DesktopServerExposureModePersistenceError,
|
||||
DesktopTailscaleServePersistenceError,
|
||||
]);
|
||||
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
|
||||
export const isDesktopServerExposureError = Schema.is(DesktopServerExposureError);
|
||||
|
||||
export interface DesktopServerExposureBackendConfig {
|
||||
readonly port: number;
|
||||
@@ -256,36 +267,25 @@ 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,
|
||||
DesktopServerExposureShape
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopServerExposureState>;
|
||||
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
|
||||
readonly configureFromSettings: (input: {
|
||||
readonly port: number;
|
||||
}) => Effect.Effect<DesktopServerExposureState>;
|
||||
readonly setMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
|
||||
|
||||
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;
|
||||
@@ -307,10 +307,10 @@ interface ResolvedRuntimeState {
|
||||
|
||||
const initialRuntimeState = (): RuntimeState =>
|
||||
runtimeStateFromResolvedExposure({
|
||||
requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
settings: DEFAULT_DESKTOP_SETTINGS,
|
||||
requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
exposure: resolveDesktopServerExposure({
|
||||
mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
port: 0,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
@@ -344,7 +344,7 @@ const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure
|
||||
|
||||
function runtimeStateFromResolvedExposure(input: {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly settings: DesktopSettings;
|
||||
readonly settings: DesktopAppSettings.DesktopSettings;
|
||||
readonly exposure: ResolvedDesktopServerExposure;
|
||||
readonly port: number;
|
||||
}): RuntimeState {
|
||||
@@ -365,9 +365,9 @@ function runtimeStateFromResolvedExposure(input: {
|
||||
|
||||
function resolveRuntimeState(input: {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly settings: DesktopSettings;
|
||||
readonly settings: DesktopAppSettings.DesktopSettings;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly advertisedHostOverride: Option.Option<string>;
|
||||
}): ResolvedRuntimeState {
|
||||
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
|
||||
@@ -404,14 +404,26 @@ const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): bo
|
||||
previous.bindHost !== next.bindHost ||
|
||||
previous.localHttpUrl !== next.localHttpUrl;
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const networkInterfaces = yield* DesktopNetworkInterfacesService;
|
||||
const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const stateRef = yield* Ref.make(initialRuntimeState());
|
||||
|
||||
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
|
||||
// Store Tailscale CLI lives inside Tailscale's sandbox container, so each
|
||||
// spawn re-triggers the "Other apps" TCC prompt.
|
||||
const cachedReadMagicDnsName = yield* Effect.cachedWithTTL(
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
),
|
||||
TAILSCALE_STATUS_CACHE_TTL,
|
||||
);
|
||||
|
||||
const readNetworkInterfaces = networkInterfaces.read;
|
||||
|
||||
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
|
||||
@@ -460,8 +472,8 @@ const make = Effect.gen(function* () {
|
||||
const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopServerExposurePersistenceError({
|
||||
operation: "server-exposure-mode",
|
||||
new DesktopServerExposureModePersistenceError({
|
||||
mode,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -488,8 +500,9 @@ const make = Effect.gen(function* () {
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopServerExposurePersistenceError({
|
||||
operation: "tailscale-serve",
|
||||
new DesktopTailscaleServePersistenceError({
|
||||
enabled: input.enabled,
|
||||
port: input.port ?? null,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -516,11 +529,20 @@ const make = Effect.gen(function* () {
|
||||
exposure: toResolvedExposure(state),
|
||||
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
|
||||
});
|
||||
|
||||
// Don't spawn the Tailscale CLI when the user hasn't opted into any
|
||||
// network exposure. The spawn itself triggers a macOS "Other apps"
|
||||
// TCC prompt on Mac App Store Tailscale builds.
|
||||
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
|
||||
return coreEndpoints;
|
||||
}
|
||||
|
||||
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
|
||||
port: state.port,
|
||||
serveEnabled: state.tailscaleServeEnabled,
|
||||
servePort: state.tailscaleServePort,
|
||||
networkInterfaces: currentNetworkInterfaces,
|
||||
readMagicDnsName: cachedReadMagicDnsName,
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
@@ -539,10 +561,3 @@ 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()),
|
||||
}),
|
||||
);
|
||||
@@ -104,6 +104,25 @@ describe("tailscale endpoint provider", () => {
|
||||
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
|
||||
);
|
||||
|
||||
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
|
||||
Effect.gen(function* () {
|
||||
let readerCalls = 0;
|
||||
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
readMagicDnsName: Effect.sync(() => {
|
||||
readerCalls += 1;
|
||||
return "desktop.tail.ts.net";
|
||||
}),
|
||||
});
|
||||
assert.equal(readerCalls, 1);
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["https://desktop.tail.ts.net/"],
|
||||
);
|
||||
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
|
||||
() =>
|
||||
|
||||
@@ -9,10 +9,10 @@ import {
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
|
||||
import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts";
|
||||
|
||||
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
|
||||
|
||||
@@ -25,7 +25,7 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
|
||||
function resolveTailscaleIpAdvertisedEndpoints(input: {
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: NetworkInterfaces;
|
||||
}): readonly AdvertisedEndpoint[] {
|
||||
const seen = new Set<string>();
|
||||
const endpoints: AdvertisedEndpoint[] = [];
|
||||
@@ -103,8 +103,13 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
readonly port: number;
|
||||
readonly serveEnabled?: boolean;
|
||||
readonly servePort?: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: NetworkInterfaces;
|
||||
readonly statusJson?: string | null;
|
||||
readonly readMagicDnsName?: Effect.Effect<
|
||||
string | null,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
>;
|
||||
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
|
||||
}): Effect.fn.Return<
|
||||
readonly AdvertisedEndpoint[],
|
||||
@@ -112,15 +117,18 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
|
||||
> {
|
||||
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
|
||||
const readDnsName =
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
? yield* readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
)
|
||||
? yield* readDnsName
|
||||
: input.statusJson
|
||||
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
: null;
|
||||
const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({
|
||||
|
||||
@@ -7,12 +7,15 @@ const {
|
||||
exitMock,
|
||||
getAppPathMock,
|
||||
getVersionMock,
|
||||
isDefaultProtocolClientMock,
|
||||
onMock,
|
||||
quitMock,
|
||||
relaunchMock,
|
||||
removeListenerMock,
|
||||
requestSingleInstanceLockMock,
|
||||
setAboutPanelOptionsMock,
|
||||
setAppUserModelIdMock,
|
||||
setAsDefaultProtocolClientMock,
|
||||
setDesktopNameMock,
|
||||
setDockIconMock,
|
||||
setNameMock,
|
||||
@@ -23,12 +26,15 @@ const {
|
||||
exitMock: vi.fn(),
|
||||
getAppPathMock: vi.fn(() => "/app"),
|
||||
getVersionMock: vi.fn(() => "1.2.3"),
|
||||
isDefaultProtocolClientMock: vi.fn(() => false),
|
||||
onMock: vi.fn(),
|
||||
quitMock: vi.fn(),
|
||||
relaunchMock: vi.fn(),
|
||||
removeListenerMock: vi.fn(),
|
||||
requestSingleInstanceLockMock: vi.fn(() => true),
|
||||
setAboutPanelOptionsMock: vi.fn(),
|
||||
setAppUserModelIdMock: vi.fn(),
|
||||
setAsDefaultProtocolClientMock: vi.fn(() => true),
|
||||
setDesktopNameMock: vi.fn(),
|
||||
setDockIconMock: vi.fn(),
|
||||
setNameMock: vi.fn(),
|
||||
@@ -46,14 +52,17 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
getAppPath: getAppPathMock,
|
||||
getVersion: getVersionMock,
|
||||
isDefaultProtocolClient: isDefaultProtocolClientMock,
|
||||
isPackaged: true,
|
||||
name: "T3 Code",
|
||||
on: onMock,
|
||||
quit: quitMock,
|
||||
relaunch: relaunchMock,
|
||||
removeListener: removeListenerMock,
|
||||
requestSingleInstanceLock: requestSingleInstanceLockMock,
|
||||
runningUnderARM64Translation: false,
|
||||
setAboutPanelOptions: setAboutPanelOptionsMock,
|
||||
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
|
||||
setAppUserModelId: setAppUserModelIdMock,
|
||||
setDesktopName: setDesktopNameMock,
|
||||
setName: setNameMock,
|
||||
@@ -91,6 +100,44 @@ describe("ElectronApp", () => {
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports which app metadata property failed", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("version unavailable");
|
||||
getVersionMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const error = yield* electronApp.metadata.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronApp.ElectronAppMetadataReadError);
|
||||
assert.strictEqual(error.property, "app-version");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
'Failed to read Electron app metadata property "app-version".',
|
||||
);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves Electron readiness failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("ready failed");
|
||||
whenReadyMock.mockRejectedValueOnce(cause);
|
||||
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const error = yield* electronApp.whenReady.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronApp.ElectronAppWhenReadyError);
|
||||
assert.strictEqual(error.isPackaged, true);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Failed to wait for the Electron app to become ready (packaged: true).",
|
||||
);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("scopes app event listeners", () =>
|
||||
Effect.gen(function* () {
|
||||
const listener = vi.fn();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
@@ -13,34 +14,64 @@ export interface ElectronAppMetadata {
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
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 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 ElectronAppMetadataReadError extends Schema.TaggedErrorClass<ElectronAppMetadataReadError>()(
|
||||
"ElectronAppMetadataReadError",
|
||||
{
|
||||
property: Schema.Literals(["app-version", "app-path"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read Electron app metadata property "${this.property}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
|
||||
"@t3tools/desktop/electron/ElectronApp",
|
||||
) {}
|
||||
export class ElectronAppWhenReadyError extends Schema.TaggedErrorClass<ElectronAppWhenReadyError>()(
|
||||
"ElectronAppWhenReadyError",
|
||||
{
|
||||
isPackaged: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to wait for the Electron app to become ready (packaged: ${this.isPackaged}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<
|
||||
ElectronApp,
|
||||
{
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
|
||||
readonly name: Effect.Effect<string>;
|
||||
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
|
||||
readonly quit: Effect.Effect<void>;
|
||||
readonly exit: (code: number) => Effect.Effect<void>;
|
||||
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
|
||||
readonly setPath: (
|
||||
name: Parameters<Electron.App["setPath"]>[0],
|
||||
path: string,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setName: (name: string) => Effect.Effect<void>;
|
||||
readonly setAboutPanelOptions: (
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
path?: string,
|
||||
args?: readonly string[],
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
|
||||
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
|
||||
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronApp") {}
|
||||
|
||||
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
@@ -56,16 +87,41 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const make = ElectronApp.of({
|
||||
metadata: Effect.sync(() => ({
|
||||
appVersion: Electron.app.getVersion(),
|
||||
appPath: Electron.app.getAppPath(),
|
||||
isPackaged: Electron.app.isPackaged,
|
||||
resourcesPath: process.resourcesPath,
|
||||
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
|
||||
})),
|
||||
export const make = ElectronApp.of({
|
||||
metadata: Effect.gen(function* () {
|
||||
const appVersion = yield* Effect.try({
|
||||
try: () => Electron.app.getVersion(),
|
||||
catch: (cause) =>
|
||||
new ElectronAppMetadataReadError({
|
||||
property: "app-version",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const appPath = yield* Effect.try({
|
||||
try: () => Electron.app.getAppPath(),
|
||||
catch: (cause) =>
|
||||
new ElectronAppMetadataReadError({
|
||||
property: "app-path",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
appVersion,
|
||||
appPath,
|
||||
isPackaged: Electron.app.isPackaged,
|
||||
resourcesPath: process.resourcesPath,
|
||||
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
|
||||
};
|
||||
}),
|
||||
name: Effect.sync(() => Electron.app.name),
|
||||
whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
|
||||
whenReady: Effect.gen(function* () {
|
||||
const isPackaged = Electron.app.isPackaged;
|
||||
yield* Effect.tryPromise({
|
||||
try: () => Electron.app.whenReady(),
|
||||
catch: (cause) => new ElectronAppWhenReadyError({ isPackaged, cause }),
|
||||
});
|
||||
}),
|
||||
quit: Effect.sync(() => {
|
||||
Electron.app.quit();
|
||||
}),
|
||||
@@ -93,6 +149,16 @@ const make = ElectronApp.of({
|
||||
Effect.sync(() => {
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
Effect.sync(() => {
|
||||
if (path === undefined) {
|
||||
return Electron.app.setAsDefaultProtocolClient(protocol);
|
||||
}
|
||||
return Electron.app.setAsDefaultProtocolClient(protocol, path, [...(args ?? [])]);
|
||||
}),
|
||||
setDesktopName: (desktopName) =>
|
||||
Effect.sync(() => {
|
||||
const linuxApp = Electron.app as Electron.App & {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import type { BrowserWindow } from "electron";
|
||||
@@ -90,4 +91,116 @@ describe("ElectronDialog", () => {
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves folder picker request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("folder picker failed");
|
||||
const owner = { id: 7 } as BrowserWindow;
|
||||
showOpenDialogMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.pickFolder({
|
||||
owner: Option.some(owner),
|
||||
defaultPath: Option.some("/workspace"),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError);
|
||||
assert.isTrue(ElectronDialog.isElectronDialogError(error));
|
||||
assert.strictEqual(error.ownerWindowId, 7);
|
||||
assert.strictEqual(error.defaultPath, "/workspace");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 7");
|
||||
assert.include(error.message, "/workspace");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves confirmation request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("confirmation failed");
|
||||
const owner = { id: 9 } as BrowserWindow;
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.confirm({
|
||||
owner: Option.some(owner),
|
||||
message: " Confirm removal? ",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
|
||||
assert.strictEqual(error.ownerWindowId, 9);
|
||||
assert.strictEqual(error.promptLength, "Confirm removal?".length);
|
||||
assert.notProperty(error, "promptMessage");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 9");
|
||||
assert.notInclude(error.message, "Confirm removal?");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message box request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("message box failed");
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.showMessageBox({
|
||||
type: "warning",
|
||||
title: "Unsaved changes",
|
||||
message: "Discard changes?",
|
||||
detail: "This cannot be undone.",
|
||||
buttons: ["Cancel", "Discard"],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogShowMessageBoxError);
|
||||
assert.strictEqual(error.type, "warning");
|
||||
assert.strictEqual(error.titleLength, "Unsaved changes".length);
|
||||
assert.strictEqual(error.messageLength, "Discard changes?".length);
|
||||
assert.strictEqual(error.detailLength, "This cannot be undone.".length);
|
||||
assert.strictEqual(error.buttonCount, 2);
|
||||
assert.notProperty(error, "title");
|
||||
assert.notProperty(error, "dialogMessage");
|
||||
assert.notProperty(error, "dialogDetail");
|
||||
assert.notProperty(error, "buttons");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "warning");
|
||||
assert.notInclude(error.message, "Unsaved changes");
|
||||
assert.notInclude(error.message, "Discard changes?");
|
||||
assert.notInclude(error.message, "This cannot be undone.");
|
||||
assert.notInclude(error.message, "Cancel");
|
||||
assert.notInclude(error.message, "Discard");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves error box request context and cause in the defect", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("error box failed");
|
||||
showErrorBoxMock.mockImplementation(() => {
|
||||
throw cause;
|
||||
});
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const exit = yield* Effect.exit(dialog.showErrorBox("Startup failed", "Could not start."));
|
||||
|
||||
assert.isTrue(exit._tag === "Failure");
|
||||
if (exit._tag === "Success") return;
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogShowErrorBoxError);
|
||||
assert.strictEqual(error.titleLength, "Startup failed".length);
|
||||
assert.strictEqual(error.contentLength, "Could not start.".length);
|
||||
assert.notProperty(error, "title");
|
||||
assert.notProperty(error, "content");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, "Startup failed");
|
||||
assert.notInclude(error.message, "Could not start.");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
});
|
||||
@@ -2,11 +2,80 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
|
||||
"ElectronDialogPickFolderError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
defaultPath: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
|
||||
return `Failed to open the Electron folder picker for ${owner} with ${defaultPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
promptLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
|
||||
"ElectronDialogShowMessageBoxError",
|
||||
{
|
||||
type: Schema.NullOr(Schema.Literals(["none", "info", "error", "question", "warning"])),
|
||||
titleLength: Schema.NullOr(Schema.Number),
|
||||
messageLength: Schema.Number,
|
||||
detailLength: Schema.NullOr(Schema.Number),
|
||||
buttonCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const type = this.type === null ? "untyped" : this.type;
|
||||
return `Failed to show the Electron ${type} message box with ${this.buttonCount} buttons.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<ElectronDialogShowErrorBoxError>()(
|
||||
"ElectronDialogShowErrorBoxError",
|
||||
{
|
||||
titleLength: Schema.Number,
|
||||
contentLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to show the Electron error box with a ${this.titleLength}-character title and ${this.contentLength}-character content.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
export type ElectronDialogError = typeof ElectronDialogError.Type;
|
||||
export const isElectronDialogError = Schema.is(ElectronDialogError);
|
||||
|
||||
export interface ElectronDialogPickFolderInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
@@ -17,23 +86,29 @@ export interface ElectronDialogConfirmInput {
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
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 class ElectronDialog extends Context.Service<
|
||||
ElectronDialog,
|
||||
{
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
|
||||
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronDialog") {}
|
||||
|
||||
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
|
||||
"@t3tools/desktop/electron/ElectronDialog",
|
||||
) {}
|
||||
|
||||
const make = ElectronDialog.of({
|
||||
export const make = ElectronDialog.of({
|
||||
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const defaultPath = Option.getOrNull(input.defaultPath);
|
||||
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
|
||||
onNone: () => ({
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
@@ -43,10 +118,18 @@ const make = ElectronDialog.of({
|
||||
defaultPath,
|
||||
}),
|
||||
});
|
||||
const result = yield* Option.match(input.owner, {
|
||||
onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
|
||||
onSome: (owner) =>
|
||||
Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
|
||||
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogPickFolderError({
|
||||
ownerWindowId,
|
||||
defaultPath,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
if (result.canceled) {
|
||||
@@ -68,17 +151,48 @@ const make = ElectronDialog.of({
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
};
|
||||
const result = yield* Option.match(input.owner, {
|
||||
onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
|
||||
onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showMessageBox(options),
|
||||
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogConfirmError({
|
||||
ownerWindowId,
|
||||
promptLength: normalizedMessage.length,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.response === CONFIRM_BUTTON_INDEX;
|
||||
}),
|
||||
showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
|
||||
showErrorBox: (title, content) =>
|
||||
Effect.sync(() => {
|
||||
Electron.dialog.showErrorBox(title, content);
|
||||
showMessageBox: (options) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.dialog.showMessageBox(options),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogShowMessageBoxError({
|
||||
type: options.type ?? null,
|
||||
titleLength: options.title?.length ?? null,
|
||||
messageLength: options.message.length,
|
||||
detailLength: options.detail?.length ?? null,
|
||||
buttonCount: options.buttons?.length ?? 0,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
showErrorBox: (title, content) =>
|
||||
Effect.try({
|
||||
try: () => Electron.dialog.showErrorBox(title, content),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogShowErrorBoxError({
|
||||
titleLength: title.length,
|
||||
contentLength: content.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronDialog, make);
|
||||
@@ -1,5 +1,8 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
@@ -24,6 +27,10 @@ vi.mock("electron", () => ({
|
||||
|
||||
import * as ElectronMenu from "./ElectronMenu.ts";
|
||||
|
||||
const TestLayer = ElectronMenu.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
describe("ElectronMenu", () => {
|
||||
beforeEach(() => {
|
||||
buildFromTemplateMock.mockReset();
|
||||
@@ -42,7 +49,7 @@ describe("ElectronMenu", () => {
|
||||
|
||||
assert.isTrue(Option.isNone(selectedItemId));
|
||||
assert.equal(buildFromTemplateMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronMenu.layer)),
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("resolves with the clicked leaf item id", () =>
|
||||
@@ -69,7 +76,7 @@ describe("ElectronMenu", () => {
|
||||
});
|
||||
|
||||
assert.equal(Option.getOrNull(selectedItemId), "copy");
|
||||
}).pipe(Effect.provide(ElectronMenu.layer)),
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("resolves with none when the menu closes without a click", () =>
|
||||
@@ -93,7 +100,7 @@ describe("ElectronMenu", () => {
|
||||
enabled: true,
|
||||
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
|
||||
});
|
||||
}).pipe(Effect.provide(ElectronMenu.layer)),
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("defers popupTemplate side effects until the returned Effect runs", () =>
|
||||
@@ -114,6 +121,89 @@ describe("ElectronMenu", () => {
|
||||
|
||||
assert.equal(buildFromTemplateMock.mock.calls.length, 1);
|
||||
assert.equal(popupMock.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(ElectronMenu.layer)),
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves application-menu failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("application menu build failed");
|
||||
buildFromTemplateMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const exit = yield* Effect.exit(
|
||||
electronMenu.setApplicationMenu([{ label: "File" }, { label: "Edit" }]),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
|
||||
assert.equal(error.operation, "set-application-menu");
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.isNull(error.windowId);
|
||||
assert.equal(error.itemCount, 2);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves popup-template failures with window context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("popup failed");
|
||||
buildFromTemplateMock.mockReturnValueOnce({
|
||||
popup: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const exit = yield* Effect.exit(
|
||||
electronMenu.popupTemplate({
|
||||
window: { id: 41 } as Electron.BrowserWindow,
|
||||
template: [{ label: "Copy" }],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
|
||||
assert.equal(error.operation, "popup-template");
|
||||
assert.equal(error.windowId, 41);
|
||||
assert.equal(error.itemCount, 1);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves context-menu failures with normalized item context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("context menu build failed");
|
||||
buildFromTemplateMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const exit = yield* Effect.exit(
|
||||
electronMenu.showContextMenu({
|
||||
window: { id: 42 } as Electron.BrowserWindow,
|
||||
items: [{ id: "copy", label: "Copy" }],
|
||||
position: Option.none(),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
|
||||
assert.equal(error.operation, "show-context-menu");
|
||||
assert.equal(error.windowId, 42);
|
||||
assert.equal(error.itemCount, 1);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
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 Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
@@ -22,19 +24,40 @@ export interface ElectronMenuTemplateInput {
|
||||
readonly template: readonly Electron.MenuItemConstructorOptions[];
|
||||
}
|
||||
|
||||
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>;
|
||||
const ElectronMenuOperation = Schema.Literals([
|
||||
"set-application-menu",
|
||||
"popup-template",
|
||||
"show-context-menu",
|
||||
]);
|
||||
|
||||
export class ElectronMenuOperationError extends Schema.TaggedErrorClass<ElectronMenuOperationError>()(
|
||||
"ElectronMenuOperationError",
|
||||
{
|
||||
operation: ElectronMenuOperation,
|
||||
platform: Schema.String,
|
||||
windowId: Schema.NullOr(Schema.Number),
|
||||
itemCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
|
||||
return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
|
||||
"@t3tools/desktop/electron/ElectronMenu",
|
||||
) {}
|
||||
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") {}
|
||||
|
||||
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
|
||||
const normalizedItems: ContextMenuItem[] = [];
|
||||
@@ -44,6 +67,12 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
|
||||
continue;
|
||||
}
|
||||
|
||||
// Header items are decorative section labels for the web fallback only —
|
||||
// Electron's native menu has no equivalent affordance, so we skip them.
|
||||
if (sourceItem.header === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedItem: ContextMenuItem = {
|
||||
id: sourceItem.id,
|
||||
label: sourceItem.label,
|
||||
@@ -73,11 +102,12 @@ 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 layer = Layer.sync(ElectronMenu, () => {
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (process.platform !== "darwin") {
|
||||
if (platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
@@ -89,6 +119,7 @@ export const layer = Layer.sync(ElectronMenu, () => {
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
icon.setTemplateImage(true);
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
@@ -134,16 +165,36 @@ export const layer = Layer.sync(ElectronMenu, () => {
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
Effect.try({
|
||||
try: () => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ElectronMenuOperationError({
|
||||
operation: "set-application-menu",
|
||||
platform,
|
||||
windowId: null,
|
||||
itemCount: template.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
input.template.length === 0
|
||||
? Effect.void
|
||||
: Effect.try({
|
||||
try: () =>
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({
|
||||
window: input.window,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronMenuOperationError({
|
||||
operation: "popup-template",
|
||||
platform,
|
||||
windowId: input.window.id,
|
||||
itemCount: input.template.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
@@ -161,21 +212,41 @@ export const layer = Layer.sync(ElectronMenu, () => {
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
try {
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
} catch (cause) {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(
|
||||
Effect.die(
|
||||
new ElectronMenuOperationError({
|
||||
operation: "show-context-menu",
|
||||
platform,
|
||||
windowId: input.window.id,
|
||||
itemCount: normalizedItems.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ElectronMenu, make);
|
||||
@@ -1,105 +1,187 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
|
||||
vi.hoisted(() => ({
|
||||
registerFileProtocolMock: vi.fn(),
|
||||
registerSchemesAsPrivilegedMock: vi.fn(),
|
||||
unregisterProtocolMock: vi.fn(),
|
||||
}));
|
||||
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
|
||||
handleMock: vi.fn(),
|
||||
netFetchMock: vi.fn(),
|
||||
unhandleMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
protocol: {
|
||||
registerFileProtocol: registerFileProtocolMock,
|
||||
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
|
||||
unregisterProtocol: unregisterProtocolMock,
|
||||
},
|
||||
net: { fetch: netFetchMock },
|
||||
protocol: { handle: handleMock, unhandle: unhandleMock },
|
||||
}));
|
||||
|
||||
import * as ElectronProtocol from "./ElectronProtocol.ts";
|
||||
|
||||
describe("ElectronProtocol", () => {
|
||||
beforeEach(() => {
|
||||
registerFileProtocolMock.mockReset();
|
||||
registerSchemesAsPrivilegedMock.mockReset();
|
||||
unregisterProtocolMock.mockReset();
|
||||
handleMock.mockReset();
|
||||
netFetchMock.mockReset();
|
||||
unhandleMock.mockReset();
|
||||
});
|
||||
|
||||
it("normalizes safe desktop protocol pathnames", () => {
|
||||
assert.equal(
|
||||
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
|
||||
"settings/general",
|
||||
);
|
||||
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
|
||||
});
|
||||
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.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,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
]);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
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("scopes registered file protocols", () =>
|
||||
it.effect("rejects custom protocol requests for another host", () =>
|
||||
Effect.gen(function* () {
|
||||
let capturedHandler:
|
||||
| ((
|
||||
request: Electron.ProtocolRequest,
|
||||
callback: (response: Electron.ProtocolResponse) => void,
|
||||
) => void)
|
||||
| undefined;
|
||||
|
||||
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
|
||||
capturedHandler = handler;
|
||||
return true;
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
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)),
|
||||
);
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(response, { path: "/app/index.html" });
|
||||
assert.deepEqual(
|
||||
registerFileProtocolMock.mock.calls.map((call) => call[0]),
|
||||
["t3"],
|
||||
);
|
||||
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
|
||||
assert.equal(response.status, 404);
|
||||
assert.equal(netFetchMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
handleMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const error = yield* Effect.scoped(
|
||||
protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3774/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronProtocol.ElectronProtocolRegistrationError);
|
||||
assert.equal(error.scheme, "t3code-dev");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to register Electron protocol scheme "t3code-dev".');
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol unregistration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol unregistration failed");
|
||||
unhandleMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const exit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
protocol.registerDesktopProtocol({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronProtocol.ElectronProtocolUnregistrationError);
|
||||
assert.equal(error.scheme, "t3code");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to unregister Electron protocol scheme "t3code".');
|
||||
}
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
|
||||
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
|
||||
scheme: "t3code",
|
||||
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:"]);
|
||||
});
|
||||
});
|
||||
@@ -1,272 +1,163 @@
|
||||
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";
|
||||
|
||||
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
|
||||
export const DESKTOP_HOST = "app";
|
||||
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
|
||||
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
|
||||
|
||||
export const DESKTOP_SCHEME = "t3";
|
||||
export function getDesktopScheme(isDevelopment: boolean): string {
|
||||
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
|
||||
}
|
||||
|
||||
export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
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>()(
|
||||
"ElectronProtocolRegistrationError",
|
||||
)<{
|
||||
readonly scheme: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to register ${this.scheme}: file protocol.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
|
||||
"ElectronProtocolStaticBundleMissingError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
|
||||
}
|
||||
}
|
||||
|
||||
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"),
|
||||
];
|
||||
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 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");
|
||||
{
|
||||
scheme: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
);
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return environment.path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to register Electron protocol scheme "${this.scheme}".`;
|
||||
}
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
export class ElectronProtocolUnregistrationError extends Schema.TaggedErrorClass<ElectronProtocolUnregistrationError>()(
|
||||
"ElectronProtocolUnregistrationError",
|
||||
{
|
||||
scheme: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
export interface DesktopProtocolRegistrationInput {
|
||||
readonly scheme: string;
|
||||
readonly targetOrigin: URL;
|
||||
readonly backendOrigin: URL;
|
||||
readonly clerkFrontendApiHostname: string | undefined;
|
||||
}
|
||||
|
||||
const context = yield* Effect.context<R>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
export class ElectronProtocol extends Context.Service<
|
||||
ElectronProtocol,
|
||||
{
|
||||
readonly registerDesktopProtocol: (
|
||||
input: DesktopProtocolRegistrationInput,
|
||||
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
|
||||
}
|
||||
>()("@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",
|
||||
];
|
||||
|
||||
// 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 });
|
||||
}
|
||||
|
||||
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 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 registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
|
||||
function* (input: DesktopProtocolRegistrationInput) {
|
||||
if (yield* Ref.get(registered)) return;
|
||||
|
||||
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => {
|
||||
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 }));
|
||||
},
|
||||
Electron.protocol.handle(input.scheme, (request) =>
|
||||
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
|
||||
);
|
||||
if (!registered) {
|
||||
throw new ElectronProtocolRegistrationError({
|
||||
scheme,
|
||||
cause: "registerFileProtocol returned false",
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof ElectronProtocolRegistrationError
|
||||
? cause
|
||||
: new ElectronProtocolRegistrationError({ scheme, cause }),
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
|
||||
),
|
||||
),
|
||||
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, true))),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.protocol.unregisterProtocol(scheme);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => {
|
||||
const next = new Set(protocols);
|
||||
next.delete(scheme);
|
||||
return next;
|
||||
Effect.try({
|
||||
try: () => Electron.protocol.unhandle(input.scheme),
|
||||
catch: (cause) =>
|
||||
new ElectronProtocolUnregistrationError({
|
||||
scheme: input.scheme,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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,
|
||||
});
|
||||
return ElectronProtocol.of({ registerDesktopProtocol });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ElectronProtocol, make);
|
||||
@@ -1,56 +1,69 @@
|
||||
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 Electron from "electron";
|
||||
|
||||
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
|
||||
const electronSafeStorageErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class ElectronSafeStorageAvailabilityError extends Schema.TaggedErrorClass<ElectronSafeStorageAvailabilityError>()(
|
||||
"ElectronSafeStorageAvailabilityError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Electron safe storage failed to check encryption availability.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronSafeStorageEncryptError extends Data.TaggedError(
|
||||
export class ElectronSafeStorageEncryptError extends Schema.TaggedErrorClass<ElectronSafeStorageEncryptError>()(
|
||||
"ElectronSafeStorageEncryptError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Electron safe storage failed to encrypt a string.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronSafeStorageDecryptError extends Data.TaggedError(
|
||||
export class ElectronSafeStorageDecryptError extends Schema.TaggedErrorClass<ElectronSafeStorageDecryptError>()(
|
||||
"ElectronSafeStorageDecryptError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Electron safe storage failed to decrypt a string.";
|
||||
}
|
||||
}
|
||||
|
||||
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 const ElectronSafeStorageError = Schema.Union([
|
||||
ElectronSafeStorageAvailabilityError,
|
||||
ElectronSafeStorageEncryptError,
|
||||
ElectronSafeStorageDecryptError,
|
||||
]);
|
||||
export type ElectronSafeStorageError = typeof ElectronSafeStorageError.Type;
|
||||
export const isElectronSafeStorageError = Schema.is(ElectronSafeStorageError);
|
||||
|
||||
export class ElectronSafeStorage extends Context.Service<
|
||||
ElectronSafeStorage,
|
||||
ElectronSafeStorageShape
|
||||
{
|
||||
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
|
||||
readonly encryptString: (
|
||||
value: string,
|
||||
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
|
||||
|
||||
const make = ElectronSafeStorage.of({
|
||||
export const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
|
||||
@@ -20,16 +20,15 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
}
|
||||
}
|
||||
|
||||
export interface ElectronShellShape {
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
}
|
||||
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 class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
|
||||
"@t3tools/desktop/electron/ElectronShell",
|
||||
) {}
|
||||
|
||||
const make = ElectronShell.of({
|
||||
export const make = ElectronShell.of({
|
||||
openExternal: (rawUrl) =>
|
||||
Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
onNone: () => Effect.succeed(false),
|
||||
|
||||
@@ -8,6 +8,7 @@ const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
|
||||
themeState: {
|
||||
shouldUseDarkColors: true,
|
||||
themeSource: "system",
|
||||
setSourceError: null as unknown,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -17,6 +18,9 @@ vi.mock("electron", () => ({
|
||||
return themeState.shouldUseDarkColors;
|
||||
},
|
||||
set themeSource(value: string) {
|
||||
if (themeState.setSourceError !== null) {
|
||||
throw themeState.setSourceError;
|
||||
}
|
||||
themeState.themeSource = value;
|
||||
},
|
||||
on: onMock,
|
||||
@@ -32,6 +36,7 @@ describe("ElectronTheme", () => {
|
||||
removeListenerMock.mockClear();
|
||||
themeState.shouldUseDarkColors = true;
|
||||
themeState.themeSource = "system";
|
||||
themeState.setSourceError = null;
|
||||
});
|
||||
|
||||
it.effect("scopes native theme update listeners", () =>
|
||||
@@ -49,4 +54,21 @@ describe("ElectronTheme", () => {
|
||||
assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]);
|
||||
}).pipe(Effect.provide(ElectronTheme.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves the requested source and cause when setting the theme fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("theme source failed");
|
||||
themeState.setSourceError = cause;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
|
||||
const error = yield* Effect.flip(electronTheme.setSource("dark"));
|
||||
|
||||
assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError);
|
||||
assert.isTrue(ElectronTheme.isElectronThemeSetSourceError(error));
|
||||
assert.strictEqual(error.source, "dark");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "dark");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronTheme.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,27 +1,43 @@
|
||||
import type { DesktopTheme } from "@t3tools/contracts";
|
||||
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export 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 class ElectronThemeSetSourceError extends Schema.TaggedErrorClass<ElectronThemeSetSourceError>()(
|
||||
"ElectronThemeSetSourceError",
|
||||
{
|
||||
source: DesktopThemeSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to set the Electron theme source to ${this.source}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
|
||||
"@t3tools/desktop/electron/ElectronTheme",
|
||||
) {}
|
||||
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
|
||||
|
||||
const make = ElectronTheme.of({
|
||||
export class ElectronTheme extends Context.Service<
|
||||
ElectronTheme,
|
||||
{
|
||||
readonly shouldUseDarkColors: Effect.Effect<boolean>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
|
||||
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronTheme") {}
|
||||
|
||||
export const make = ElectronTheme.of({
|
||||
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
|
||||
setSource: (theme) =>
|
||||
Effect.suspend(() => {
|
||||
Electron.nativeTheme.themeSource = theme;
|
||||
return Effect.void;
|
||||
Effect.try({
|
||||
try: () => {
|
||||
Electron.nativeTheme.themeSource = theme;
|
||||
},
|
||||
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
|
||||
}),
|
||||
onUpdated: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
@@ -65,15 +64,65 @@ describe("ElectronUpdater", () => {
|
||||
const cause = new Error("network unavailable");
|
||||
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "beta";
|
||||
|
||||
const exit = yield* Effect.exit(updater.checkForUpdates);
|
||||
const error = yield* updater.checkForUpdates.pipe(Effect.flip);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
|
||||
assert.equal(error.cause, cause);
|
||||
}
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "beta");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, "Electron updater failed to check for updates on channel beta.");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves the execution-time channel on download failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("download unavailable");
|
||||
autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => Promise.reject(cause));
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "nightly";
|
||||
|
||||
const error = yield* updater.downloadUpdate.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "nightly");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Electron updater failed to download the update on channel nightly.",
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("quit and install failed");
|
||||
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "alpha";
|
||||
|
||||
const error = yield* updater
|
||||
.quitAndInstall({ isSilent: true, isForceRunAfter: false })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "alpha");
|
||||
assert.equal(error.isSilent, true);
|
||||
assert.equal(error.isForceRunAfter, false);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Electron updater failed to quit and install the update on channel alpha (silent: true, force run after: false).",
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
});
|
||||
@@ -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,67 +10,77 @@ type AutoUpdater = typeof autoUpdater;
|
||||
|
||||
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
|
||||
|
||||
export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
|
||||
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
|
||||
"ElectronUpdaterCheckForUpdatesError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to check for updates.";
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
|
||||
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
|
||||
"ElectronUpdaterDownloadUpdateError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to download the update.";
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
|
||||
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
|
||||
"ElectronUpdaterQuitAndInstallError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to quit and install the update.";
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
isSilent: Schema.Boolean,
|
||||
isForceRunAfter: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ElectronUpdaterError =
|
||||
| ElectronUpdaterCheckForUpdatesError
|
||||
| ElectronUpdaterDownloadUpdateError
|
||||
| ElectronUpdaterQuitAndInstallError;
|
||||
export const ElectronUpdaterError = Schema.Union([
|
||||
ElectronUpdaterCheckForUpdatesError,
|
||||
ElectronUpdaterDownloadUpdateError,
|
||||
ElectronUpdaterQuitAndInstallError,
|
||||
]);
|
||||
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
|
||||
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
|
||||
|
||||
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 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 class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
|
||||
"@t3tools/desktop/electron/ElectronUpdater",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.succeed(ElectronUpdater, {
|
||||
export const make = ElectronUpdater.of({
|
||||
setFeedURL: (options) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.setFeedURL(options);
|
||||
@@ -107,18 +117,33 @@ export const layer = Layer.succeed(ElectronUpdater, {
|
||||
autoUpdater.disableDifferentialDownload = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
checkForUpdates: Effect.tryPromise({
|
||||
try: () => autoUpdater.checkForUpdates(),
|
||||
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ cause }),
|
||||
}).pipe(Effect.asVoid),
|
||||
downloadUpdate: Effect.tryPromise({
|
||||
try: () => autoUpdater.downloadUpdate(),
|
||||
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ cause }),
|
||||
}).pipe(Effect.asVoid),
|
||||
checkForUpdates: Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.tryPromise({
|
||||
try: () => autoUpdater.checkForUpdates(),
|
||||
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ channel, cause }),
|
||||
}).pipe(Effect.asVoid);
|
||||
}),
|
||||
downloadUpdate: Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.tryPromise({
|
||||
try: () => autoUpdater.downloadUpdate(),
|
||||
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
|
||||
}).pipe(Effect.asVoid);
|
||||
}),
|
||||
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
|
||||
Effect.try({
|
||||
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
|
||||
catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
|
||||
Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.try({
|
||||
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
|
||||
catch: (cause) =>
|
||||
new ElectronUpdaterQuitAndInstallError({
|
||||
channel,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}),
|
||||
on: (eventName, listener) => {
|
||||
const eventTarget = autoUpdater as unknown as {
|
||||
@@ -136,4 +161,6 @@ export const layer = Layer.succeed(ElectronUpdater, {
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
},
|
||||
} satisfies ElectronUpdaterShape);
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronUpdater, make);
|
||||
@@ -1,26 +1,39 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
|
||||
appFocusMock: vi.fn(),
|
||||
getAllWindowsMock: vi.fn(),
|
||||
}));
|
||||
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
|
||||
() => ({
|
||||
appFocusMock: vi.fn(),
|
||||
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
|
||||
getAllWindowsMock: vi.fn(),
|
||||
getFocusedWindowMock: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
focus: appFocusMock,
|
||||
},
|
||||
BrowserWindow: {
|
||||
BrowserWindow: Object.assign(browserWindowMock, {
|
||||
getAllWindows: getAllWindowsMock,
|
||||
},
|
||||
getFocusedWindow: getFocusedWindowMock,
|
||||
}),
|
||||
}));
|
||||
|
||||
import * as ElectronWindow from "./ElectronWindow.ts";
|
||||
|
||||
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
|
||||
const TestLayer = ElectronWindow.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
|
||||
return {
|
||||
id: input.id,
|
||||
isDestroyed: vi.fn(() => input.destroyed),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
}
|
||||
@@ -28,13 +41,78 @@ function makeBrowserWindow(input: { readonly destroyed: boolean }) {
|
||||
describe("ElectronWindow", () => {
|
||||
beforeEach(() => {
|
||||
appFocusMock.mockReset();
|
||||
browserWindowMock.mockReset();
|
||||
getAllWindowsMock.mockReset();
|
||||
getFocusedWindowMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("preserves schema-safe creation context and the Electron cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("native BrowserWindow construction failed");
|
||||
browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() {
|
||||
throw cause;
|
||||
});
|
||||
const options = {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
modal: false,
|
||||
frame: true,
|
||||
transparent: false,
|
||||
backgroundColor: "#101010",
|
||||
icon: {} as Electron.NativeImage,
|
||||
webPreferences: {
|
||||
preload: "/tmp/preload.js",
|
||||
partition: "persist:t3code-preview-test",
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webviewTag: true,
|
||||
spellcheck: true,
|
||||
},
|
||||
} satisfies Electron.BrowserWindowConstructorOptions;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
|
||||
const error = yield* electronWindow.create(options).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
|
||||
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
|
||||
assert.deepEqual(error.options, {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
modal: false,
|
||||
frame: true,
|
||||
transparent: false,
|
||||
backgroundColor: "#101010",
|
||||
webPreferences: {
|
||||
preload: "/tmp/preload.js",
|
||||
partition: "persist:t3code-preview-test",
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webviewTag: true,
|
||||
},
|
||||
});
|
||||
assert.isFalse("icon" in error.options);
|
||||
assert.isFalse("spellcheck" in error.options.webPreferences);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).');
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.deepEqual(browserWindowMock.mock.calls, [[options]]);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("skips windows destroyed before appearance sync runs", () =>
|
||||
Effect.gen(function* () {
|
||||
const liveWindow = makeBrowserWindow({ destroyed: false });
|
||||
const destroyedWindow = makeBrowserWindow({ destroyed: true });
|
||||
const liveWindow = makeBrowserWindow({ id: 1, destroyed: false });
|
||||
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true });
|
||||
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
|
||||
|
||||
const syncedWindows: Electron.BrowserWindow[] = [];
|
||||
@@ -46,6 +124,112 @@ describe("ElectronWindow", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(syncedWindows, [liveWindow]);
|
||||
}).pipe(Effect.provide(ElectronWindow.layer)),
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves window enumeration failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window enumeration failed");
|
||||
getAllWindowsMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.currentMainOrFirst);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "list-windows");
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.isNull(error.windowId);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves reveal failures with the target window", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window restore failed");
|
||||
const window = {
|
||||
id: 41,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => true),
|
||||
restore: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.reveal(window));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "reveal-window");
|
||||
assert.equal(error.windowId, 41);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message delivery failures with window and channel context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("renderer send failed");
|
||||
const window = {
|
||||
id: 42,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
webContents: {
|
||||
send: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
},
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
getAllWindowsMock.mockReturnValueOnce([window]);
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true }));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "send-window-message");
|
||||
assert.equal(error.windowId, 42);
|
||||
assert.equal(error.channel, "desktop:update");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves destroy failures with the target window", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window destroy failed");
|
||||
const window = {
|
||||
id: 43,
|
||||
destroy: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
getAllWindowsMock.mockReturnValueOnce([window]);
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.destroyAll);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "destroy-window");
|
||||
assert.equal(error.windowId, 43);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,47 +1,135 @@
|
||||
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";
|
||||
|
||||
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to create Electron BrowserWindow.";
|
||||
const ElectronWindowCreateOptions = Schema.Struct({
|
||||
title: Schema.NullOr(Schema.String),
|
||||
width: Schema.NullOr(Schema.Number),
|
||||
height: Schema.NullOr(Schema.Number),
|
||||
minWidth: Schema.NullOr(Schema.Number),
|
||||
minHeight: Schema.NullOr(Schema.Number),
|
||||
show: Schema.NullOr(Schema.Boolean),
|
||||
modal: Schema.NullOr(Schema.Boolean),
|
||||
frame: Schema.NullOr(Schema.Boolean),
|
||||
transparent: Schema.NullOr(Schema.Boolean),
|
||||
backgroundColor: Schema.NullOr(Schema.String),
|
||||
webPreferences: Schema.Struct({
|
||||
preload: Schema.NullOr(Schema.String),
|
||||
partition: Schema.NullOr(Schema.String),
|
||||
sandbox: Schema.NullOr(Schema.Boolean),
|
||||
contextIsolation: Schema.NullOr(Schema.Boolean),
|
||||
nodeIntegration: Schema.NullOr(Schema.Boolean),
|
||||
webviewTag: Schema.NullOr(Schema.Boolean),
|
||||
}),
|
||||
});
|
||||
|
||||
const ElectronWindowOperation = Schema.Literals([
|
||||
"list-windows",
|
||||
"get-focused-window",
|
||||
"inspect-window",
|
||||
"reveal-window",
|
||||
"send-window-message",
|
||||
"destroy-window",
|
||||
]);
|
||||
|
||||
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
|
||||
"ElectronWindowCreateError",
|
||||
{
|
||||
options: ElectronWindowCreateOptions,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
|
||||
const dimensions =
|
||||
this.options.width === null || this.options.height === null
|
||||
? ""
|
||||
: ` (${this.options.width}x${this.options.height})`;
|
||||
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export 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 isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
|
||||
|
||||
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
|
||||
"ElectronWindowOperationError",
|
||||
{
|
||||
operation: ElectronWindowOperation,
|
||||
platform: Schema.String,
|
||||
windowId: Schema.NullOr(Schema.Number),
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
|
||||
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
|
||||
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
|
||||
"@t3tools/desktop/electron/ElectronWindow",
|
||||
) {}
|
||||
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") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
Effect.map(Option.filter((value) => !value.isDestroyed())),
|
||||
);
|
||||
const listWindows = Effect.try({
|
||||
try: () => Electron.BrowserWindow.getAllWindows(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "list-windows",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
|
||||
Effect.try({
|
||||
try: () => window.isDestroyed(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "inspect-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const liveMain = Effect.gen(function* () {
|
||||
const main = yield* Ref.get(mainWindowRef);
|
||||
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return main;
|
||||
});
|
||||
|
||||
const currentMainOrFirst = Effect.gen(function* () {
|
||||
const main = yield* liveMain;
|
||||
@@ -49,27 +137,60 @@ const make = Effect.gen(function* () {
|
||||
return main;
|
||||
}
|
||||
|
||||
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
);
|
||||
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
|
||||
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return first;
|
||||
});
|
||||
|
||||
const focusedMainOrFirst = Effect.sync(() =>
|
||||
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
),
|
||||
).pipe(
|
||||
Effect.flatMap((focused) =>
|
||||
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
|
||||
),
|
||||
);
|
||||
const focusedMainOrFirst = Effect.gen(function* () {
|
||||
const focused = yield* Effect.try({
|
||||
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "get-focused-window",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
|
||||
return focused;
|
||||
}
|
||||
return yield* currentMainOrFirst;
|
||||
});
|
||||
|
||||
return ElectronWindow.of({
|
||||
create: (options) =>
|
||||
Effect.try({
|
||||
create: (options) => {
|
||||
const webPreferences = options.webPreferences;
|
||||
const diagnosticOptions = {
|
||||
title: options.title ?? null,
|
||||
width: options.width ?? null,
|
||||
height: options.height ?? null,
|
||||
minWidth: options.minWidth ?? null,
|
||||
minHeight: options.minHeight ?? null,
|
||||
show: options.show ?? null,
|
||||
modal: options.modal ?? null,
|
||||
frame: options.frame ?? null,
|
||||
transparent: options.transparent ?? null,
|
||||
backgroundColor: options.backgroundColor ?? null,
|
||||
webPreferences: {
|
||||
preload: webPreferences?.preload ?? null,
|
||||
partition: webPreferences?.partition ?? null,
|
||||
sandbox: webPreferences?.sandbox ?? null,
|
||||
contextIsolation: webPreferences?.contextIsolation ?? null,
|
||||
nodeIntegration: webPreferences?.nodeIntegration ?? null,
|
||||
webviewTag: webPreferences?.webviewTag ?? null,
|
||||
},
|
||||
} satisfies typeof ElectronWindowCreateOptions.Type;
|
||||
|
||||
return Effect.try({
|
||||
try: () => new Electron.BrowserWindow(options),
|
||||
catch: (cause) => new ElectronWindowCreateError({ cause }),
|
||||
}),
|
||||
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
|
||||
});
|
||||
},
|
||||
main: liveMain,
|
||||
currentMainOrFirst,
|
||||
focusedMainOrFirst,
|
||||
@@ -85,45 +206,75 @@ const make = Effect.gen(function* () {
|
||||
return Option.none();
|
||||
}),
|
||||
reveal: (window) =>
|
||||
Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "reveal-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
continue;
|
||||
}
|
||||
window.webContents.send(channel, ...args);
|
||||
yield* Effect.try({
|
||||
try: () => window.webContents.send(channel, ...args),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
destroyAll: Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
window.destroy();
|
||||
destroyAll: Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
yield* Effect.try({
|
||||
try: () => window.destroy(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "destroy-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) {
|
||||
const windows = Electron.BrowserWindow.getAllWindows();
|
||||
const windows = yield* listWindows;
|
||||
for (const window of windows) {
|
||||
if (window.isDestroyed()) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
continue;
|
||||
}
|
||||
yield* sync(window);
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import * as DesktopIpc from "./DesktopIpc.ts";
|
||||
|
||||
const invokeMethod: DesktopIpc.DesktopIpcMethod<never, never> = {
|
||||
channel: "desktop.test.invoke",
|
||||
handler: () => Effect.void,
|
||||
};
|
||||
|
||||
const syncMethod: DesktopIpc.DesktopSyncIpcMethod<never, never> = {
|
||||
channel: "desktop.test.sync",
|
||||
handler: () => Effect.void,
|
||||
};
|
||||
|
||||
function makeIpcMain(
|
||||
overrides: Partial<DesktopIpc.DesktopIpcMain> = {},
|
||||
): DesktopIpc.DesktopIpcMain {
|
||||
return {
|
||||
removeHandler: vi.fn(),
|
||||
handle: vi.fn(),
|
||||
removeAllListeners: vi.fn(),
|
||||
on: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("DesktopIpc", () => {
|
||||
it.effect("preserves invoke registration context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("invoke registration failed");
|
||||
const ipcMain = makeIpcMain({
|
||||
handle: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
const ipc = DesktopIpc.make(ipcMain);
|
||||
|
||||
const error = yield* Effect.flip(Effect.scoped(ipc.handle(invokeMethod)));
|
||||
|
||||
assert.instanceOf(error, DesktopIpc.DesktopIpcRegistrationError);
|
||||
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
|
||||
assert.strictEqual(error.handlerKind, "invoke");
|
||||
assert.strictEqual(error.channel, invokeMethod.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "invoke");
|
||||
assert.include(error.message, invokeMethod.channel);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves sync unregistration context and cause in the finalizer defect", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("sync unregistration failed");
|
||||
let removeCount = 0;
|
||||
const ipcMain = makeIpcMain({
|
||||
removeAllListeners: () => {
|
||||
removeCount += 1;
|
||||
if (removeCount === 2) throw cause;
|
||||
},
|
||||
});
|
||||
const ipc = DesktopIpc.make(ipcMain);
|
||||
|
||||
const exit = yield* Effect.exit(Effect.scoped(ipc.handleSync(syncMethod)));
|
||||
|
||||
assert.isTrue(exit._tag === "Failure");
|
||||
if (exit._tag === "Success") return;
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopIpc.DesktopIpcUnregistrationError);
|
||||
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
|
||||
assert.strictEqual(error.handlerKind, "sync");
|
||||
assert.strictEqual(error.channel, syncMethod.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
@@ -23,6 +24,39 @@ export interface DesktopIpcMain {
|
||||
on(channel: string, listener: DesktopIpcSyncListener): void;
|
||||
}
|
||||
|
||||
export class DesktopIpcRegistrationError extends Schema.TaggedErrorClass<DesktopIpcRegistrationError>()(
|
||||
"DesktopIpcRegistrationError",
|
||||
{
|
||||
handlerKind: Schema.Literals(["invoke", "sync"]),
|
||||
channel: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to register the ${this.handlerKind} IPC handler for ${this.channel}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopIpcUnregistrationError extends Schema.TaggedErrorClass<DesktopIpcUnregistrationError>()(
|
||||
"DesktopIpcUnregistrationError",
|
||||
{
|
||||
handlerKind: Schema.Literals(["invoke", "sync"]),
|
||||
channel: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to unregister the ${this.handlerKind} IPC handler for ${this.channel}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const DesktopIpcError = Schema.Union([
|
||||
DesktopIpcRegistrationError,
|
||||
DesktopIpcUnregistrationError,
|
||||
]);
|
||||
export type DesktopIpcError = typeof DesktopIpcError.Type;
|
||||
export const isDesktopIpcError = Schema.is(DesktopIpcError);
|
||||
|
||||
export interface DesktopIpcMethod<E, R> {
|
||||
readonly channel: string;
|
||||
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
|
||||
@@ -33,20 +67,19 @@ export interface DesktopSyncIpcMethod<E, R> {
|
||||
readonly handler: () => Effect.Effect<unknown, E, R>;
|
||||
}
|
||||
|
||||
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 class DesktopIpc extends Context.Service<
|
||||
DesktopIpc,
|
||||
{
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/ipc/DesktopIpc") {}
|
||||
|
||||
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
|
||||
"@t3tools/desktop/ipc/DesktopIpc",
|
||||
) {}
|
||||
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
DesktopIpc.of({
|
||||
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
|
||||
channel,
|
||||
@@ -57,18 +90,27 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
ipcMain.removeHandler(channel);
|
||||
ipcMain.handle(channel, (_event, raw) =>
|
||||
runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler(raw);
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
|
||||
),
|
||||
);
|
||||
Effect.try({
|
||||
try: () => {
|
||||
ipcMain.removeHandler(channel);
|
||||
ipcMain.handle(channel, (_event, raw) =>
|
||||
runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler(raw);
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
|
||||
),
|
||||
);
|
||||
},
|
||||
catch: (cause) =>
|
||||
new DesktopIpcRegistrationError({ handlerKind: "invoke", channel, cause }),
|
||||
}),
|
||||
() => Effect.sync(() => ipcMain.removeHandler(channel)),
|
||||
() =>
|
||||
Effect.try({
|
||||
try: () => ipcMain.removeHandler(channel),
|
||||
catch: (cause) =>
|
||||
new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -81,22 +123,36 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
const runSync = Effect.runSyncWith(context);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
ipcMain.removeAllListeners(channel);
|
||||
ipcMain.on(channel, (event) => {
|
||||
event.returnValue = runSync(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler();
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync")),
|
||||
);
|
||||
});
|
||||
Effect.try({
|
||||
try: () => {
|
||||
ipcMain.removeAllListeners(channel);
|
||||
ipcMain.on(channel, (event) => {
|
||||
event.returnValue = runSync(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler();
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ channel }),
|
||||
Effect.withSpan("desktop.ipc.invokeSync"),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
catch: (cause) =>
|
||||
new DesktopIpcRegistrationError({ handlerKind: "sync", channel, cause }),
|
||||
}),
|
||||
() => Effect.sync(() => ipcMain.removeAllListeners(channel)),
|
||||
() =>
|
||||
Effect.try({
|
||||
try: () => ipcMain.removeAllListeners(channel),
|
||||
catch: (cause) =>
|
||||
new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
|
||||
|
||||
/**
|
||||
* Convenience helpers for creating IPC methods
|
||||
*/
|
||||
|
||||
@@ -3,12 +3,10 @@ import * as Effect from "effect/Effect";
|
||||
import * as DesktopIpc from "./DesktopIpc.ts";
|
||||
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
|
||||
import {
|
||||
getSavedEnvironmentRegistry,
|
||||
getSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
setSavedEnvironmentRegistry,
|
||||
setSavedEnvironmentSecret,
|
||||
} from "./methods/savedEnvironments.ts";
|
||||
clearConnectionCatalog,
|
||||
getConnectionCatalog,
|
||||
setConnectionCatalog,
|
||||
} from "./methods/connectionCatalog.ts";
|
||||
import {
|
||||
getAdvertisedEndpoints,
|
||||
getServerExposureState,
|
||||
@@ -35,26 +33,28 @@ import {
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getLocalEnvironmentBootstrap,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
yield* ipc.handle(getClientSettings);
|
||||
yield* ipc.handle(setClientSettings);
|
||||
yield* ipc.handle(getSavedEnvironmentRegistry);
|
||||
yield* ipc.handle(setSavedEnvironmentRegistry);
|
||||
yield* ipc.handle(getSavedEnvironmentSecret);
|
||||
yield* ipc.handle(setSavedEnvironmentSecret);
|
||||
yield* ipc.handle(removeSavedEnvironmentSecret);
|
||||
yield* ipc.handle(getConnectionCatalog);
|
||||
yield* ipc.handle(setConnectionCatalog);
|
||||
yield* ipc.handle(clearConnectionCatalog);
|
||||
|
||||
yield* ipc.handle(discoverSshHosts);
|
||||
yield* ipc.handle(ensureSshEnvironment);
|
||||
@@ -75,10 +75,12 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
|
||||
yield* ipc.handle(getUpdateState);
|
||||
yield* ipc.handle(setUpdateChannel);
|
||||
yield* ipc.handle(downloadUpdate);
|
||||
yield* ipc.handle(installUpdate);
|
||||
yield* ipc.handle(checkForUpdate);
|
||||
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
|
||||
for (const previewMethod of PreviewIpc.methods) {
|
||||
yield* ipc.handle(previewMethod);
|
||||
}
|
||||
});
|
||||
@@ -12,13 +12,13 @@ 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_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
|
||||
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
|
||||
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
|
||||
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
||||
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
@@ -33,3 +33,38 @@ export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mod
|
||||
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
|
||||
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
|
||||
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
|
||||
export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate";
|
||||
export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back";
|
||||
export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward";
|
||||
export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh";
|
||||
export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
|
||||
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
|
||||
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
|
||||
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
|
||||
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
|
||||
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
|
||||
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
|
||||
export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
|
||||
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
|
||||
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
|
||||
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
|
||||
export const PREVIEW_CAPTURE_SCREENSHOT_CHANNEL = "desktop:preview-capture-screenshot";
|
||||
export const PREVIEW_REVEAL_ARTIFACT_CHANNEL = "desktop:preview-reveal-artifact";
|
||||
export const PREVIEW_COPY_ARTIFACT_CHANNEL = "desktop:preview-copy-artifact";
|
||||
export const PREVIEW_AUTOMATION_STATUS_CHANNEL = "desktop:preview-automation-status";
|
||||
export const PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL = "desktop:preview-automation-snapshot";
|
||||
export const PREVIEW_AUTOMATION_CLICK_CHANNEL = "desktop:preview-automation-click";
|
||||
export const PREVIEW_AUTOMATION_TYPE_CHANNEL = "desktop:preview-automation-type";
|
||||
export const PREVIEW_AUTOMATION_PRESS_CHANNEL = "desktop:preview-automation-press";
|
||||
export const PREVIEW_AUTOMATION_SCROLL_CHANNEL = "desktop:preview-automation-scroll";
|
||||
export const PREVIEW_AUTOMATION_EVALUATE_CHANNEL = "desktop:preview-automation-evaluate";
|
||||
export const PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL = "desktop:preview-automation-wait-for";
|
||||
export const PREVIEW_RECORDING_START_CHANNEL = "desktop:preview-recording-start";
|
||||
export const PREVIEW_RECORDING_STOP_CHANNEL = "desktop:preview-recording-stop";
|
||||
export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
|
||||
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
|
||||
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
|
||||
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
|
||||
@@ -5,9 +5,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const getClientSettings = makeIpcMethod({
|
||||
export const getClientSettings = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(ClientSettingsSchema),
|
||||
@@ -17,7 +17,7 @@ export const getClientSettings = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setClientSettings = makeIpcMethod({
|
||||
export const setClientSettings = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
|
||||
payload: ClientSettingsSchema,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
return Option.getOrNull(yield* store.get);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
return yield* store.set(catalog);
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
yield* store.clear;
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import * as PreviewIpc from "./preview.ts";
|
||||
|
||||
const { fromPartition } = vi.hoisted(() => ({
|
||||
fromPartition: vi.fn(() => {
|
||||
throw new Error("Session can only be received when app is ready");
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
BrowserWindow: {
|
||||
getAllWindows: vi.fn(() => []),
|
||||
},
|
||||
session: {
|
||||
fromPartition,
|
||||
},
|
||||
webContents: {
|
||||
fromId: vi.fn(() => null),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("preview IPC methods", () => {
|
||||
beforeEach(() => {
|
||||
fromPartition.mockClear();
|
||||
});
|
||||
|
||||
it("does not access the Electron session while the module loads", async () => {
|
||||
await expect(import("./preview.ts")).resolves.toBeDefined();
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
|
||||
Effect.map(
|
||||
PreviewIpc.registerWebview
|
||||
.handler({ tabId: "tab-1", webContentsId: 0 })
|
||||
.pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit),
|
||||
(exit) => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Cause.findErrorOption(exit.cause);
|
||||
expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true);
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,370 @@
|
||||
import {
|
||||
DesktopPreviewAnnotationThemeInputSchema,
|
||||
DesktopPreviewArtifactInputSchema,
|
||||
DesktopPreviewAutomationClickInputSchema,
|
||||
DesktopPreviewAutomationEvaluateInputSchema,
|
||||
DesktopPreviewAutomationPressInputSchema,
|
||||
DesktopPreviewAutomationScrollInputSchema,
|
||||
DesktopPreviewAutomationTypeInputSchema,
|
||||
DesktopPreviewAutomationWaitForInputSchema,
|
||||
DesktopPreviewConfigInputSchema,
|
||||
DesktopPreviewNavigateInputSchema,
|
||||
DesktopPreviewRecordingArtifactSchema,
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const installPreviewEventForwarding = Effect.fn(
|
||||
"desktop.ipc.preview.installEventForwarding",
|
||||
)(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.subscribeStateChanges((tabId, state) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
|
||||
);
|
||||
yield* manager.subscribeRecordingFrames((frame) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
|
||||
);
|
||||
yield* manager.subscribePointerEvents((event) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
|
||||
);
|
||||
});
|
||||
|
||||
export const createTab = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.createTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const closeTab = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.closeTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const registerWebview = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
|
||||
payload: DesktopPreviewRegisterWebviewInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.registerWebview(tabId, webContentsId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const navigate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
|
||||
payload: DesktopPreviewNavigateInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.navigate(tabId, url);
|
||||
}),
|
||||
});
|
||||
|
||||
const tabMethod = (
|
||||
channel: string,
|
||||
name: string,
|
||||
invoke: (
|
||||
manager: PreviewManager.PreviewManager["Service"],
|
||||
tabId: string,
|
||||
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
|
||||
) =>
|
||||
DesktopIpc.makeIpcMethod({
|
||||
channel,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn(name)(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* invoke(manager, tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const goBack = tabMethod(
|
||||
IpcChannels.PREVIEW_GO_BACK_CHANNEL,
|
||||
"desktop.ipc.preview.goBack",
|
||||
(manager, tabId) => manager.goBack(tabId),
|
||||
);
|
||||
export const goForward = tabMethod(
|
||||
IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
|
||||
"desktop.ipc.preview.goForward",
|
||||
(manager, tabId) => manager.goForward(tabId),
|
||||
);
|
||||
export const refresh = tabMethod(
|
||||
IpcChannels.PREVIEW_REFRESH_CHANNEL,
|
||||
"desktop.ipc.preview.refresh",
|
||||
(manager, tabId) => manager.refresh(tabId),
|
||||
);
|
||||
export const zoomIn = tabMethod(
|
||||
IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
|
||||
"desktop.ipc.preview.zoomIn",
|
||||
(manager, tabId) => manager.zoomIn(tabId),
|
||||
);
|
||||
export const zoomOut = tabMethod(
|
||||
IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
|
||||
"desktop.ipc.preview.zoomOut",
|
||||
(manager, tabId) => manager.zoomOut(tabId),
|
||||
);
|
||||
export const resetZoom = tabMethod(
|
||||
IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
|
||||
"desktop.ipc.preview.resetZoom",
|
||||
(manager, tabId) => manager.resetZoom(tabId),
|
||||
);
|
||||
export const hardReload = tabMethod(
|
||||
IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
|
||||
"desktop.ipc.preview.hardReload",
|
||||
(manager, tabId) => manager.hardReload(tabId),
|
||||
);
|
||||
export const openDevTools = tabMethod(
|
||||
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
|
||||
"desktop.ipc.preview.openDevTools",
|
||||
(manager, tabId) => manager.openDevTools(tabId),
|
||||
);
|
||||
export const cancelPickElement = tabMethod(
|
||||
IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
|
||||
"desktop.ipc.preview.cancelPickElement",
|
||||
(manager, tabId) => manager.cancelPickElement(tabId),
|
||||
);
|
||||
export const startRecording = tabMethod(
|
||||
IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
|
||||
"desktop.ipc.preview.startRecording",
|
||||
(manager, tabId) => manager.startRecording(tabId),
|
||||
);
|
||||
export const stopRecording = tabMethod(
|
||||
IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
|
||||
"desktop.ipc.preview.stopRecording",
|
||||
(manager, tabId) => manager.stopRecording(tabId),
|
||||
);
|
||||
|
||||
export const clearCookies = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCookies();
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCache = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCache();
|
||||
}),
|
||||
});
|
||||
|
||||
export const getPreviewConfig = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
|
||||
payload: DesktopPreviewConfigInputSchema,
|
||||
result: DesktopPreviewWebviewConfigSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.getBrowserSession(environmentId);
|
||||
return {
|
||||
partition: yield* manager.getBrowserPartition(environmentId),
|
||||
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
|
||||
preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
|
||||
payload: DesktopPreviewAnnotationThemeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.setAnnotationTheme(theme);
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.pickElement(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const captureScreenshot = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: DesktopPreviewScreenshotArtifactSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.captureScreenshot(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const revealArtifact = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.revealArtifact(path);
|
||||
}),
|
||||
});
|
||||
|
||||
export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.copyArtifactToClipboard(path);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationStatus = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationStatus,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationStatus")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationStatus(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationSnapshot = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationSnapshot,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationSnapshot")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationSnapshot(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationClick = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
|
||||
payload: DesktopPreviewAutomationClickInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationClick")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationClick(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationType = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationTypeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationType")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationType(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationPress = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
|
||||
payload: DesktopPreviewAutomationPressInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationPress")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationPress(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationScroll = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
|
||||
payload: DesktopPreviewAutomationScrollInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationScroll")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationScroll(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationEvaluate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationEvaluateInputSchema,
|
||||
result: Schema.Unknown,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationEvaluate")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationEvaluate(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationWaitFor = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
|
||||
payload: DesktopPreviewAutomationWaitForInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationWaitFor")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationWaitFor(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const saveRecording = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
|
||||
payload: DesktopPreviewRecordingSaveInputSchema,
|
||||
result: DesktopPreviewRecordingArtifactSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.saveRecording(tabId, mimeType, data);
|
||||
}),
|
||||
});
|
||||
|
||||
export const methods = [
|
||||
createTab,
|
||||
closeTab,
|
||||
registerWebview,
|
||||
navigate,
|
||||
goBack,
|
||||
goForward,
|
||||
refresh,
|
||||
zoomIn,
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
getPreviewConfig,
|
||||
setAnnotationTheme,
|
||||
pickElement,
|
||||
cancelPickElement,
|
||||
captureScreenshot,
|
||||
revealArtifact,
|
||||
copyArtifactToClipboard,
|
||||
automationStatus,
|
||||
automationSnapshot,
|
||||
automationClick,
|
||||
automationType,
|
||||
automationPress,
|
||||
automationScroll,
|
||||
automationEvaluate,
|
||||
automationWaitFor,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
saveRecording,
|
||||
] as const;
|
||||
@@ -1,76 +0,0 @@
|
||||
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
|
||||
const NonBlankString = Schema.String.check(
|
||||
Schema.makeFilter((value) =>
|
||||
value.trim().length > 0 ? undefined : "Expected a non-empty string",
|
||||
),
|
||||
);
|
||||
|
||||
const SetSavedEnvironmentSecretInput = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
secret: NonBlankString,
|
||||
});
|
||||
|
||||
export const getSavedEnvironmentRegistry = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: SavedEnvironmentRegistryPayload,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return yield* savedEnvironments.getRegistry;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setSavedEnvironmentRegistry = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
|
||||
payload: SavedEnvironmentRegistryPayload,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry(records);
|
||||
}),
|
||||
});
|
||||
|
||||
export const getSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: EnvironmentId,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
|
||||
}),
|
||||
});
|
||||
|
||||
export const setSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: SetSavedEnvironmentSecretInput,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
|
||||
environmentId,
|
||||
secret,
|
||||
}) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return yield* savedEnvironments.setSecret({
|
||||
environmentId,
|
||||
secret,
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
export const removeSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: EnvironmentId,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.removeSecret(environmentId);
|
||||
}),
|
||||
});
|
||||
@@ -9,14 +9,14 @@ import * as Schema from "effect/Schema";
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
const SetTailscaleServeEnabledInput = Schema.Struct({
|
||||
enabled: Schema.Boolean,
|
||||
port: Schema.optionalKey(Schema.Number),
|
||||
});
|
||||
|
||||
export const getServerExposureState = makeIpcMethod({
|
||||
export const getServerExposureState = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -26,7 +26,7 @@ export const getServerExposureState = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setServerExposureMode = makeIpcMethod({
|
||||
export const setServerExposureMode = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_SERVER_EXPOSURE_MODE_CHANNEL,
|
||||
payload: DesktopServerExposureModeSchema,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -41,7 +41,7 @@ export const setServerExposureMode = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTailscaleServeEnabled = makeIpcMethod({
|
||||
export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL,
|
||||
payload: SetTailscaleServeEnabledInput,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -58,7 +58,7 @@ export const setTailscaleServeEnabled = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getAdvertisedEndpoints = makeIpcMethod({
|
||||
export const getAdvertisedEndpoints = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Array(AdvertisedEndpoint),
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import {
|
||||
bootstrapRemoteBearerSession,
|
||||
fetchRemoteEnvironmentDescriptor,
|
||||
fetchRemoteSessionState,
|
||||
issueRemoteWebSocketTicket,
|
||||
RemoteEnvironmentAuthUndeclaredStatusError,
|
||||
type RemoteEnvironmentAuthError,
|
||||
} from "@t3tools/client-runtime";
|
||||
} from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
EnvironmentAuthInvalidError,
|
||||
DesktopDiscoveredSshHostSchema,
|
||||
@@ -33,7 +33,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc 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 = makeIpcMethod({
|
||||
export const discoverSshHosts = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Array(DesktopDiscoveredSshHostSchema),
|
||||
@@ -117,7 +117,7 @@ export const discoverSshHosts = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const ensureSshEnvironment = makeIpcMethod({
|
||||
export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
|
||||
payload: DesktopSshEnvironmentEnsureInputSchema,
|
||||
result: DesktopSshEnvironmentEnsureResultSchema,
|
||||
@@ -139,7 +139,7 @@ export const ensureSshEnvironment = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const disconnectSshEnvironment = makeIpcMethod({
|
||||
export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL,
|
||||
payload: DesktopSshEnvironmentTargetSchema,
|
||||
result: Schema.Void,
|
||||
@@ -149,7 +149,7 @@ export const disconnectSshEnvironment = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchSshEnvironmentDescriptor = makeIpcMethod({
|
||||
export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
|
||||
payload: DesktopSshHttpBaseUrlInputSchema,
|
||||
result: ExecutionEnvironmentDescriptor,
|
||||
@@ -160,7 +160,7 @@ export const fetchSshEnvironmentDescriptor = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const bootstrapSshBearerSession = makeIpcMethod({
|
||||
export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
|
||||
payload: DesktopSshBearerBootstrapInputSchema,
|
||||
result: AuthAccessTokenResult,
|
||||
@@ -177,7 +177,7 @@ export const bootstrapSshBearerSession = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchSshSessionState = makeIpcMethod({
|
||||
export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL,
|
||||
payload: DesktopSshBearerRequestInputSchema,
|
||||
result: AuthSessionState,
|
||||
@@ -194,7 +194,7 @@ export const fetchSshSessionState = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const issueSshWebSocketTicket = makeIpcMethod({
|
||||
export const issueSshWebSocketTicket = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
|
||||
payload: DesktopSshBearerRequestInputSchema,
|
||||
result: AuthWebSocketTicketResult,
|
||||
@@ -211,7 +211,7 @@ export const issueSshWebSocketTicket = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const resolveSshPasswordPrompt = makeIpcMethod({
|
||||
export const resolveSshPasswordPrompt = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
|
||||
payload: DesktopSshPasswordPromptResolutionInputSchema,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -9,9 +9,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopUpdates from "../../updates/DesktopUpdates.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const getUpdateState = makeIpcMethod({
|
||||
export const getUpdateState = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_GET_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateStateSchema,
|
||||
@@ -21,7 +21,7 @@ export const getUpdateState = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setUpdateChannel = makeIpcMethod({
|
||||
export const setUpdateChannel = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
|
||||
payload: DesktopUpdateChannelSchema,
|
||||
result: DesktopUpdateStateSchema,
|
||||
@@ -31,7 +31,7 @@ export const setUpdateChannel = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const downloadUpdate = makeIpcMethod({
|
||||
export const downloadUpdate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_DOWNLOAD_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateActionResultSchema,
|
||||
@@ -41,7 +41,7 @@ export const downloadUpdate = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const installUpdate = makeIpcMethod({
|
||||
export const installUpdate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateActionResultSchema,
|
||||
@@ -51,7 +51,7 @@ export const installUpdate = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const checkForUpdate = makeIpcMethod({
|
||||
export const checkForUpdate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_CHECK_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateCheckResultSchema,
|
||||
|
||||
@@ -10,6 +10,7 @@ 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";
|
||||
@@ -17,7 +18,7 @@ import * as ElectronShell from "../../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
const ContextMenuPosition = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
@@ -35,7 +36,7 @@ function toWebSocketBaseUrl(httpBaseUrl: URL): string {
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export const getAppBranding = makeSyncIpcMethod({
|
||||
export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
|
||||
result: Schema.NullOr(DesktopAppBrandingSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
|
||||
@@ -44,7 +45,7 @@ export const getAppBranding = makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
|
||||
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
|
||||
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
|
||||
@@ -64,7 +65,17 @@ export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickFolder = makeIpcMethod({
|
||||
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({
|
||||
channel: IpcChannels.PICK_FOLDER_CHANNEL,
|
||||
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
|
||||
result: Schema.NullOr(Schema.String),
|
||||
@@ -80,7 +91,7 @@ export const pickFolder = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const confirm = makeIpcMethod({
|
||||
export const confirm = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CONFIRM_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
@@ -93,7 +104,7 @@ export const confirm = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTheme = makeIpcMethod({
|
||||
export const setTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_THEME_CHANNEL,
|
||||
payload: DesktopThemeSchema,
|
||||
result: Schema.Void,
|
||||
@@ -103,7 +114,7 @@ export const setTheme = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const showContextMenu = makeIpcMethod({
|
||||
export const showContextMenu = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CONTEXT_MENU_CHANNEL,
|
||||
payload: ContextMenuInput,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
@@ -124,7 +135,7 @@ export const showContextMenu = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const openExternal = makeIpcMethod({
|
||||
export const openExternal = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
|
||||
+46
-15
@@ -9,29 +9,34 @@ import * as Option from "effect/Option";
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
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 DesktopSecretStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as ElectronSafeStorage 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 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";
|
||||
@@ -42,6 +47,8 @@ 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 PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
@@ -49,19 +56,21 @@ const desktopEnvironmentLayer = Layer.unwrap(
|
||||
const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe(
|
||||
Effect.flatMap((app) => app.metadata),
|
||||
);
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const processArch = yield* HostProcessArchitecture;
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: __dirname,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
platform,
|
||||
processArch,
|
||||
...metadata,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveDesktopSshCliRunner = (
|
||||
environment: DesktopEnvironment.DesktopEnvironmentShape,
|
||||
settings: DesktopSettingsValue,
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
settings: DesktopAppSettings.DesktopSettings,
|
||||
): RemoteT3RunnerOptions => {
|
||||
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
|
||||
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
|
||||
@@ -97,20 +106,20 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronProtocol.layer,
|
||||
DesktopSecretStorage.layer,
|
||||
ElectronSafeStorage.layer,
|
||||
ElectronShell.layer,
|
||||
ElectronTheme.layer,
|
||||
ElectronUpdater.layer,
|
||||
ElectronWindow.layer,
|
||||
Layer.succeed(DesktopIpc.DesktopIpc, DesktopIpc.make(Electron.ipcMain)),
|
||||
DesktopIpc.layer(Electron.ipcMain),
|
||||
);
|
||||
|
||||
const desktopFoundationLayer = Layer.mergeAll(
|
||||
DesktopState.layer,
|
||||
DesktopLifecycle.layerShutdown,
|
||||
DesktopShutdown.layer,
|
||||
DesktopAppSettings.layer,
|
||||
DesktopClientSettings.layer,
|
||||
DesktopSavedEnvironments.layer,
|
||||
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
|
||||
DesktopAssets.layer,
|
||||
DesktopObservability.layer,
|
||||
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
|
||||
@@ -120,11 +129,19 @@ const desktopSshLayer = desktopSshEnvironmentLayer.pipe(
|
||||
);
|
||||
|
||||
const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(DesktopServerExposure.networkInterfacesLayer),
|
||||
Layer.provideMerge(DesktopNetworkInterfaces.layer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer));
|
||||
const desktopPreviewLayer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(BrowserSession.layer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
Layer.provideMerge(desktopServerExposureLayer),
|
||||
Layer.provideMerge(desktopPreviewLayer),
|
||||
);
|
||||
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
@@ -132,16 +149,30 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
|
||||
).pipe(
|
||||
Layer.provideMerge(DesktopUpdates.layer),
|
||||
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
|
||||
Layer.flatMap(() =>
|
||||
const desktopClerkLayer = DesktopClerk.layer.pipe(
|
||||
Layer.provideMerge(desktopEnvironmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ElectronApp.layer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = desktopClerkLayer.pipe(
|
||||
Layer.flatMap((clerkContext) =>
|
||||
desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
|
||||
+108
-11
@@ -1,8 +1,16 @@
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
import type {
|
||||
DesktopBridge,
|
||||
DesktopPreviewPointerEvent,
|
||||
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" &&
|
||||
@@ -34,19 +42,15 @@ 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),
|
||||
getSavedEnvironmentRegistry: () =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
|
||||
setSavedEnvironmentRegistry: (records) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
|
||||
getSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
setSavedEnvironmentSecret: (environmentId, secret) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
|
||||
removeSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
|
||||
setConnectionCatalog: (catalog) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
|
||||
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
|
||||
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
|
||||
ensureSshEnvironment: async (target, options) =>
|
||||
unwrapEnsureSshEnvironmentResult(
|
||||
@@ -124,4 +128,97 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
preview: {
|
||||
createTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, { tabId }),
|
||||
closeTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, { tabId }),
|
||||
registerWebview: (tabId, webContentsId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, { tabId, webContentsId }),
|
||||
navigate: (tabId, url) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_NAVIGATE_CHANNEL, { tabId, url }),
|
||||
goBack: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_BACK_CHANNEL, { tabId }),
|
||||
goForward: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, { tabId }),
|
||||
refresh: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_REFRESH_CHANNEL, { tabId }),
|
||||
zoomIn: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, { tabId }),
|
||||
zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
|
||||
resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
|
||||
hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
|
||||
openDevTools: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
|
||||
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
|
||||
clearCache: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL),
|
||||
getPreviewConfig: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId }),
|
||||
setAnnotationTheme: (theme) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }),
|
||||
pickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId }),
|
||||
cancelPickElement: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, { tabId }),
|
||||
captureScreenshot: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, { tabId }),
|
||||
revealArtifact: (path) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, { path }),
|
||||
copyArtifactToClipboard: (path) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, { path }),
|
||||
recording: {
|
||||
startScreencast: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_START_CHANNEL, { tabId }),
|
||||
stopScreencast: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL, { tabId }),
|
||||
save: (tabId, mimeType, data) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL, {
|
||||
tabId,
|
||||
mimeType,
|
||||
data,
|
||||
}),
|
||||
onFrame: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, frame: unknown) => {
|
||||
if (typeof frame !== "object" || frame === null) return;
|
||||
listener(frame as DesktopPreviewRecordingFrame);
|
||||
};
|
||||
ipcRenderer.on(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, wrappedListener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, wrappedListener);
|
||||
},
|
||||
},
|
||||
automation: {
|
||||
status: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL, { tabId }),
|
||||
snapshot: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL, { tabId }),
|
||||
click: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL, { tabId, input }),
|
||||
type: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL, { tabId, input }),
|
||||
press: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL, { tabId, input }),
|
||||
scroll: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL, { tabId, input }),
|
||||
evaluate: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL, { tabId, input }),
|
||||
waitFor: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL, { tabId, input }),
|
||||
},
|
||||
onStateChange: (listener) => {
|
||||
const wrappedListener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
tabId: unknown,
|
||||
state: unknown,
|
||||
) => {
|
||||
if (typeof tabId !== "string" || typeof state !== "object" || state === null) return;
|
||||
listener(tabId, state as DesktopPreviewTabState);
|
||||
};
|
||||
ipcRenderer.on(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
|
||||
},
|
||||
onPointerEvent: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, pointerEvent: unknown) => {
|
||||
if (typeof pointerEvent !== "object" || pointerEvent === null) return;
|
||||
listener(pointerEvent as DesktopPreviewPointerEvent);
|
||||
};
|
||||
ipcRenderer.on(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
|
||||
},
|
||||
},
|
||||
} satisfies DesktopBridge);
|
||||
@@ -0,0 +1 @@
|
||||
import "./preview/PickPreload.ts";
|
||||
@@ -0,0 +1,68 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme inline {
|
||||
--font-sans: var(--t3-font-sans);
|
||||
--font-mono: var(--t3-font-mono);
|
||||
--color-background: var(--t3-background);
|
||||
--color-foreground: var(--t3-foreground);
|
||||
--color-popover: var(--t3-popover);
|
||||
--color-popover-foreground: var(--t3-popover-foreground);
|
||||
--color-primary: var(--t3-primary);
|
||||
--color-primary-foreground: var(--t3-primary-foreground);
|
||||
--color-muted: var(--t3-muted);
|
||||
--color-muted-foreground: var(--t3-muted-foreground);
|
||||
--color-accent: var(--t3-accent);
|
||||
--color-accent-foreground: var(--t3-accent-foreground);
|
||||
--color-border: var(--t3-border);
|
||||
--color-input: var(--t3-input);
|
||||
--color-ring: var(--t3-ring);
|
||||
--radius-sm: calc(var(--t3-radius) - 4px);
|
||||
--radius-md: calc(var(--t3-radius) - 2px);
|
||||
--radius-lg: var(--t3-radius);
|
||||
--radius-xl: calc(var(--t3-radius) + 4px);
|
||||
--radius-2xl: calc(var(--t3-radius) + 8px);
|
||||
}
|
||||
|
||||
:host {
|
||||
--t3-font-sans:
|
||||
"DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,
|
||||
sans-serif;
|
||||
--t3-font-mono:
|
||||
"SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;
|
||||
--t3-radius: 0.625rem;
|
||||
--t3-background: white;
|
||||
--t3-foreground: oklch(0.269 0 0);
|
||||
--t3-popover: white;
|
||||
--t3-popover-foreground: oklch(0.269 0 0);
|
||||
--t3-primary: oklch(0.488 0.217 264);
|
||||
--t3-primary-foreground: white;
|
||||
--t3-muted: rgb(0 0 0 / 4%);
|
||||
--t3-muted-foreground: oklch(0.556 0 0);
|
||||
--t3-accent: rgb(0 0 0 / 4%);
|
||||
--t3-accent-foreground: oklch(0.269 0 0);
|
||||
--t3-border: rgb(0 0 0 / 8%);
|
||||
--t3-input: rgb(0 0 0 / 10%);
|
||||
--t3-ring: oklch(0.488 0.217 264);
|
||||
color: var(--t3-foreground);
|
||||
font-family: var(--t3-font-sans);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
border-color: var(--t3-border);
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button:focus-visible,
|
||||
input:focus-visible,
|
||||
select:focus-visible,
|
||||
textarea:focus-visible {
|
||||
outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.
|
||||
export const previewAnnotationStyles =
|
||||
'/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: calc(var(--spacing) * 0);\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);Line truncated
|
||||
@@ -0,0 +1,191 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { fromPartition, sessions } = vi.hoisted(() => ({
|
||||
fromPartition: vi.fn(),
|
||||
sessions: new Map<
|
||||
string,
|
||||
{
|
||||
readonly clearCache: ReturnType<typeof vi.fn>;
|
||||
readonly clearStorageData: ReturnType<typeof vi.fn>;
|
||||
readonly getUserAgent: ReturnType<typeof vi.fn>;
|
||||
readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
|
||||
readonly setUserAgent: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
>(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
session: {
|
||||
fromPartition,
|
||||
},
|
||||
}));
|
||||
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
|
||||
const layer = BrowserSession.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
describe("BrowserSession", () => {
|
||||
beforeEach(() => {
|
||||
sessions.clear();
|
||||
fromPartition.mockReset();
|
||||
fromPartition.mockImplementation((partition: string) => {
|
||||
const browserSession = {
|
||||
clearCache: vi.fn(() => Promise.resolve()),
|
||||
clearStorageData: vi.fn(() => Promise.resolve()),
|
||||
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
|
||||
setPermissionRequestHandler: vi.fn(),
|
||||
setUserAgent: vi.fn(),
|
||||
};
|
||||
sessions.set(partition, browserSession);
|
||||
return browserSession;
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("derives deterministic partitions and memoizes sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
|
||||
const partition = yield* browserSessions.getPartition("scope-a");
|
||||
const first = yield* browserSessions.getSession("scope-a");
|
||||
const second = yield* browserSessions.getSession("scope-a");
|
||||
|
||||
assert.strictEqual(partition, "persist:t3code-preview-f051bb2c68cb7b2fe969");
|
||||
assert.strictEqual(first, second);
|
||||
assert.strictEqual(fromPartition.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves partition scope and the platform failure chain", () => {
|
||||
const nativeCause = new Error("native digest failed");
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "Crypto",
|
||||
method: "digest",
|
||||
cause: nativeCause,
|
||||
});
|
||||
const failingCryptoLayer = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => new Uint8Array(size),
|
||||
digest: () => Effect.fail(platformCause),
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-a");
|
||||
assert.strictEqual(error.cause, platformCause);
|
||||
assert.strictEqual(error.cause.reason.cause, nativeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to derive a desktop preview browser partition for scope environment-a.",
|
||||
);
|
||||
assert.notInclude(error.message, nativeCause.message);
|
||||
}).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
|
||||
});
|
||||
|
||||
it.effect("preserves session scope, partition, and the Electron failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("Electron session failed");
|
||||
fromPartition.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const partition = yield* browserSessions.getPartition("environment-b");
|
||||
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-b");
|
||||
assert.equal(error.partition, partition);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("clears storage and cache for every created session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
yield* browserSessions.getSession("scope-b");
|
||||
|
||||
yield* browserSessions.clearCookies();
|
||||
yield* browserSessions.clearCache();
|
||||
|
||||
assert.strictEqual(sessions.size, 2);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
|
||||
assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
|
||||
{
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("correlates clear failures while still attempting every session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
yield* browserSessions.getSession("scope-b");
|
||||
const firstPartition = yield* browserSessions.getPartition("scope-a");
|
||||
const secondPartition = yield* browserSessions.getPartition("scope-b");
|
||||
const firstSession = sessions.get(firstPartition);
|
||||
const secondSession = sessions.get(secondPartition);
|
||||
assert.isDefined(firstSession);
|
||||
assert.isDefined(secondSession);
|
||||
|
||||
const storageCause = new Error("storage clear failed");
|
||||
secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
|
||||
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
|
||||
assert.equal(storageError.partition, secondPartition);
|
||||
assert.strictEqual(storageError.cause, storageCause);
|
||||
assert.equal(
|
||||
storageError.message,
|
||||
`Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
|
||||
);
|
||||
assert.notInclude(storageError.message, storageCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
|
||||
}
|
||||
|
||||
const cacheCause = new Error("cache clear failed");
|
||||
firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
|
||||
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
|
||||
assert.equal(cacheError.partition, firstPartition);
|
||||
assert.strictEqual(cacheError.cause, cacheCause);
|
||||
assert.equal(
|
||||
cacheError.message,
|
||||
`Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
|
||||
);
|
||||
assert.notInclude(cacheError.message, cacheCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import type { Session } from "electron";
|
||||
import { session } from "electron";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
"BrowserSessionPartitionDerivationError",
|
||||
{
|
||||
scope: Schema.String,
|
||||
cause: Schema.instanceOf(PlatformError.PlatformError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
|
||||
"BrowserSessionCreationError",
|
||||
{
|
||||
scope: Schema.String,
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
|
||||
"BrowserSessionStorageClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
|
||||
"BrowserSessionCacheClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BrowserSessionGetSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
]);
|
||||
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
|
||||
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
|
||||
|
||||
export const BrowserSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
BrowserSessionStorageClearError,
|
||||
BrowserSessionCacheClearError,
|
||||
]);
|
||||
export type BrowserSessionError = typeof BrowserSessionError.Type;
|
||||
export const isBrowserSessionError = Schema.is(BrowserSessionError);
|
||||
|
||||
export class BrowserSession extends Context.Service<
|
||||
BrowserSession,
|
||||
{
|
||||
readonly getPartition: (
|
||||
scope?: string,
|
||||
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserSession") {}
|
||||
|
||||
export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
|
||||
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BrowserSessionPartitionDerivationError({
|
||||
scope,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
|
||||
});
|
||||
|
||||
const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
|
||||
const partition = yield* getPartition(scope);
|
||||
return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
|
||||
const existing = sessions.get(partition);
|
||||
if (existing) return Effect.succeed([existing, sessions] as const);
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const browserSession = session.fromPartition(partition);
|
||||
const userAgent = browserSession
|
||||
.getUserAgent()
|
||||
.replace(/Electron\/[\d.]+ /, "")
|
||||
.replace(/\s*t3code\/[\d.]+/, "");
|
||||
browserSession.setUserAgent(userAgent);
|
||||
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
|
||||
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
|
||||
callback(allowed.includes(permission));
|
||||
});
|
||||
const next = new Map(sessions);
|
||||
next.set(partition, browserSession);
|
||||
return [browserSession, next] as const;
|
||||
},
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCreationError({
|
||||
scope,
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
return BrowserSession.of({
|
||||
getPartition,
|
||||
isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
|
||||
getSession,
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
browserSession.clearStorageData({
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionStorageClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
}),
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () => browserSession.clearCache(),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCacheClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
}),
|
||||
});
|
||||
}).pipe(Effect.withSpan("BrowserSession.make"));
|
||||
|
||||
export const layer = Layer.effect(BrowserSession, make);
|
||||
@@ -0,0 +1,6 @@
|
||||
export const START_PICK_CHANNEL = "preview:start-pick";
|
||||
export const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
|
||||
export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
|
||||
export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
|
||||
export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
|
||||
export const HUMAN_INPUT_CHANNEL = "preview:human-input";
|
||||
@@ -0,0 +1,742 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
writeImage,
|
||||
},
|
||||
nativeImage: {
|
||||
createFromPath,
|
||||
},
|
||||
shell: {
|
||||
showItemInFolder,
|
||||
},
|
||||
session: {
|
||||
fromPartition: vi.fn(),
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
},
|
||||
}));
|
||||
|
||||
const browserSessionLayer = Layer.succeed(
|
||||
BrowserSession.BrowserSession,
|
||||
BrowserSession.BrowserSession.of({
|
||||
getPartition: () => Effect.succeed("persist:t3code-preview-test"),
|
||||
isPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
|
||||
getSession: () => Effect.die("unexpected getSession"),
|
||||
clearCookies: () => Effect.void,
|
||||
clearCache: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
|
||||
const environmentLayer = Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
|
||||
} as DesktopEnvironment.DesktopEnvironment["Service"]),
|
||||
);
|
||||
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: (path) =>
|
||||
Effect.sync(() => {
|
||||
mkdir(path);
|
||||
}),
|
||||
writeFile: (path, data) =>
|
||||
Effect.sync(() => {
|
||||
writeFile(path, data);
|
||||
}),
|
||||
});
|
||||
|
||||
const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(browserSessionLayer),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
);
|
||||
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
|
||||
|
||||
const withManager = <A>(
|
||||
use: (
|
||||
manager: PreviewManager.PreviewManager["Service"],
|
||||
) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* use(manager);
|
||||
}).pipe(Effect.provide(layer), Effect.scoped);
|
||||
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
writeImage.mockClear();
|
||||
createFromPath.mockClear();
|
||||
webviewSend.mockClear();
|
||||
});
|
||||
|
||||
effectIt.effect("reports an unregistered webview as temporarily unavailable", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
expect(yield* manager.automationStatus("tab_1")).toEqual({
|
||||
available: false,
|
||||
visible: true,
|
||||
tabId: "tab_1",
|
||||
url: null,
|
||||
title: null,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
|
||||
expect(yield* manager.automationStatus("tab_1")).toEqual({
|
||||
available: false,
|
||||
visible: true,
|
||||
tabId: "tab_1",
|
||||
url: null,
|
||||
title: null,
|
||||
loading: false,
|
||||
});
|
||||
expect(fromId).not.toHaveBeenCalled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("isolates failed state listeners and continues delivery", () => {
|
||||
const loggedErrors: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
for (const value of Array.isArray(message) ? message : [message]) {
|
||||
if (typeof value === "object" && value !== null && "cause" in value) {
|
||||
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
|
||||
}
|
||||
}
|
||||
});
|
||||
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform: "darwin",
|
||||
windowId: 42,
|
||||
channel: "preview:state-change",
|
||||
cause: new Error("renderer unavailable"),
|
||||
});
|
||||
const delivered = vi.fn();
|
||||
|
||||
return withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
|
||||
yield* manager.subscribeStateChanges((tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
delivered(tabId, state);
|
||||
}),
|
||||
);
|
||||
|
||||
const state = yield* manager.createTab("tab_listener_failure");
|
||||
|
||||
expect(delivered).toHaveBeenCalledOnce();
|
||||
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
|
||||
expect(loggedErrors).toHaveLength(1);
|
||||
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
|
||||
expect(loggedErrors[0]).toMatchObject({
|
||||
operation: "send-window-message",
|
||||
windowId: 42,
|
||||
channel: "preview:state-change",
|
||||
});
|
||||
}),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Logger.layer([logger], {
|
||||
mergeWithExisting: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
effectIt.effect("does not swallow state listener interruption", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const exit = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* manager.subscribeStateChanges(() => Effect.interrupt);
|
||||
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("queues navigation until the webview registers", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const loadURL = vi.fn(async () => undefined);
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "about:blank",
|
||||
getTitle: () => "",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
loadURL,
|
||||
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.navigate("tab_pending", "localhost:3200");
|
||||
|
||||
expect(yield* manager.automationStatus("tab_pending")).toEqual({
|
||||
available: false,
|
||||
visible: true,
|
||||
tabId: "tab_pending",
|
||||
url: "http://localhost:3200/",
|
||||
title: "",
|
||||
loading: true,
|
||||
});
|
||||
|
||||
yield* manager.registerWebview("tab_pending", 42);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(loadURL).toHaveBeenCalledOnce();
|
||||
expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const png = Buffer.from("preview-png");
|
||||
const capturePage = vi.fn(async () => ({ toPNG: () => png }));
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com:8443/path?query=value",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
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(),
|
||||
},
|
||||
capturePage,
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
|
||||
expect(webviewSend).toHaveBeenCalledWith(
|
||||
"preview:annotation-theme",
|
||||
expect.objectContaining({
|
||||
colorScheme: "light",
|
||||
primary: "oklch(0.488 0.217 264)",
|
||||
}),
|
||||
);
|
||||
|
||||
const artifact = yield* manager.captureScreenshot("tab_1");
|
||||
|
||||
expect(capturePage).toHaveBeenCalledOnce();
|
||||
expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts");
|
||||
expect(writeFile).toHaveBeenCalledWith(artifact.path, png);
|
||||
expect(artifact).toMatchObject({
|
||||
tabId: "tab_1",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: png.byteLength,
|
||||
});
|
||||
expect(artifact.path).toMatch(
|
||||
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
|
||||
);
|
||||
|
||||
const captureCause = new Error("capture failed");
|
||||
capturePage.mockRejectedValueOnce(captureCause);
|
||||
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewOperationError",
|
||||
operation: "captureScreenshot.capturePage",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
cause: captureCause,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps element picking active during subframe navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isFocused: () => true,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
listeners.get("did-start-navigation")?.({}, "about:blank", false, false);
|
||||
yield* Effect.yieldNow;
|
||||
expect(pick.pollUnsafe()).toBeUndefined();
|
||||
|
||||
listeners.get("did-start-navigation")?.({}, "https://example.com/next", false, true);
|
||||
expect(yield* Fiber.join(pick)).toBeNull();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
yield* manager.revealArtifact("/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png");
|
||||
|
||||
expect(showItemInFolder).toHaveBeenCalledWith(
|
||||
"/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png",
|
||||
);
|
||||
const exit = yield* Effect.exit(manager.revealArtifact("/tmp/t3/dev/settings.json"));
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewArtifactPathOutsideDirectoryError",
|
||||
artifactPath: "/tmp/t3/dev/settings.json",
|
||||
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("copies screenshot artifacts to the system clipboard", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png";
|
||||
|
||||
yield* manager.copyArtifactToClipboard(artifactPath);
|
||||
|
||||
expect(createFromPath).toHaveBeenCalledWith(artifactPath);
|
||||
expect(writeImage).toHaveBeenCalledOnce();
|
||||
const exit = yield* Effect.exit(
|
||||
manager.copyArtifactToClipboard("/tmp/t3/dev/settings.json"),
|
||||
);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewArtifactPathOutsideDirectoryError",
|
||||
artifactPath: "/tmp/t3/dev/settings.json",
|
||||
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
|
||||
createFromPath.mockReturnValueOnce({ isEmpty: () => true });
|
||||
const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
|
||||
expect(Exit.isFailure(invalidImageExit)).toBe(true);
|
||||
if (Exit.isSuccess(invalidImageExit)) return;
|
||||
expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({
|
||||
_tag: "PreviewArtifactImageLoadError",
|
||||
artifactPath,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("emits the resolved pointer target before dispatching an automation click", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const activity: string[] = [];
|
||||
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (method === "Runtime.evaluate") {
|
||||
return {
|
||||
result: {
|
||||
value: { width: 800, height: 600 },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === "Input.dispatchMouseEvent" && params?.type === "mousePressed") {
|
||||
activity.push("mousePressed");
|
||||
humanInput?.({}, { kind: "pointer", x: params.x, y: params.y, button: 0 });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.subscribePointerEvents((event) =>
|
||||
Effect.sync(() => {
|
||||
activity.push(event.phase);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const click = yield* manager
|
||||
.automationClick("tab_1", { x: 120, y: 80 })
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* TestClock.adjust(200);
|
||||
yield* Fiber.join(click);
|
||||
|
||||
expect(activity).toEqual(["move", "click", "mousePressed"]);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
|
||||
type: "mousePressed",
|
||||
x: 120,
|
||||
y: 80,
|
||||
button: "left",
|
||||
clickCount: 1,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
|
||||
type: "mouseReleased",
|
||||
x: 120,
|
||||
y: 80,
|
||||
button: "left",
|
||||
clickCount: 1,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const sendCommand = vi.fn(async (method: string) => {
|
||||
if (method === "Runtime.evaluate") {
|
||||
return {
|
||||
result: {
|
||||
value: { width: 800, height: 600 },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === "Input.dispatchMouseEvent") {
|
||||
humanInput?.({}, { kind: "pointer", x: 400, y: 300, button: 0 });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
|
||||
const click = yield* manager
|
||||
.automationClick("tab_1", { x: 120, y: 80 })
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* TestClock.adjust(200);
|
||||
const exit = yield* Fiber.await(click);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewAutomationControlInterruptedError",
|
||||
operation: "click",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
});
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
if (error instanceof Error) {
|
||||
expect(error.name).toBe("PreviewAutomationControlInterruptedError");
|
||||
}
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("derives evaluation detail kind and length from the same non-empty source", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const text = "ReferenceError: fallbackDetail is not defined";
|
||||
const exceptionDetails = {
|
||||
text,
|
||||
exception: { description: "" },
|
||||
};
|
||||
const sendCommand = vi.fn(async (method: string) =>
|
||||
method === "Runtime.evaluate" ? { exceptionDetails } : undefined,
|
||||
);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const exit = yield* Effect.exit(
|
||||
manager.automationEvaluate("tab_1", { expression: "fallbackDetail" }),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewAutomationEvaluationError",
|
||||
detailKind: "exception-text",
|
||||
detailLength: text.length,
|
||||
cause: exceptionDetails,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("PreviewOperationError", () => {
|
||||
it("keeps timeline detail separate from its structured message", () => {
|
||||
const cause = new Error("CDP command failed with an invalid node id");
|
||||
const error = new PreviewManager.PreviewOperationError({
|
||||
operation: "click.DOM.resolveNode",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Preview automation diagnostics", () => {
|
||||
it("keeps browser exception detail out of structural diagnostics", () => {
|
||||
const secret = "unrelated-browser-payload-secret";
|
||||
const detail = "ReferenceError: missingValue is not defined";
|
||||
const cause = {
|
||||
text: "Uncaught Error",
|
||||
exception: { description: detail },
|
||||
unsafePayload: secret,
|
||||
};
|
||||
const error = new PreviewManager.PreviewAutomationEvaluationError({
|
||||
tabId: "tab_1",
|
||||
detailKind: "exception-description",
|
||||
detailLength: detail.length,
|
||||
cause,
|
||||
});
|
||||
|
||||
const encoded = encodePreviewManagerError(error);
|
||||
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
|
||||
readonly cause?: unknown;
|
||||
};
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodedCause).toStrictEqual(cause);
|
||||
expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
|
||||
expect("detail" in error).toBe(false);
|
||||
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
|
||||
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
|
||||
secret,
|
||||
);
|
||||
});
|
||||
|
||||
it("retains bounded selector diagnostics without exposing selector or reason text", () => {
|
||||
const selector = "role=button[name='selector-secret']";
|
||||
const reason = "Unexpected token near reason-secret";
|
||||
const cause = { invalidSelector: true as const, message: reason };
|
||||
const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
|
||||
operation: "click",
|
||||
tabId: "tab_1",
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
reasonLength: reason.length,
|
||||
cause,
|
||||
});
|
||||
|
||||
const encoded = encodePreviewManagerError(error);
|
||||
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
|
||||
readonly cause?: unknown;
|
||||
};
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodedCause).toStrictEqual(cause);
|
||||
expect(error).toMatchObject({
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
reasonLength: reason.length,
|
||||
});
|
||||
expect(error.detail).toEqual({
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
});
|
||||
expect(error.message).not.toContain("secret");
|
||||
expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
|
||||
expect("selector" in error).toBe(false);
|
||||
expect("reason" in error).toBe(false);
|
||||
expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
|
||||
reason,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not retain a missing target locator", () => {
|
||||
const selector = "[data-token='target-secret']";
|
||||
const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
|
||||
operation: "scroll",
|
||||
tabId: "tab_1",
|
||||
selectorKind: "selector",
|
||||
selectorLength: selector.length,
|
||||
});
|
||||
|
||||
expect(error.message).not.toContain(selector);
|
||||
expect(JSON.stringify(error)).not.toContain(selector);
|
||||
expect("locator" in error).toBe(false);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Pure clamp/flip math for the floating label that follows the cursor while
|
||||
* the user is picking an element in the in-app browser. Lives in its own
|
||||
* electron-free module so the geometry can be unit-tested without spinning
|
||||
* up an Electron preload context (`PickPreload.ts` itself imports
|
||||
* `electron` and `react-grab/primitives`, which can't load under vitest).
|
||||
*
|
||||
* - Horizontally pins the label to `targetLeft`, clamped into
|
||||
* `[VIEWPORT_MARGIN, viewportWidth - labelWidth - VIEWPORT_MARGIN]`.
|
||||
* - Vertically prefers above the target. If the label would overflow the
|
||||
* top, flips below; if THAT also overflows the bottom, pins to the
|
||||
* bottom margin (better to overlap the highlight than disappear).
|
||||
*/
|
||||
|
||||
/** Distance in CSS pixels between the highlight and the floating label. */
|
||||
export const LABEL_GAP = 4;
|
||||
/** Minimum padding the label keeps from any viewport edge. */
|
||||
export const VIEWPORT_MARGIN = 4;
|
||||
|
||||
export function computeLabelPosition(input: {
|
||||
targetLeft: number;
|
||||
targetTop: number;
|
||||
targetBottom: number;
|
||||
labelWidth: number;
|
||||
labelHeight: number;
|
||||
viewportWidth: number;
|
||||
viewportHeight: number;
|
||||
}): { x: number; y: number } {
|
||||
const { targetLeft, targetTop, targetBottom, labelWidth, labelHeight } = input;
|
||||
const { viewportWidth, viewportHeight } = input;
|
||||
|
||||
let x = targetLeft;
|
||||
const maxX = viewportWidth - labelWidth - VIEWPORT_MARGIN;
|
||||
if (x > maxX) x = maxX;
|
||||
if (x < VIEWPORT_MARGIN) x = VIEWPORT_MARGIN;
|
||||
|
||||
let y = targetTop - labelHeight - LABEL_GAP;
|
||||
if (y < VIEWPORT_MARGIN) {
|
||||
y = targetBottom + LABEL_GAP;
|
||||
if (y + labelHeight > viewportHeight - VIEWPORT_MARGIN) {
|
||||
y = Math.max(VIEWPORT_MARGIN, viewportHeight - labelHeight - VIEWPORT_MARGIN);
|
||||
}
|
||||
}
|
||||
|
||||
return { x, y };
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { computeLabelPosition } from "./PickLabelPosition.ts";
|
||||
|
||||
const VIEWPORT = { viewportWidth: 1280, viewportHeight: 800 };
|
||||
|
||||
describe("computeLabelPosition", () => {
|
||||
it("anchors to the element's top-left when there's room above and to the right", () => {
|
||||
const { x, y } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: 200,
|
||||
targetTop: 200,
|
||||
targetBottom: 240,
|
||||
labelWidth: 120,
|
||||
labelHeight: 18,
|
||||
});
|
||||
expect(x).toBe(200);
|
||||
// 200 (top) - 18 (height) - 4 (gap)
|
||||
expect(y).toBe(200 - 18 - 4);
|
||||
});
|
||||
|
||||
it("clamps left edge so the label stays inside the viewport", () => {
|
||||
const { x } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: -50,
|
||||
targetTop: 200,
|
||||
targetBottom: 240,
|
||||
labelWidth: 120,
|
||||
labelHeight: 18,
|
||||
});
|
||||
expect(x).toBe(4);
|
||||
});
|
||||
|
||||
it("clamps right edge when the label would overflow the viewport (the bug we shipped)", () => {
|
||||
const { x } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: 1240,
|
||||
targetTop: 200,
|
||||
targetBottom: 240,
|
||||
labelWidth: 200,
|
||||
labelHeight: 18,
|
||||
});
|
||||
// viewportWidth (1280) - labelWidth (200) - margin (4) = 1076
|
||||
expect(x).toBe(1076);
|
||||
});
|
||||
|
||||
it("flips the label below the element when there's no room above", () => {
|
||||
const { y } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: 200,
|
||||
targetTop: 4,
|
||||
targetBottom: 44,
|
||||
labelWidth: 120,
|
||||
labelHeight: 18,
|
||||
});
|
||||
// labelY = 4 - 18 - 4 = -18 → flip → 44 + 4 = 48
|
||||
expect(y).toBe(48);
|
||||
});
|
||||
|
||||
it("pins to the bottom margin when the element fills the viewport (no room above OR below)", () => {
|
||||
const { y } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: 200,
|
||||
targetTop: 0,
|
||||
targetBottom: 800,
|
||||
labelWidth: 120,
|
||||
labelHeight: 18,
|
||||
});
|
||||
// Above overflows top → flip below = 800 + 4 = 804 → also overflows
|
||||
// bottom → pin to viewportHeight - labelHeight - margin = 778.
|
||||
expect(y).toBe(800 - 18 - 4);
|
||||
});
|
||||
|
||||
it("never returns a negative coordinate", () => {
|
||||
const { x, y } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: -1000,
|
||||
targetTop: -1000,
|
||||
targetBottom: -900,
|
||||
labelWidth: 5000,
|
||||
labelHeight: 5000,
|
||||
});
|
||||
expect(x).toBeGreaterThanOrEqual(0);
|
||||
expect(y).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,201 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isPickedElementPayload, isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
|
||||
function validPayload(overrides?: Record<string, unknown>): Record<string, unknown> {
|
||||
return {
|
||||
pageUrl: "https://example.com/",
|
||||
pageTitle: "Example",
|
||||
tagName: "button",
|
||||
selector: "button.submit",
|
||||
htmlPreview: "<button>Save</button>",
|
||||
componentName: "SubmitButton",
|
||||
source: {
|
||||
functionName: "SubmitButton",
|
||||
fileName: "/repo/src/Button.tsx",
|
||||
lineNumber: 12,
|
||||
columnNumber: 5,
|
||||
},
|
||||
stack: [
|
||||
{
|
||||
functionName: "SubmitButton",
|
||||
fileName: "/repo/src/Button.tsx",
|
||||
lineNumber: 12,
|
||||
columnNumber: 5,
|
||||
},
|
||||
],
|
||||
styles: ".submit { color: white; }",
|
||||
pickedAt: "2026-05-03T18:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("isPickedElementPayload", () => {
|
||||
it("accepts a complete, well-typed payload", () => {
|
||||
expect(isPickedElementPayload(validPayload())).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts nullable string fields when null", () => {
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({ pageTitle: null, selector: null, componentName: null, source: null }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts an empty stack array", () => {
|
||||
expect(isPickedElementPayload(validPayload({ stack: [] }))).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts stack frames with null fields", () => {
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({
|
||||
stack: [
|
||||
{
|
||||
functionName: null,
|
||||
fileName: null,
|
||||
lineNumber: null,
|
||||
columnNumber: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects null and primitive inputs", () => {
|
||||
expect(isPickedElementPayload(null)).toBe(false);
|
||||
expect(isPickedElementPayload(undefined)).toBe(false);
|
||||
expect(isPickedElementPayload("string")).toBe(false);
|
||||
expect(isPickedElementPayload(42)).toBe(false);
|
||||
expect(isPickedElementPayload([])).toBe(false);
|
||||
});
|
||||
|
||||
it.each<[string, Record<string, unknown>]>([
|
||||
["missing pageUrl", validPayload({ pageUrl: undefined })],
|
||||
["wrong-type pageUrl", validPayload({ pageUrl: 123 })],
|
||||
["missing tagName", validPayload({ tagName: undefined })],
|
||||
["missing htmlPreview", validPayload({ htmlPreview: undefined })],
|
||||
["missing styles", validPayload({ styles: undefined })],
|
||||
["missing pickedAt", validPayload({ pickedAt: undefined })],
|
||||
["wrong-type pageTitle", validPayload({ pageTitle: 99 })],
|
||||
["wrong-type selector", validPayload({ selector: 99 })],
|
||||
["wrong-type componentName", validPayload({ componentName: 99 })],
|
||||
])("rejects payloads with %s", (_label, value) => {
|
||||
expect(isPickedElementPayload(value)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed source frames", () => {
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({
|
||||
source: {
|
||||
functionName: 0,
|
||||
fileName: null,
|
||||
lineNumber: null,
|
||||
columnNumber: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects non-finite numeric line/column numbers", () => {
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({
|
||||
source: {
|
||||
functionName: null,
|
||||
fileName: null,
|
||||
lineNumber: Number.POSITIVE_INFINITY,
|
||||
columnNumber: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({
|
||||
source: {
|
||||
functionName: null,
|
||||
fileName: null,
|
||||
lineNumber: Number.NaN,
|
||||
columnNumber: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed stack arrays", () => {
|
||||
expect(isPickedElementPayload(validPayload({ stack: "not-an-array" }))).toBe(false);
|
||||
expect(isPickedElementPayload(validPayload({ stack: [{ bogus: true }] }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function validAnnotation(overrides?: Record<string, unknown>): Record<string, unknown> {
|
||||
return {
|
||||
id: "annotation_1",
|
||||
pageUrl: "https://example.com/",
|
||||
pageTitle: "Example",
|
||||
comment: "Make this clearer",
|
||||
elements: [
|
||||
{
|
||||
id: "element_1",
|
||||
element: validPayload(),
|
||||
rect: { x: 10, y: 20, width: 100, height: 40 },
|
||||
},
|
||||
],
|
||||
regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }],
|
||||
strokes: [
|
||||
{
|
||||
id: "stroke_1",
|
||||
color: "#7c3aed",
|
||||
width: 4,
|
||||
points: [
|
||||
{ x: 10, y: 10 },
|
||||
{ x: 20, y: 20 },
|
||||
],
|
||||
bounds: { x: 6, y: 6, width: 18, height: 18 },
|
||||
},
|
||||
],
|
||||
styleChanges: [
|
||||
{
|
||||
targetId: "element_1",
|
||||
selector: "button.submit",
|
||||
property: "opacity",
|
||||
previousValue: "1",
|
||||
value: "0.5",
|
||||
},
|
||||
],
|
||||
screenshot: null,
|
||||
createdAt: "2026-06-11T00:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("isPreviewAnnotationPayload", () => {
|
||||
it("accepts a structured annotation draft before screenshot capture", () => {
|
||||
expect(isPreviewAnnotationPayload(validAnnotation())).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects screenshots supplied by the guest preload", () => {
|
||||
expect(isPreviewAnnotationPayload(validAnnotation({ screenshot: { dataUrl: "bad" } }))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects malformed geometry and nested element payloads", () => {
|
||||
expect(
|
||||
isPreviewAnnotationPayload(
|
||||
validAnnotation({ regions: [{ id: "region_1", rect: { x: 0, y: 0, width: "wide" } }] }),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPreviewAnnotationPayload(
|
||||
validAnnotation({ elements: [{ id: "element_1", element: {}, rect: {} }] }),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Strict structural validator for `PickedElementPayload` messages received
|
||||
* from the in-page picker preload (`apps/desktop/src/preview/PickPreload.ts`)
|
||||
* via `wc.ipc`. Lives in its own electron-free module so the validator is
|
||||
* trivially unit-testable.
|
||||
*
|
||||
* Validation must be tight: downstream `normalizeElementContextSelection`
|
||||
* calls `.trim()` on incoming strings, so a malformed payload (preload bug,
|
||||
* future schema mismatch, malicious page that intercepts the preload's IPC
|
||||
* channel via prototype pollution) would otherwise throw deep in the
|
||||
* renderer and the chip silently never appears.
|
||||
*/
|
||||
import type { PickedElementPayload, PreviewAnnotationPayload } from "@t3tools/contracts";
|
||||
|
||||
function isStringOrNull(value: unknown): value is string | null {
|
||||
return value === null || typeof value === "string";
|
||||
}
|
||||
|
||||
function isFiniteNumberOrNull(value: unknown): value is number | null {
|
||||
return value === null || (typeof value === "number" && Number.isFinite(value));
|
||||
}
|
||||
|
||||
function isPickedStackFrame(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const frame = value as Record<string, unknown>;
|
||||
return (
|
||||
isStringOrNull(frame["functionName"]) &&
|
||||
isStringOrNull(frame["fileName"]) &&
|
||||
isFiniteNumberOrNull(frame["lineNumber"]) &&
|
||||
isFiniteNumberOrNull(frame["columnNumber"])
|
||||
);
|
||||
}
|
||||
|
||||
export function isPickedElementPayload(value: unknown): value is PickedElementPayload {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const c = value as Record<string, unknown>;
|
||||
if (typeof c["pageUrl"] !== "string") return false;
|
||||
if (typeof c["tagName"] !== "string") return false;
|
||||
if (typeof c["htmlPreview"] !== "string") return false;
|
||||
if (typeof c["styles"] !== "string") return false;
|
||||
if (typeof c["pickedAt"] !== "string") return false;
|
||||
if (!isStringOrNull(c["pageTitle"])) return false;
|
||||
if (!isStringOrNull(c["selector"])) return false;
|
||||
if (!isStringOrNull(c["componentName"])) return false;
|
||||
if (c["source"] !== null && !isPickedStackFrame(c["source"])) return false;
|
||||
if (!Array.isArray(c["stack"])) return false;
|
||||
if (!c["stack"].every(isPickedStackFrame)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function isRect(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const rect = value as Record<string, unknown>;
|
||||
return ["x", "y", "width", "height"].every(
|
||||
(key) => typeof rect[key] === "number" && Number.isFinite(rect[key]),
|
||||
);
|
||||
}
|
||||
|
||||
function isPoint(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const point = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof point["x"] === "number" &&
|
||||
Number.isFinite(point["x"]) &&
|
||||
typeof point["y"] === "number" &&
|
||||
Number.isFinite(point["y"])
|
||||
);
|
||||
}
|
||||
|
||||
export function isPreviewAnnotationPayload(value: unknown): value is PreviewAnnotationPayload {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const annotation = value as Record<string, unknown>;
|
||||
if (typeof annotation["id"] !== "string") return false;
|
||||
if (typeof annotation["pageUrl"] !== "string") return false;
|
||||
if (!isStringOrNull(annotation["pageTitle"])) return false;
|
||||
if (typeof annotation["comment"] !== "string") return false;
|
||||
if (typeof annotation["createdAt"] !== "string") return false;
|
||||
if (annotation["screenshot"] !== null) return false;
|
||||
|
||||
const elements = annotation["elements"];
|
||||
if (!Array.isArray(elements)) return false;
|
||||
if (
|
||||
!elements.every((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
const target = entry as Record<string, unknown>;
|
||||
return (
|
||||
typeof target["id"] === "string" &&
|
||||
isPickedElementPayload(target["element"]) &&
|
||||
isRect(target["rect"])
|
||||
);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const regions = annotation["regions"];
|
||||
if (!Array.isArray(regions)) return false;
|
||||
if (
|
||||
!regions.every((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
const target = entry as Record<string, unknown>;
|
||||
return typeof target["id"] === "string" && isRect(target["rect"]);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const strokes = annotation["strokes"];
|
||||
if (!Array.isArray(strokes)) return false;
|
||||
if (
|
||||
!strokes.every((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
const target = entry as Record<string, unknown>;
|
||||
return (
|
||||
typeof target["id"] === "string" &&
|
||||
typeof target["color"] === "string" &&
|
||||
typeof target["width"] === "number" &&
|
||||
Number.isFinite(target["width"]) &&
|
||||
Array.isArray(target["points"]) &&
|
||||
target["points"].every(isPoint) &&
|
||||
isRect(target["bounds"])
|
||||
);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const styleChanges = annotation["styleChanges"];
|
||||
if (!Array.isArray(styleChanges)) return false;
|
||||
if (
|
||||
!styleChanges.every((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
const change = entry as Record<string, unknown>;
|
||||
return (
|
||||
typeof change["targetId"] === "string" &&
|
||||
isStringOrNull(change["selector"]) &&
|
||||
typeof change["property"] === "string" &&
|
||||
typeof change["previousValue"] === "string" &&
|
||||
typeof change["value"] === "string"
|
||||
);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractPlaywrightInjectedRuntimeSource,
|
||||
playwrightInjectedRuntimeInstallExpression,
|
||||
playwrightInjectedRuntimeSource,
|
||||
} from "./PlaywrightInjectedRuntime.ts";
|
||||
|
||||
const bundleWithSourceLiteral = (literal: string): string =>
|
||||
`const source3 = ${literal};\n }\n});`;
|
||||
|
||||
describe("playwright injected runtime", () => {
|
||||
effectIt.effect("extracts the pinned runtime from playwright-core", () =>
|
||||
Effect.gen(function* () {
|
||||
const source = yield* playwrightInjectedRuntimeSource();
|
||||
expect(source.length).toBeGreaterThan(100_000);
|
||||
expect(source).toContain("InjectedScript");
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("builds an idempotent install expression", () =>
|
||||
Effect.gen(function* () {
|
||||
const expression = yield* playwrightInjectedRuntimeInstallExpression();
|
||||
expect(expression).toContain("__t3PlaywrightInjected");
|
||||
expect(expression).toContain('testIdAttributeName":"data-testid');
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("reports a missing source marker without an artificial cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource("const source = 'missing';", "/tmp/coreBundle.js"),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceMarkerNotFoundError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
marker: "source3 = ",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps source validation metadata cause-free", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource(
|
||||
bundleWithSourceLiteral('"short"'),
|
||||
"/tmp/coreBundle.js",
|
||||
),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceValidationError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
actualType: "string",
|
||||
actualLength: 5,
|
||||
minimumLength: 100_000,
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("preserves the source evaluation cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource(bundleWithSourceLiteral("("), "/tmp/coreBundle.js"),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceEvaluationError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
timeoutMs: 1_000,
|
||||
cause: expect.objectContaining({ name: "SyntaxError" }),
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
// @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 * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
|
||||
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
|
||||
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
|
||||
const PLAYWRIGHT_SOURCE_MINIMUM_LENGTH = 100_000;
|
||||
const PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS = 1_000;
|
||||
const PLAYWRIGHT_SDK_LANGUAGE = "javascript";
|
||||
const PLAYWRIGHT_BROWSER_NAME = "chromium";
|
||||
|
||||
export class PlaywrightPackageResolveError extends Schema.TaggedErrorClass<PlaywrightPackageResolveError>()(
|
||||
"PlaywrightPackageResolveError",
|
||||
{
|
||||
specifier: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to resolve Playwright package: ${this.specifier}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightCoreBundleReadError extends Schema.TaggedErrorClass<PlaywrightCoreBundleReadError>()(
|
||||
"PlaywrightCoreBundleReadError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read Playwright core bundle: ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceMarkerNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceMarkerNotFoundError>()(
|
||||
"PlaywrightSourceMarkerNotFoundError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
marker: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Playwright injected runtime marker ${JSON.stringify(this.marker)} was not found in ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceTerminatorNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceTerminatorNotFoundError>()(
|
||||
"PlaywrightSourceTerminatorNotFoundError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
terminator: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Playwright injected runtime terminator ${JSON.stringify(this.terminator)} was not found in ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceEvaluationError extends Schema.TaggedErrorClass<PlaywrightSourceEvaluationError>()(
|
||||
"PlaywrightSourceEvaluationError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to evaluate the Playwright injected runtime literal from ${this.bundlePath} within ${this.timeoutMs}ms`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceValidationError extends Schema.TaggedErrorClass<PlaywrightSourceValidationError>()(
|
||||
"PlaywrightSourceValidationError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
actualType: Schema.String,
|
||||
actualLength: Schema.NullOr(Schema.Number),
|
||||
minimumLength: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const actual =
|
||||
this.actualLength === null
|
||||
? this.actualType
|
||||
: `${this.actualType} with ${this.actualLength} characters`;
|
||||
return `Playwright injected runtime from ${this.bundlePath} was ${actual}; expected a string with at least ${this.minimumLength} characters`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightOptionsEncodeError extends Schema.TaggedErrorClass<PlaywrightOptionsEncodeError>()(
|
||||
"PlaywrightOptionsEncodeError",
|
||||
{
|
||||
sdkLanguage: Schema.String,
|
||||
browserName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode ${this.browserName} Playwright injected runtime options for ${this.sdkLanguage}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const PlaywrightInjectedRuntimeError = Schema.Union([
|
||||
PlaywrightPackageResolveError,
|
||||
PlaywrightCoreBundleReadError,
|
||||
PlaywrightSourceMarkerNotFoundError,
|
||||
PlaywrightSourceTerminatorNotFoundError,
|
||||
PlaywrightSourceEvaluationError,
|
||||
PlaywrightSourceValidationError,
|
||||
PlaywrightOptionsEncodeError,
|
||||
]);
|
||||
export type PlaywrightInjectedRuntimeError = typeof PlaywrightInjectedRuntimeError.Type;
|
||||
|
||||
export const extractPlaywrightInjectedRuntimeSource = Effect.fn(
|
||||
"PlaywrightInjectedRuntime.extractSource",
|
||||
)(function* (coreBundle: string, bundlePath: string) {
|
||||
const start = coreBundle.indexOf(PLAYWRIGHT_SOURCE_MARKER);
|
||||
if (start < 0) {
|
||||
return yield* new PlaywrightSourceMarkerNotFoundError({
|
||||
bundlePath,
|
||||
marker: PLAYWRIGHT_SOURCE_MARKER,
|
||||
});
|
||||
}
|
||||
const literalStart = start + PLAYWRIGHT_SOURCE_MARKER.length;
|
||||
const literalEnd = coreBundle.indexOf(PLAYWRIGHT_SOURCE_TERMINATOR, literalStart);
|
||||
if (literalEnd < 0) {
|
||||
return yield* new PlaywrightSourceTerminatorNotFoundError({
|
||||
bundlePath,
|
||||
terminator: PLAYWRIGHT_SOURCE_TERMINATOR,
|
||||
});
|
||||
}
|
||||
const literal = coreBundle.slice(literalStart, literalEnd);
|
||||
const source = yield* Effect.try({
|
||||
try: () =>
|
||||
NodeVM.runInNewContext(literal, Object.create(null), {
|
||||
timeout: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new PlaywrightSourceEvaluationError({
|
||||
bundlePath,
|
||||
timeoutMs: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (typeof source !== "string" || source.length < PLAYWRIGHT_SOURCE_MINIMUM_LENGTH) {
|
||||
return yield* new PlaywrightSourceValidationError({
|
||||
bundlePath,
|
||||
actualType: typeof source,
|
||||
actualLength: typeof source === "string" ? source.length : null,
|
||||
minimumLength: PLAYWRIGHT_SOURCE_MINIMUM_LENGTH,
|
||||
});
|
||||
}
|
||||
return source;
|
||||
});
|
||||
|
||||
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
|
||||
function* () {
|
||||
const packageJsonPath = yield* Effect.try({
|
||||
try: () => require.resolve(PLAYWRIGHT_PACKAGE_SPECIFIER),
|
||||
catch: (cause) =>
|
||||
new PlaywrightPackageResolveError({
|
||||
specifier: PLAYWRIGHT_PACKAGE_SPECIFIER,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const bundlePath = NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js");
|
||||
const coreBundle = yield* Effect.tryPromise({
|
||||
try: () => NodeFSP.readFile(bundlePath, "utf8"),
|
||||
catch: (cause) => new PlaywrightCoreBundleReadError({ bundlePath, cause }),
|
||||
});
|
||||
return yield* extractPlaywrightInjectedRuntimeSource(coreBundle, bundlePath);
|
||||
},
|
||||
);
|
||||
|
||||
export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
|
||||
"PlaywrightInjectedRuntime.installExpression",
|
||||
)(function* () {
|
||||
const source = yield* playwrightInjectedRuntimeSource();
|
||||
const options = yield* encodeUnknownJson({
|
||||
isUnderTest: false,
|
||||
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
|
||||
testIdAttributeName: "data-testid",
|
||||
stableRafCount: 1,
|
||||
browserName: PLAYWRIGHT_BROWSER_NAME,
|
||||
shouldPrependErrorPrefix: false,
|
||||
isUtilityWorld: false,
|
||||
customEngines: [],
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PlaywrightOptionsEncodeError({
|
||||
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
|
||||
browserName: PLAYWRIGHT_BROWSER_NAME,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return `(() => {
|
||||
if (globalThis.__t3PlaywrightInjected) return true;
|
||||
const module = { exports: {} };
|
||||
${source}
|
||||
globalThis.__t3PlaywrightInjected = new (module.exports.InjectedScript())(globalThis, ${options});
|
||||
return true;
|
||||
})()`;
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "./WebviewPreferences.ts";
|
||||
|
||||
/**
|
||||
* Mirrors Electron's webview attribute parser closely enough to catch the
|
||||
* regressions we've already hit:
|
||||
*
|
||||
* - whitespace inside the comma-separated list silently drops keys (so
|
||||
* `" sandbox=true"` becomes an unknown key and Electron falls back to
|
||||
* defaults — re-opening the Node-leak window we closed),
|
||||
* - non-`true`/`false` values (`"yes"`, `"no"`, etc.) are kept as truthy
|
||||
* strings and assigned to a boolean preference, which silently flips
|
||||
* `contextIsolation=no` to ENABLED (then react-grab can't see the React
|
||||
* DevTools hook and componentName resolution always returns null).
|
||||
*
|
||||
* The actual Electron parser does roughly:
|
||||
*
|
||||
* for (const pair of webpreferences.split(',')) {
|
||||
* const [key, value] = pair.split('=');
|
||||
* prefs[key] = value; // value left as a string
|
||||
* }
|
||||
*
|
||||
* then later coerces booleans via `Boolean(value)`. Replicating that here
|
||||
* keeps the test independent of Electron internals while still failing if
|
||||
* we accidentally ship `"contextIsolation=no"` again.
|
||||
*/
|
||||
function parseWebPreferences(input: string): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const pair of input.split(",")) {
|
||||
if (pair !== pair.trim()) {
|
||||
// Electron's parser doesn't trim; surface the bug as undefined-key.
|
||||
out[pair] = pair.split("=")[1];
|
||||
continue;
|
||||
}
|
||||
const [key, value] = pair.split("=");
|
||||
if (!key) continue;
|
||||
out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("PREVIEW_WEBVIEW_PREFERENCES", () => {
|
||||
const parsed = parseWebPreferences(PREVIEW_WEBVIEW_PREFERENCES);
|
||||
|
||||
it("contains exactly the three security-critical keys", () => {
|
||||
expect(Object.keys(parsed).toSorted()).toEqual(
|
||||
["contextIsolation", "nodeIntegration", "sandbox"].toSorted(),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses canonical JS-boolean string literals (not yes/no, on/off, 1/0)", () => {
|
||||
// `value="no"` is a TRUTHY string when assigned to webPreferences.X — so
|
||||
// `contextIsolation="no"` would silently leave isolation ENABLED. Lock
|
||||
// the values to `"true"` / `"false"` so the parser does the right thing.
|
||||
for (const value of Object.values(parsed)) {
|
||||
expect(value).toMatch(/^(true|false)$/);
|
||||
}
|
||||
});
|
||||
|
||||
it("disables context isolation (so react-grab can see the page's React DevTools hook)", () => {
|
||||
expect(parsed["contextIsolation"]).toBe("false");
|
||||
});
|
||||
|
||||
it("keeps the renderer sandbox enabled (so the page cannot reach Node APIs)", () => {
|
||||
expect(parsed["sandbox"]).toBe("true");
|
||||
});
|
||||
|
||||
it("disables nodeIntegration (defense in depth — page never gets Node)", () => {
|
||||
expect(parsed["nodeIntegration"]).toBe("false");
|
||||
});
|
||||
|
||||
it("contains no whitespace (Electron's parser does not trim)", () => {
|
||||
// Electron splits on `,` without trimming, so any whitespace would turn
|
||||
// a key into an unknown one and silently drop the security flag.
|
||||
expect(PREVIEW_WEBVIEW_PREFERENCES).not.toMatch(/\s/);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 1676 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user