Compare commits

..
Author SHA1 Message Date
Theo Browne 11849617ae fold completed turn work in chat history 2026-06-04 18:37:39 -07:00
Julius Marminge 65f080aeef Derive relay URL from API zone in release workflow 2026-06-04 17:55:04 -07:00
Julius Marminge 640dc63eda Separate relay API and tunnel zones 2026-06-04 17:24:57 -07:00
Julius Marmingeandcodex 1bb073742b Refine mobile composer and sheet controls
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:35 -07:00
Julius Marminge 7c7fa6e6c0 Refine mobile new task toolbar labels and focus 2026-06-04 14:03:35 -07:00
Julius Marmingeandcodex 39006ef617 fix(deps): omit unused Clerk wallet integrations
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:35 -07:00
Julius Marmingeandcodex e25cf80506 feat(cloud): add headless cloud CLI control plane (#2905)
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:35 -07:00
Julius Marmingeandcodex 3024b5804e fix(relay): run tests through vite plus
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 97edbcf6ef fix(release): include relay in smoke lockfile fixture
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex d8d5057477 chore(relay): migrate deployment workflow to vite plus
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 4952f36289 chore(relay): refresh pnpm lockfile
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 6699281019 docs(relay): redirect root to API docs
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 445e914580 docs(relay): emit lowercase bearer schemes
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 676360e4a7 docs(relay): describe endpoint authentication schemes
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 47de59eed3 fix(relay): harden cloud lifecycle security
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 231de30606 feat(relay): expose Scalar API docs
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 7b3bc331cc fix(cloud): validate relay URL origins
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 26f36ca992 ci(relay): scope production deploy secrets
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex ab10db22f8 fix(relay): restrict connector egress to managed endpoints
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 2c34b11bbd fix(cloud): spawn relay client without shell
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 175f1737b6 refactor(cloud): clarify agent activity publishing logs
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 820d4e6ad5 refactor(cloud): use relay client runtime wording
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex aaf881ac96 fix(relay): clean up managed endpoints on unlink
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex a7b8af3604 fix(relay): reconcile managed endpoint provisioning
Persist per-user environment allocations and checkpoint Cloudflare resources so retries converge partial provisioning state.

Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex aa866a1e9d refactor(cloud): simplify relay install progress
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex c5a1419fa7 feat(cloud): add relay client install dialog
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 95dc1a525b feat(cloud): stream relay client installation over rpc
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:01 -07:00
Julius Marmingeandcodex 373e9fc504 refactor(cloud): name managed connector relay client
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 321e4b9551 fix(relay): use stable Clerk JWT audience
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 91d650353f fix(relay): keep managed endpoint zone prod-owned
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 14b5817472 fix(relay): name singleton database explicitly
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex d3d36a1d3a fix(relay): read stage from worker stack context
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 56009d5a5b fix(relay): suffix production Axiom resource names
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex fe2e557cc8 fix(relay): scope Axiom resources by stage
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 4d31e08cb4 test(cloud): remove rename-only relay config coverage
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 7cf8d6cdc2 refactor(cloud): keep relay infra config unprefixed
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 4a37834df4 docs(cloud): use canonical CLI OAuth variable
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 8fa897055b refactor(cloud): standardize relay environment prefix
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex a45418a218 feat(cloud): make relay public config opt-in
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex bb92893ee2 docs(relay): clarify deployment environment variables
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 294e8c90df refactor(relay): simplify deploy wiring
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 85c3d4cf5b refactor(relay): deploy stack programmatically
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex ad35d5b9bd refactor(http): use context-backed API clients
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex cf5e6acf1a ci(cloud): stop injecting CLI oauth config into relay
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 58050e8261 feat(cloud): isolate relay resources by stage
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex b40dd17d69 ci(cloud): deploy production relay from main
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex eadcf71a49 feat(cloud): manage cloudflared installation and relay defaults
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 2b5213d920 feat(web): add desktop Clerk-compatible cloud auth UI
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex fd3fff7f19 fix(mobile): keep live activity layout self-contained
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 5e4309dd12 fix(mobile): reconnect saved environments after resume
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex d17343e41b chore(cloud): clarify private beta settings copy
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 6e87a42247 fix(mobile): refresh cloud environment credentials on reconnect
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex fb2d7cca77 refactor(cloud): retain relay queries with atoms
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marmingeandcodex 5d6c25b959 feat(cloud): integrate relay environments and notification settings
Co-authored-by: codex <[email protected]>
2026-06-04 14:03:00 -07:00
Julius Marminge 500939ddb8 rename 2026-06-04 14:02:59 -07:00
Julius Marminge f99454502b chore: update alchemy package to version 2.0.0-beta.49
refactor: remove cloudflare settings from RelayConfigurationShape and related tests

test: clean up tests by removing cloudflare settings from configuration

feat: implement ManagedEndpointDnsClient for DNS operations with Cloudflare

refactor: simplify ManagedEndpointProvider by removing HTTP client dependencies

fix: update ManagedEndpointProvider to use new DNS client for CNAME record management

chore: adjust Api to use new DNS binding and remove deprecated cloudflare settings

refactor: streamline ManagedEndpointZone creation by removing unnecessary token generation
2026-06-04 14:02:59 -07:00
Julius Marminge cb4e5c8e33 renames 2026-06-04 14:02:59 -07:00
Julius Marminge 163ba21b0b fmt 2026-06-04 14:02:59 -07:00
Julius Marminge e1cdcb513a Simplify Cloudflare zone resource mapping 2026-06-04 14:02:59 -07:00
Julius Marminge 2048bcdfbe Flatten relay worker layer graph and managed endpoint bindings 2026-06-04 14:02:59 -07:00
Julius Marminge e07cbab31a Refactor relay bindings for Alchemy Cloudflare integration 2026-06-04 14:02:59 -07:00
Julius Marminge 40e7d88187 Update relay for Alchemy beta.48 and Cloudflare bindings 2026-06-04 14:02:59 -07:00
Julius Marminge b65e22c765 refactor relay/ 2026-06-04 14:02:59 -07:00
Julius Marmingeandcodex 556e893df0 add managed relay tunnels and standards-based auth
Co-authored-by: codex <[email protected]>
2026-06-04 14:02:59 -07:00
1303 changed files with 70842 additions and 101005 deletions

No files matched your search

File renamed without changes.
+1 -1
View File
@@ -3,4 +3,4 @@
- `.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 [Release Checklist](./release.md) for the full release/signing setup checklist.
- See `docs/release.md` for full release/signing setup checklist.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+2 -7
View File
@@ -1,5 +1,5 @@
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Optional: T3 Cloud source builds
# Leave these unset to disable optional T3 Cloud features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
@@ -10,8 +10,3 @@
# 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-...
+46
View File
@@ -60,6 +60,52 @@ 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
+6 -27
View File
@@ -1,4 +1,4 @@
name: Deploy T3 Connect relay
name: Deploy T3 Cloud relay
on:
push:
@@ -8,7 +8,6 @@ on:
permissions:
contents: read
id-token: none
statuses: write
concurrency:
group: relay-production
@@ -44,11 +43,13 @@ jobs:
with:
node-version-file: package.json
cache: true
run-install: true
run-install: false
- name: Install dependencies
run: vp install --frozen-lockfile
- name: Deploy production relay stage
id: deploy
run: vp run --filter t3code-relay deploy --stage prod --yes --github-output
run: vp run --filter t3code-relay deploy -- --stage prod --yes
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
@@ -56,25 +57,3 @@ jobs:
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}`,
});
+1 -81
View File
@@ -167,7 +167,7 @@ jobs:
--github-output
relay_public_config:
name: Resolve T3 Connect public config
name: Resolve T3 Cloud public config
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
@@ -180,46 +180,12 @@ jobs:
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
@@ -306,20 +272,6 @@ 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 }}"
@@ -556,20 +508,6 @@ 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 }}"
@@ -732,20 +670,6 @@ 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 }}"
@@ -792,9 +716,6 @@ jobs:
--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"
)"
@@ -852,7 +773,6 @@ jobs:
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/oxlint-plugin-t3code...
- id: update_versions
name: Update version strings
+2
View File
@@ -0,0 +1,2 @@
[tools]
node = "24.13.1"
+1
View File
@@ -0,0 +1 @@
vp staged
+2 -16
View File
@@ -13,7 +13,7 @@ The file must be a JSON array of rules:
]
```
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](../../packages/contracts/src/keybindings.ts)
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Defaults
@@ -23,12 +23,6 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+shift+j", "command": "preview.toggle" },
{ "key": "mod+r", "command": "preview.refresh", "when": "previewFocus" },
{ "key": "mod+l", "command": "preview.focusUrl", "when": "previewFocus" },
{ "key": "mod+=", "command": "preview.zoomIn", "when": "previewFocus" },
{ "key": "mod+-", "command": "preview.zoomOut", "when": "previewFocus" },
{ "key": "mod+0", "command": "preview.resetZoom", "when": "previewFocus" },
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
@@ -37,7 +31,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
]
```
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](../../apps/server/src/keybindings.ts)
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
## Configuration
@@ -57,12 +51,6 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `preview.toggle`: open/close the in-app browser preview panel (desktop app only)
- `preview.refresh`: reload the active preview tab (in focused preview context by default)
- `preview.focusUrl`: focus the URL input of the preview panel (in focused preview context by default)
- `preview.zoomIn`: zoom the preview viewport in one step (in focused preview context by default)
- `preview.zoomOut`: zoom the preview viewport out one step (in focused preview context by default)
- `preview.resetZoom`: reset the preview zoom to 100% (in focused preview context by default)
- `commandPalette.toggle`: open or close the global command palette
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
@@ -92,8 +80,6 @@ Currently available context keys:
- `terminalFocus`
- `terminalOpen`
- `previewFocus`
- `previewOpen`
Supported operators:
+13 -32
View File
@@ -1,26 +1,23 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
> T3 Code currently supports Codex, Claude, 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@latest
npx t3
```
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:
@@ -49,41 +46,25 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
Observability guide: [docs/observability.md](./docs/observability.md)
## Documentation
Relay observability: [docs/relay-observability.md](./docs/relay-observability.md)
- [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)
T3 Cloud Clerk setup: [docs/t3-cloud-clerk.md](./docs/t3-cloud-clerk.md)
## If you REALLY want to contribute still.... read this first
### Install `vp`
T3 Code uses Vite+ so you'll need to install the global `vp` command-line tool.
#### macOS / Linux
Before local development, prepare the environment and install dependencies:
```bash
curl -fsSL https://vite.plus | bash
# Optional: only needed if you use mise for dev tool management.
mise install
vp install
```
#### 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
```
T3 Cloud is optional and disabled in a fresh clone. To enable it for web, desktop, and mobile source
builds, copy [`.env.example`](./.env.example) to `.env` at the repository root and set the canonical
public configuration there.
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
File renamed without changes.
View File
File renamed without changes.
+4 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.27",
"version": "0.0.24",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -20,17 +20,15 @@
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-updater": "^6.6.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
"vite-plus": "catalog:",
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
@@ -1,40 +0,0 @@
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { compile } from "tailwindcss";
const directory = dirname(fileURLToPath(import.meta.url));
const appRoot = join(directory, "..");
const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = createRequire(import.meta.url);
const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
readFile(sourcePath, "utf8"),
readFile(preloadPath, "utf8"),
readFile(join(tailwindRoot, "theme.css"), "utf8"),
readFile(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 writeFile(outputPath, moduleSource);
+5 -13
View File
@@ -1,13 +1,8 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import * as NodeOS from "node:os";
import { join } from "node:path";
import {
desktopDir,
resolveDevProtocolClient,
resolveElectronLaunchCommand,
} from "./electron-launcher.mjs";
import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
@@ -34,8 +29,6 @@ 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,
@@ -60,7 +53,7 @@ const expectedExits = new WeakSet();
const watchers = [];
function killChildTreeByPid(pid, signal) {
if (hostPlatform === "win32" || typeof pid !== "number") {
if (process.platform === "win32" || typeof pid !== "number") {
return;
}
@@ -68,7 +61,7 @@ function killChildTreeByPid(pid, signal) {
}
function cleanupStaleDevApps() {
if (hostPlatform === "win32") {
if (process.platform === "win32") {
return;
}
@@ -86,8 +79,7 @@ function startApp() {
const launchArgs = devProtocolClient
? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const electronCommand = resolveElectronLaunchCommand(launchArgs);
const app = spawn(electronCommand.electronPath, electronCommand.args, {
const app = spawn(resolveElectronPath(), launchArgs, {
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
@@ -197,7 +189,7 @@ function startWatchers() {
}
function killChildTree(signal) {
if (hostPlatform === "win32") {
if (process.platform === "win32") {
return;
}
+4 -44
View File
@@ -14,7 +14,6 @@ import {
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import * as NodeOS from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
@@ -31,11 +30,9 @@ 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 = 11;
const LAUNCHER_VERSION = 10;
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
const hostPlatform = NodeOS.platform();
function resolveDevelopmentProtocolCallbackPort() {
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
@@ -298,11 +295,7 @@ function buildMacLauncher(electronBinaryPath) {
}
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).
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
@@ -314,54 +307,21 @@ function buildMacLauncher(electronBinaryPath) {
return targetBinaryPath;
}
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
if (hostPlatform !== "linux") {
return true;
}
const sandboxPath = join(dirname(electronBinaryPath), "chrome-sandbox");
try {
const sandboxStat = 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 electronBinaryPath = require("electron");
if (hostPlatform !== "darwin") {
if (process.platform !== "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) {
if (process.platform !== "darwin" || !isDevelopment) {
return null;
}
@@ -1,17 +1,13 @@
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { arch, platform, tmpdir } from "node:os";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
const require = createRequire(import.meta.url);
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostPlatform = platform();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostArch = arch();
function getPlatformPath() {
switch (hostPlatform) {
switch (process.platform) {
case "darwin":
return "Electron.app/Contents/MacOS/Electron";
case "freebsd":
@@ -21,12 +17,12 @@ function getPlatformPath() {
case "win32":
return "electron.exe";
default:
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
}
}
function ensureExecutable(filePath) {
if (hostPlatform !== "win32") {
if (process.platform !== "win32") {
chmodSync(filePath, 0o755);
}
}
@@ -43,7 +39,7 @@ function repairPathFile(electronDir, platformPath) {
function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [join(electronDir, "dist", platformPath)];
if (hostPlatform === "darwin") {
if (process.platform === "darwin") {
paths.push(
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
join(
@@ -62,7 +58,7 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
}
function isMachO(filePath) {
if (hostPlatform !== "darwin") {
if (process.platform !== "darwin") {
return true;
}
@@ -80,7 +76,7 @@ function missingRuntimePaths(electronDir, platformPath) {
}
function invalidRuntimePaths(electronDir, platformPath) {
if (hostPlatform !== "darwin") {
if (process.platform !== "darwin") {
return [];
}
@@ -115,16 +111,16 @@ function runChecked(command, args) {
function installElectronRuntime(electronDir, version) {
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
try {
runChecked("curl", [
"-fsSL",
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
"-o",
zipPath,
]);
if (hostPlatform === "darwin") {
if (process.platform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
} else {
runChecked("python3", [
+2 -3
View File
@@ -1,16 +1,15 @@
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const __dirname = 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");
console.log("\nLaunching Electron smoke test...");
const electronCommand = resolveElectronLaunchCommand([mainJs]);
const child = spawn(electronCommand.electronPath, electronCommand.args, {
const child = spawn(electronBin, [mainJs], {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
+2 -3
View File
@@ -1,12 +1,11 @@
import { spawn } from "node:child_process";
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
const child = spawn(electronCommand.electronPath, electronCommand.args, {
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+1 -1
View File
@@ -176,7 +176,7 @@ const bootstrap = Effect.gen(function* () {
);
}
yield* installDesktopIpcHandlers();
yield* installDesktopIpcHandlers;
yield* logBootstrapInfo("bootstrap ipc handlers registered");
if (!(yield* Ref.get(state.quitting))) {
+1 -1
View File
@@ -52,7 +52,7 @@ const make = Effect.gen(function* () {
Effect.map((parsed) =>
Option.fromNullishOr(parsed.t3codeCommitHash).pipe(Option.flatMap(normalizeCommitHash)),
),
Effect.orElseSucceed(() => Option.none<string>()),
Effect.catch(() => Effect.succeed(Option.none<string>())),
),
});
});
+1 -1
View File
@@ -49,7 +49,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = environment.developmentDockIconPath;
const developmentDockIconExists = yield* fileSystem
.exists(developmentDockIconPath)
@@ -1,297 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
const decodeConnectionCatalog = Schema.decodeEffect(
Schema.fromJsonString(ConnectionCatalogDocument),
);
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
decryptString: (value) => {
return Effect.gen(function* () {
const decoded = textDecoder.decode(value);
if (
!decoded.startsWith("encrypted:") ||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
) {
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted catalog"),
});
}
return decoded.slice("encrypted:".length);
});
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
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.DesktopConnectionCatalogStoreReadError,
);
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}/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.cause, permissionError);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
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, ElectronSafeStorage.ElectronSafeStorageDecryptError);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
@@ -1,328 +0,0 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionTarget,
RelayConnectionTarget,
SshConnectionProfile,
SshConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
} from "@t3tools/client-runtime/platform";
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as 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,
);
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
"DesktopConnectionCatalogStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
"DesktopConnectionCatalogStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode the desktop connection catalog.";
}
}
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
"DesktopConnectionCatalogStoreReadError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
"DesktopConnectionCatalogStoreMigrationError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to migrate legacy desktop saved environments.";
}
}
export interface DesktopConnectionCatalogStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
| DesktopConnectionCatalogStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
DesktopConnectionCatalogStoreShape
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
catalogPath: string,
): Effect.Effect<
Option.Option<EncryptedConnectionCatalogDocument>,
PlatformError.PlatformError | Schema.SchemaError
> =>
fileSystem.readFileString(catalogPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
),
);
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, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* Effect.gen(function* () {
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.catalogPath);
}).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.DesktopSavedEnvironmentsShape,
): Effect.fn.Return<
RuntimeConnectionCatalogDocumentType,
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
> {
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);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
credential: new BearerConnectionCredential({ token: token.value }),
});
}
}
return {
schemaVersion: 1,
targets,
profiles,
credentials,
remoteDpopTokens: [],
};
});
export const layer = Layer.effect(
DesktopConnectionCatalogStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry;
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
yield* writeCatalog(encoded);
return Option.some(encoded);
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
);
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
Effect.flatMap(safeStorage.decryptString),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
error,
}),
),
Effect.withSpan("desktop.connectionCatalogStore.clear"),
),
});
}),
);
@@ -59,7 +59,6 @@ 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");
@@ -90,7 +89,6 @@ 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");
}),
);
@@ -49,7 +49,6 @@ export interface DesktopEnvironmentShape {
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
@@ -184,7 +183,6 @@ 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"),
@@ -64,13 +64,6 @@ 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({
dirname: "/repo/apps/desktop/src",
@@ -93,7 +86,6 @@ function makeLayer(input: {
readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces;
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
@@ -105,7 +97,7 @@ function makeLayer(input: {
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
Layer.provideMerge(mockSpawnerLayer()),
Layer.provideMerge(networkLayer),
Layer.provideMerge(DesktopConfig.layerTest(env)),
Layer.provideMerge(environmentLayer),
@@ -124,23 +116,13 @@ const withHarness = <A, E, R>(
| DesktopAppSettings.DesktopAppSettings
>,
env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
) =>
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,
...(spawnerLayer ? { spawnerLayer } : {}),
}),
),
);
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopServerExposure", () => {
@@ -257,27 +239,6 @@ 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,
@@ -12,7 +12,6 @@ import type {
} from "@t3tools/contracts";
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";
@@ -23,11 +22,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
@@ -416,18 +412,6 @@ const make = Effect.gen(function* () {
const desktopSettings = yield* DesktopAppSettingsService.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));
@@ -532,20 +516,11 @@ 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),
@@ -104,25 +104,6 @@ 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",
() =>
@@ -105,11 +105,6 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
readonly servePort?: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
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[],
@@ -117,18 +112,15 @@ 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* readDnsName
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(null)),
)
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.orElseSucceed(() => null),
Effect.catch(() => Effect.succeed(null)),
)
: null;
const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({
+94 -106
View File
@@ -5,7 +5,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
export interface ElectronMenuPosition {
readonly x: number;
@@ -45,12 +44,6 @@ 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,
@@ -80,114 +73,109 @@ 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.effect(
ElectronMenu,
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache;
}
try {
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
}
export const layer = Layer.sync(ElectronMenu, () => {
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (process.platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache;
};
}
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
try {
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
width: 12,
height: 12,
});
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
}
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return destructiveMenuIconCache;
};
const itemOption: Electron.MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children, complete);
} else {
itemOption.click = () => complete(Option.some(item.id));
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (Option.isSome(destructiveIcon)) {
itemOption.icon = destructiveIcon.value;
}
}
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
template.push(itemOption);
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return template;
};
const itemOption: Electron.MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children, complete);
} else {
itemOption.click = () => complete(Option.some(item.id));
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (Option.isSome(destructiveIcon)) {
itemOption.icon = destructiveIcon.value;
}
}
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
if (normalizedItems.length === 0) {
resume(Effect.succeed(Option.none()));
template.push(itemOption);
}
return template;
};
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
if (normalizedItems.length === 0) {
resume(Effect.succeed(Option.none()));
return;
}
let completed = false;
const complete = (selectedItemId: Option.Option<string>) => {
if (completed) {
return;
}
completed = true;
resume(Effect.succeed(selectedItemId));
};
let completed = false;
const complete = (selectedItemId: Option.Option<string>) => {
if (completed) {
return;
}
completed = true;
resume(Effect.succeed(selectedItemId));
};
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
}),
});
}),
);
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
}),
});
});
@@ -1,9 +1,9 @@
import * as Electron from "electron";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
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 Electron from "electron";
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
"ElectronSafeStorageAvailabilityError",
+1 -3
View File
@@ -6,7 +6,6 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
readonly cause: unknown;
@@ -38,7 +37,6 @@ export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWind
) {}
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(
@@ -100,7 +98,7 @@ const make = Effect.gen(function* () {
window.show();
}
if (platform === "darwin") {
if (process.platform === "darwin") {
Electron.app.focus({ steal: true });
}
+13 -14
View File
@@ -10,10 +10,12 @@ import {
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
clearConnectionCatalog,
getConnectionCatalog,
setConnectionCatalog,
} from "./methods/connectionCatalog.ts";
getSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
setSavedEnvironmentRegistry,
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
import {
getAdvertisedEndpoints,
getServerExposureState,
@@ -46,20 +48,20 @@ import {
setTheme,
showContextMenu,
} from "./methods/window.ts";
import * as PreviewIpc from "./methods/preview.ts";
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
export const installDesktopIpcHandlers = Effect.gen(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getConnectionCatalog);
yield* ipc.handle(setConnectionCatalog);
yield* ipc.handle(clearConnectionCatalog);
yield* ipc.handle(getSavedEnvironmentRegistry);
yield* ipc.handle(setSavedEnvironmentRegistry);
yield* ipc.handle(getSavedEnvironmentSecret);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
@@ -90,7 +92,4 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(downloadUpdate);
yield* ipc.handle(installUpdate);
yield* ipc.handle(checkForUpdate);
for (const previewMethod of PreviewIpc.methods) {
yield* ipc.handle(previewMethod);
}
});
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
+5 -38
View File
@@ -20,9 +20,11 @@ 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_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
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 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";
@@ -37,38 +39,3 @@ 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";
+43 -35
View File
@@ -1,35 +1,29 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { afterEach } from "vite-plus/test";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { afterEach } from "vitest";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const originalFetch = globalThis.fetch;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
const calls: Array<FetchCall> = [];
let responseIndex = 0;
const fetchFn = ((input, init) => {
calls.push([input, init ?? {}]);
const response = responses[responseIndex++];
if (!response) {
return Promise.reject(new Error("Unexpected fetch call"));
}
return Promise.resolve(response);
}) satisfies typeof fetch;
return { fetchFn, calls };
};
function makeHttpClientLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
);
}
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
@@ -39,8 +33,16 @@ describe("Desktop cloud auth IPC", () => {
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "sign_in_attempt" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -53,25 +55,32 @@ describe("Desktop cloud auth IPC", () => {
body,
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert(forwardedRequest !== null);
assert.equal(
new Headers(init.headers).get("content-type"),
forwardedRequest.headers["content-type"],
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
assert.equal(forwardedRequest.body._tag, "Uint8Array");
if (forwardedRequest.body._tag === "Uint8Array") {
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
}
}).pipe(Effect.provide(layer));
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "client" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -80,10 +89,9 @@ describe("Desktop cloud auth IPC", () => {
headers: {},
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
assert(forwardedRequest !== null);
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
}).pipe(Effect.provide(layer));
},
);
+43 -66
View File
@@ -8,11 +8,9 @@ import {
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
@@ -54,68 +52,6 @@ export function validateClerkFrontendApiUrl(rawUrl: string): URL {
return url;
}
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
return Effect.gen(function* () {
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(Object.fromEntries(headers.entries())),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
HttpClient.execute,
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed to execute.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
});
}
const electronNetFetchLayer = Layer.unwrap(
Effect.gen(function* () {
const electronFetch = yield* Effect.promise(async () => {
const electron = (await import("electron")) as {
readonly net?: { readonly fetch?: typeof globalThis.fetch };
};
return typeof electron.net?.fetch === "function"
? electron.net.fetch.bind(electron.net)
: null;
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
if (!electronFetch) {
yield* Effect.logWarning(
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
);
}
return FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
);
}),
);
export const createCloudAuthRequest = makeIpcMethod({
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
payload: Schema.Void,
@@ -172,6 +108,47 @@ export const fetchCloudAuth = makeIpcMethod({
}),
});
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
url,
{
headers: input.headers,
},
);
const request =
input.body === undefined
? requestWithoutBody
: HttpClientRequest.bodyText(
requestWithoutBody,
input.body,
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
);
const response = yield* HttpClient.execute(request).pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
}),
});
@@ -1,37 +0,0 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getConnectionCatalog = 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 = 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 = 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;
}),
});
@@ -1,54 +0,0 @@
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();
},
),
);
});
-377
View File
@@ -1,377 +0,0 @@
import {
DesktopPreviewAnnotationThemeInputSchema,
DesktopPreviewArtifactInputSchema,
DesktopPreviewAutomationClickInputSchema,
DesktopPreviewAutomationEvaluateInputSchema,
DesktopPreviewAutomationPressInputSchema,
DesktopPreviewAutomationScrollInputSchema,
DesktopPreviewAutomationTypeInputSchema,
DesktopPreviewAutomationWaitForInputSchema,
DesktopPreviewConfigInputSchema,
DesktopPreviewNavigateInputSchema,
DesktopPreviewRecordingArtifactSchema,
DesktopPreviewRecordingSaveInputSchema,
DesktopPreviewRegisterWebviewInputSchema,
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationPayloadSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { pathToFileURL } from "node:url";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(channel, ...args);
}
}
};
export const installPreviewEventForwarding = Effect.fn(
"desktop.ipc.preview.installEventForwarding",
)(function* () {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.subscribeStateChanges((tabId, state) => {
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
});
yield* manager.subscribeRecordingFrames((frame) => {
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
});
yield* manager.subscribePointerEvents((event) => {
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
});
});
export const createTab = 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 = 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 = 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 = 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.PreviewManagerShape,
tabId: string,
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
) =>
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 = 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 = 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 = 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: pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
};
}),
});
export const setAnnotationTheme = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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;
@@ -0,0 +1,76 @@
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
const NonBlankString = Schema.String.check(
Schema.makeFilter((value) =>
value.trim().length > 0 ? undefined : "Expected a non-empty string",
),
);
const SetSavedEnvironmentSecretInput = Schema.Struct({
environmentId: EnvironmentId,
secret: NonBlankString,
});
export const getSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: Schema.Void,
result: SavedEnvironmentRegistryPayload,
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.getRegistry;
}),
});
export const setSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: SavedEnvironmentRegistryPayload,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry(records);
}),
});
export const getSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
}),
});
export const setSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: SetSavedEnvironmentSecretInput,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
environmentId,
secret,
}) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.setSecret({
environmentId,
secret,
});
}),
});
export const removeSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.removeSecret(environmentId);
}),
});
@@ -1,11 +1,11 @@
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
} from "@t3tools/client-runtime";
import {
EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema,
+4 -18
View File
@@ -9,7 +9,6 @@ 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" };
@@ -29,7 +28,6 @@ import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
@@ -46,8 +44,6 @@ 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 PreviewBrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
const desktopEnvironmentLayer = Layer.unwrap(
@@ -55,13 +51,11 @@ 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,
processArch,
platform: process.platform,
processArch: process.arch,
...metadata,
});
}),
@@ -118,7 +112,7 @@ const desktopFoundationLayer = Layer.mergeAll(
DesktopLifecycle.layerShutdown,
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopSavedEnvironments.layer,
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
@@ -133,15 +127,7 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
Layer.provideMerge(desktopFoundationLayer),
);
const desktopPreviewLayer = PreviewManager.layer.pipe(
Layer.provideMerge(PreviewBrowserSession.layer),
Layer.provideMerge(desktopFoundationLayer),
);
const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopServerExposureLayer),
Layer.provideMerge(desktopPreviewLayer),
);
const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer));
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
+11 -103
View File
@@ -1,9 +1,4 @@
import type {
DesktopBridge,
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import type { DesktopBridge } from "@t3tools/contracts";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
@@ -42,10 +37,16 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
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),
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),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
@@ -140,97 +141,4 @@ 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);
-1
View File
@@ -1 +0,0 @@
import "./preview/PickPreload.ts";
-68
View File
@@ -1,68 +0,0 @@
@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;
}
@@ -1,3 +0,0 @@
// 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
@@ -1,83 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { 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("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)),
);
});
-107
View File
@@ -1,107 +0,0 @@
import type { Session } from "electron";
import { session } from "electron";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as SynchronizedRef from "effect/SynchronizedRef";
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
readonly operation: string;
readonly cause: unknown;
}> {
override get message() {
return `Desktop preview browser session operation failed: ${this.operation}`;
}
}
export interface BrowserSessionShape {
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
readonly isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
}
export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
"@t3tools/desktop/preview/BrowserSession",
) {}
const make = Effect.gen(function* BrowserSessionMake() {
const crypto = yield* Crypto.Crypto;
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
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 BrowserSessionError({ operation: "getPartition", 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 BrowserSessionError({ operation: "getSession", 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.values()].map((browserSession) =>
Effect.tryPromise({
try: () =>
browserSession.clearStorageData({
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
}),
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
}),
),
{ concurrency: "unbounded", discard: true },
);
}),
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.values()].map((browserSession) =>
Effect.tryPromise({
try: () => browserSession.clearCache(),
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
}),
),
{ concurrency: "unbounded", discard: true },
);
}),
});
}).pipe(Effect.withSpan("BrowserSession.make"));
export const layer = Layer.effect(BrowserSession, make);
@@ -1,6 +0,0 @@
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";
-475
View File
@@ -1,475 +0,0 @@
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 Option from "effect/Option";
import * as Path from "effect/Path";
import type * as Scope from "effect/Scope";
import { TestClock } from "effect/testing";
import { beforeEach, describe, expect, vi } from "vite-plus/test";
import * as DesktopEnvironment from "../app/DesktopEnvironment.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(() => ({ 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.DesktopEnvironmentShape),
);
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 withManager = <A>(
use: (
manager: PreviewManager.PreviewManagerShape,
) => 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("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$/,
);
}),
),
);
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.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
});
}),
),
);
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.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
});
}),
),
);
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) => 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.cause).toMatchObject({
name: "PreviewAutomationControlInterruptedError",
});
}),
),
);
});
File diff suppressed because it is too large. Load diff
@@ -1,46 +0,0 @@
/**
* 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 };
}
@@ -1,86 +0,0 @@
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
@@ -1,201 +0,0 @@
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);
});
});
@@ -1,146 +0,0 @@
/**
* 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;
}
@@ -1,26 +0,0 @@
import { it as effectIt } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { describe, expect } from "vite-plus/test";
import {
playwrightInjectedRuntimeInstallExpression,
playwrightInjectedRuntimeSource,
} from "./PlaywrightInjectedRuntime.ts";
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');
}),
);
});
@@ -1,90 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection.
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { runInNewContext } from "node:vm";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
"PlaywrightInjectedRuntimeError",
)<{
readonly operation: string;
readonly cause: unknown;
}> {
override get message() {
return `Playwright injected runtime operation failed: ${this.operation}`;
}
}
const fail = (operation: string, cause: unknown) =>
new PlaywrightInjectedRuntimeError({ operation, cause });
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
function* () {
const packageJsonPath = yield* Effect.try({
try: () => require.resolve("playwright-core/package.json"),
catch: (cause) => fail("resolvePackage", cause),
});
const coreBundle = yield* Effect.tryPromise({
try: () => readFile(join(dirname(packageJsonPath), "lib/coreBundle.js"), "utf8"),
catch: (cause) => fail("readCoreBundle", cause),
});
const marker = "source3 = ";
const start = coreBundle.indexOf(marker);
if (start < 0) {
return yield* fail(
"findSourceMarker",
new Error("Playwright injected runtime marker was not found."),
);
}
const literalStart = start + marker.length;
const literalEnd = coreBundle.indexOf(";\n }\n});", literalStart);
if (literalEnd < 0) {
return yield* fail(
"findSourceTerminator",
new Error("Playwright injected runtime terminator was not found."),
);
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () => runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
catch: (cause) => fail("evaluateSourceLiteral", cause),
});
if (typeof source !== "string" || source.length < 100_000) {
return yield* fail(
"validateSource",
new Error("Playwright injected runtime extraction returned invalid source."),
);
}
return source;
},
);
export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
"PlaywrightInjectedRuntime.installExpression",
)(function* () {
const source = yield* playwrightInjectedRuntimeSource();
const options = yield* encodeUnknownJson({
isUnderTest: false,
sdkLanguage: "javascript",
testIdAttributeName: "data-testid",
stableRafCount: 1,
browserName: "chromium",
shouldPrependErrorPrefix: false,
isUtilityWorld: false,
customEngines: [],
}).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
return `(() => {
if (globalThis.__t3PlaywrightInjected) return true;
const module = { exports: {} };
${source}
globalThis.__t3PlaywrightInjected = new (module.exports.InjectedScript())(globalThis, ${options});
return true;
})()`;
});
@@ -1,78 +0,0 @@
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/);
});
});
@@ -1,42 +0,0 @@
/**
* webPreferences override applied to every preview `<webview>` element via
* its `webpreferences="..."` attribute. Single source of truth so all guest
* surfaces inherit the same security posture.
*
* Lives in its own electron-free module so the value is unit-testable
* without importing `Manager.ts` (which transitively imports
* `electron` and blows up under vitest).
*
* - `contextIsolation=false`: the picker preload needs to share `globalThis`
* with the page so react-grab/bippy can read the React DevTools hook
* (`__REACT_DEVTOOLS_GLOBAL_HOOK__`) and resolve component names. Without
* this every pick comes back with `componentName: null` even on dev React
* apps.
* - `sandbox=true`: keeps the OS-level renderer sandbox enabled. Critical
* when paired with `contextIsolation=false` — without sandbox, the preload
* has full Node access (`require`, `fs`, `child_process`, ...) and that
* `require` would land on the page's shared `globalThis`, giving any
* third-party page in the preview full Node + IPC access to the host.
* In sandboxed mode Electron still synthesizes the `electron` module for
* the preload's `import { ipcRenderer }` line, but no Node globals leak.
* - `nodeIntegration=false`: pinned for clarity (the page itself never gets
* Node access).
*
* Format notes (locked down by `WebviewPreferences.test.ts`):
* - Whitespace-free. Electron's webpreferences parser splits on `,` and
* does not trim, so a leading space would turn a key into an unknown one
* and silently drop it.
* - Values are JS-boolean strings (`true`/`false`) — `yes`/`no` are not
* special-cased by the parser; `value="no"` becomes the truthy STRING
* `"no"` when assigned to a boolean webPreferences key. Most critically,
* `contextIsolation="no"` is truthy → contextIsolation stays ENABLED →
* react-grab can't see the React DevTools hook.
*
* Defense in depth: `apps/desktop/src/main.ts` also runs a
* `will-attach-webview` handler that force-sets `sandbox: true` and
* `nodeIntegration*: false` on the actual webPreferences object, gated on
* the preview partition, so even if this string is ever wrong, the
* security-critical flags can't regress on preview tabs.
*/
export const PREVIEW_WEBVIEW_PREFERENCES =
"contextIsolation=false,sandbox=true,nodeIntegration=false";
@@ -209,7 +209,7 @@ function readSettings(
onSome: (raw) =>
decodeDesktopSettingsJson(raw).pipe(
Effect.map((parsed) => normalizeDesktopSettingsDocument(parsed, appVersion)),
Effect.orElseSucceed(() => defaultSettings),
Effect.catch(() => Effect.succeed(defaultSettings)),
),
}),
),
@@ -63,7 +63,7 @@ const readClientSettings = (
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
Effect.catch(() => Effect.succeed(Option.none<ClientSettings>())),
),
}),
),
@@ -272,26 +272,6 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
});
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
}),
),
);
it.effect("treats empty saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
@@ -309,7 +289,7 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("surfaces malformed saved environment documents", () =>
it.effect("treats malformed saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -318,15 +298,10 @@ describe("DesktopSavedEnvironments", () => {
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
assert.instanceOf(
registryError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
const secretError = yield* savedEnvironments
.getSecret(savedRegistryRecord.environmentId)
.pipe(Effect.flip);
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
}),
),
);
@@ -82,16 +82,6 @@ export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
}
}
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
"DesktopSavedEnvironmentsReadError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop saved environments: ${this.cause.message}`;
}
}
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
"DesktopSavedEnvironmentSecretDecodeError",
)<{
@@ -103,7 +93,6 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
}
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
@@ -114,16 +103,10 @@ export type DesktopSavedEnvironmentsSetSecretError =
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
export interface DesktopSavedEnvironmentsShape {
readonly getRegistry: Effect.Effect<
readonly PersistedSavedEnvironmentRecord[],
DesktopSavedEnvironmentsReadError
>;
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>;
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly removeEnvironment: (
environmentId: string,
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly getSecret: (
environmentId: string,
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
@@ -193,20 +176,18 @@ function normalizeSavedEnvironmentRegistryDocument(
function readRegistryDocument(
fileSystem: FileSystem.FileSystem,
registryPath: string,
): Effect.Effect<
SavedEnvironmentRegistryDocument,
PlatformError.PlatformError | Schema.SchemaError
> {
): Effect.Effect<SavedEnvironmentRegistryDocument> {
return fileSystem.readFileString(registryPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed({ version: 1, records: [] })
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed({ version: 1, records: [] }),
onSome: (raw) =>
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.catch(() => Effect.succeed({ version: 1, records: [] })),
),
}),
),
);
}
@@ -286,39 +267,21 @@ export const layer = Layer.effect(
Effect.map((document) =>
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
),
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
const currentDocument = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (!document.records.some((record) => record.environmentId === environmentId)) {
return;
}
yield* writeDocument({
version: document.version,
records: document.records.filter((record) => record.environmentId !== environmentId),
});
},
),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
);
const encoded = Option.fromNullishOr(
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
@@ -336,7 +299,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
@@ -368,7 +331,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
if (
!document.records.some(
(record) =>
@@ -405,18 +368,6 @@ export const layerTest = (input?: {
return DesktopSavedEnvironments.of({
getRegistry: Ref.get(recordsRef),
setRegistry: (records) => Ref.set(recordsRef, records),
removeEnvironment: (environmentId) =>
Ref.update(recordsRef, (records) =>
records.filter((record) => record.environmentId !== environmentId),
).pipe(
Effect.andThen(
Ref.update(secretsRef, (secrets) => {
const nextSecrets = new Map(secrets);
nextSecrets.delete(environmentId);
return nextSecrets;
}),
),
),
getSecret: (environmentId) =>
Ref.get(secretsRef).pipe(
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
@@ -196,7 +196,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
.pipe(
Effect.timeoutOption(input.timeout),
Effect.map(Option.getOrElse(() => "")),
Effect.orElseSucceed(() => ""),
Effect.catch(() => Effect.succeed("")),
);
});
@@ -241,6 +241,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
const output = yield* runCommandOutput({
command,
args,
shell: true,
timeout: LOGIN_SHELL_TIMEOUT,
});
const environment = extractEnvironment(output, names);
+1 -1
View File
@@ -120,7 +120,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
return decodeAppUpdateYmlConfig(entries).pipe(
Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
Effect.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
);
}
+2 -33
View File
@@ -8,17 +8,6 @@ import * as Ref from "effect/Ref";
import type * as Electron from "electron";
import { vi } from "vite-plus/test";
vi.mock("electron", async (importOriginal) => ({
...(await importOriginal<typeof import("electron")>()),
session: {
fromPartition: vi.fn(() => ({
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/1.2.3"),
setPermissionRequestHandler: vi.fn(),
setUserAgent: vi.fn(),
})),
},
}));
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -29,7 +18,6 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
const environmentInput = {
dirname: "/repo/apps/desktop/dist-electron",
@@ -68,7 +56,6 @@ function makeFakeBrowserWindow() {
once: vi.fn(),
restore: vi.fn(),
setBackgroundColor: vi.fn(),
setAutoHideCursor: vi.fn(),
setTitle: vi.fn(),
setTitleBarOverlay: vi.fn(),
show: vi.fn(),
@@ -79,7 +66,6 @@ function makeFakeBrowserWindow() {
window: window as unknown as Electron.BrowserWindow,
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
};
}
@@ -136,17 +122,10 @@ function makeTestLayer(input: {
readonly window: Electron.BrowserWindow;
readonly createCount: Ref.Ref<number>;
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
readonly openedExternalUrls?: unknown[];
}) {
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
create: (options) =>
Effect.sync(() => {
input.createdWindowOptions?.push(options);
}).pipe(
Effect.andThen(Ref.update(input.createCount, (count) => count + 1)),
Effect.as(input.window),
),
create: () => Ref.update(input.createCount, (count) => count + 1).pipe(Effect.as(input.window)),
main: Ref.get(input.mainWindow),
currentMainOrFirst: Ref.get(input.mainWindow),
focusedMainOrFirst: Ref.get(input.mainWindow),
@@ -176,12 +155,6 @@ function makeTestLayer(input: {
} satisfies ElectronShell.ElectronShellShape),
electronThemeLayer,
electronWindowLayer,
Layer.mock(PreviewManager.PreviewManager)({
getBrowserSession: () => Effect.succeed({} as Electron.Session),
setMainWindow: () => Effect.void,
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
}),
),
),
);
@@ -192,7 +165,7 @@ describe("DesktopWindow", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/connections",
navigationUrl: "http://127.0.0.1:3773/settings/cloud",
}),
);
assert.isFalse(
@@ -214,12 +187,10 @@ describe("DesktopWindow", () => {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
createdWindowOptions,
});
yield* Effect.gen(function* () {
@@ -229,8 +200,6 @@ describe("DesktopWindow", () => {
yield* desktopWindow.handleBackendReady;
assert.equal(yield* Ref.get(createCount), 1);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["http://127.0.0.1:5733/"]);
assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
}).pipe(Effect.provide(layer));
+11 -42
View File
@@ -11,7 +11,6 @@ import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as PreviewManager from "../preview/Manager.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
@@ -37,8 +36,7 @@ type DesktopWindowRuntimeServices =
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
| ElectronWindow.ElectronWindow
| PreviewManager.PreviewManager;
| ElectronWindow.ElectronWindow;
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
"DesktopWindowDevServerUrlMissingError",
@@ -50,8 +48,7 @@ export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
export type DesktopWindowError =
| DesktopWindowDevServerUrlMissingError
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
| ElectronWindow.ElectronWindowCreateError;
export interface DesktopWindowShape {
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
@@ -82,10 +79,9 @@ function resolveDesktopDevServerUrl(
function getIconOption(
iconPaths: DesktopAssets.DesktopIconPaths,
platform: NodeJS.Platform,
): { icon: string } | Record<string, never> {
if (platform === "darwin") return {}; // macOS uses .icns from app bundle
const ext = platform === "win32" ? "ico" : "png";
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
const ext = process.platform === "win32" ? "ico" : "png";
return Option.match(iconPaths[ext], {
onNone: () => ({}),
onSome: (icon) => ({ icon }),
@@ -107,11 +103,8 @@ export function isSameOriginRendererNavigation(input: {
}
}
function getWindowTitleBarOptions(
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
): WindowTitleBarOptions {
if (platform === "darwin") {
function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
if (process.platform === "darwin") {
return {
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
@@ -131,7 +124,6 @@ function getWindowTitleBarOptions(
function syncWindowAppearance(
window: Electron.BrowserWindow,
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
): Effect.Effect<void> {
return Effect.sync(() => {
if (window.isDestroyed()) {
@@ -139,7 +131,7 @@ function syncWindowAppearance(
}
window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors);
if (typeof titleBarOverlay === "object") {
window.setTitleBarOverlay(titleBarOverlay);
}
@@ -170,7 +162,6 @@ const make = Effect.gen(function* () {
const electronShell = yield* ElectronShell.ElectronShell;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
@@ -179,12 +170,11 @@ const make = Effect.gen(function* () {
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
backendHttpUrl: URL,
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
yield* previewManager.getBrowserSession();
const applicationUrl = environment.isDevelopment
? yield* resolveDesktopDevServerUrl(environment)
: backendHttpUrl.href;
const iconPaths = yield* assets.iconPaths;
const iconOption = getIconOption(iconPaths, environment.platform);
const iconOption = getIconOption(iconPaths);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
const window = yield* electronWindow.create({
width: 1100,
@@ -193,39 +183,18 @@ const make = Effect.gen(function* () {
minHeight: 620,
show: false,
autoHideMenuBar: true,
...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
...iconOption,
title: environment.displayName,
...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
...getWindowTitleBarOptions(shouldUseDarkColors),
webPreferences: {
preload: environment.preloadPath,
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
webviewTag: true,
},
});
if (environment.platform === "darwin") {
window.setAutoHideCursor(false);
}
yield* previewManager.setMainWindow(window);
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
if (
typeof params.partition !== "string" ||
!previewManager.isBrowserPartition(params.partition)
) {
event.preventDefault();
return;
}
webPreferences.sandbox = true;
webPreferences.nodeIntegration = false;
webPreferences.nodeIntegrationInSubFrames = false;
webPreferences.contextIsolation = false;
});
window.webContents.on("context-menu", (event, params) => {
event.preventDefault();
@@ -328,7 +297,7 @@ const make = Effect.gen(function* () {
});
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
if (environment.platform === "linux") {
if (process.platform === "linux") {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => {
@@ -418,7 +387,7 @@ const make = Effect.gen(function* () {
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
yield* electronWindow.syncAllAppearance((window) =>
syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
syncWindowAppearance(window, shouldUseDarkColors),
);
}).pipe(Effect.withSpan("desktop.window.syncAppearance")),
});
+3 -14
View File
@@ -14,18 +14,17 @@ export default defineConfig({
run: {
tasks: {
build: {
command: "node scripts/build-preview-annotation-css.mjs && vp pack",
command: "vp pack",
dependsOn: ["t3#build"],
cache: false,
},
dev: {
command:
"node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
command: "cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
dependsOn: ["t3#build"],
cache: false,
},
"dev:bundle": {
command: "node scripts/build-preview-annotation-css.mjs && vp pack --watch",
command: "vp pack --watch",
cache: false,
},
"dev:electron": {
@@ -57,15 +56,5 @@ export default defineConfig({
define: publicConfigDefine,
entry: ["src/preload.ts"],
},
{
format: "cjs",
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
entry: ["src/preview-pick-preload.ts"],
deps: {
alwaysBundle: (id) => id === "react-grab" || id.startsWith("react-grab/"),
},
},
],
});
@@ -0,0 +1,53 @@
---
interface Props {
class?: string;
idPrefix: string;
}
const { class: className, idPrefix } = Astro.props;
---
<svg
class={className}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 256 295"
aria-hidden="true"
>
<defs>
<linearGradient id={`${idPrefix}0`} x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}6`} x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}8`} x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%">
<stop offset="0%" stop-color="#FFF" stop-opacity=".8" />
<stop offset="100%" stop-color="#FFF" stop-opacity="0" />
</linearGradient>
<linearGradient id={`${idPrefix}c`} x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}e`} x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}i`} x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
</defs>
<g fill="none">
<path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905" />
<path fill={`url(#${idPrefix}6)`} d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903" />
<path fill={`url(#${idPrefix}8)`} d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293" />
<path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z" />
<path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z" />
<path fill={`url(#${idPrefix}c)`} stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)" />
<path fill={`url(#${idPrefix}e)`} stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)" />
<path fill={`url(#${idPrefix}i)`} stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)" />
<path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255" />
</g>
</svg>
+15 -43
View File
@@ -1,6 +1,4 @@
---
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
interface Props {
title?: string;
description?: string;
@@ -38,17 +36,17 @@ const {
</a>
<div class="nav-right">
<a
class="nav-stars"
href={GITHUB_REPOSITORY_URL}
class="nav-gh"
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
aria-label={`Star T3 Code on GitHub — ${MARKETING_STATS.githubStars} stars`}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 2.3l2.9 5.88 6.49.94-4.7 4.58 1.11 6.47L12 17.12l-5.8 3.05 1.11-6.47-4.7-4.58 6.49-.94L12 2.3z"/>
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span><strong>{MARKETING_STATS.githubStars}</strong> GitHub stars</span>
<span>GitHub</span>
</a>
<a class="btn btn-primary" href="/#download">Download</a>
</div>
</div>
</nav>
@@ -64,7 +62,7 @@ const {
<span>&copy; {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
</div>
<div class="footer-links">
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
</div>
@@ -331,36 +329,23 @@ const {
gap: 8px;
}
.nav-stars {
.nav-gh {
display: inline-flex;
align-items: center;
gap: 7px;
height: 36px;
padding: 0 14px;
gap: 6px;
padding: 7px 12px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.02);
border-radius: 8px;
color: var(--fg-muted);
font-size: 13px;
letter-spacing: -0.01em;
white-space: nowrap;
transition: color 0.18s ease, border-color 0.18s ease, background 0.18s ease;
font-family: var(--font-mono);
font-size: 12px;
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
}
.nav-stars:hover {
.nav-gh:hover {
color: var(--fg);
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.04);
}
.nav-stars strong {
color: var(--fg);
font-weight: 600;
}
.nav-stars svg {
color: var(--warn);
flex-shrink: 0;
border-color: var(--border-strong);
}
.main {
@@ -422,17 +407,4 @@ const {
padding-right: 20px;
}
}
@media (max-width: 420px) {
.nav-inner {
gap: 12px;
}
.nav-stars {
height: 34px;
gap: 6px;
padding: 0 12px;
font-size: 12px;
}
}
</style>
-6
View File
@@ -1,6 +0,0 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const MARKETING_STATS = {
githubStars: "12k+",
users: "100,000",
} as const;
+1 -1
View File
@@ -47,7 +47,7 @@ import { RELEASES_URL } from "../lib/releases";
<!-- Linux -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.36.333.292.2Line truncated
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
+70 -185
View File
@@ -1,6 +1,6 @@
---
import Layout from "../layouts/Layout.astro";
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import TuxIcon from "../components/TuxIcon.astro";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -53,15 +53,14 @@ const mobileEndorsementRows = [
>
<svg class="dl-icon dl-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="dl-icon dl-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="hero-linux-" />
<span id="download-label">Download for macOS</span>
</a>
<a class="hero-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
<svg class="hero-source-mark" width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span>Steal our code (legally)</span>
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
Star on GitHub
</a>
</div>
@@ -84,8 +83,8 @@ const mobileEndorsementRows = [
<section id="endorsements" class="sec-endorsements" aria-labelledby="endorsements-title">
<div class="container">
<div class="endorsements-head">
<h2 id="endorsements-title">Tolerated by over <span class="endorsements-count">{MARKETING_STATS.users}</span> devs</h2>
<p>Some of them even tweeted about it.</p>
<h2 id="endorsements-title">Developers love T3 Code</h2>
<p>Real reactions from people building with T3 Code today.</p>
</div>
</div>
@@ -284,6 +283,10 @@ const mobileEndorsementRows = [
<div class="section-head open-head">
<div class="eyebrow">Open source</div>
<h2>If you don't like something, fork it.</h2>
<p>
T3 Code is as open as they come. We built this app to be modifiable,
customizable, and forkable. Go nuts - that's the whole point.
</p>
</div>
<div class="open-grid">
@@ -303,44 +306,43 @@ const mobileEndorsementRows = [
</div>
</div>
<div class="tile open-pitch">
<div class="open-pitch-copy">
<ul class="open-pitch-list">
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Change the UI.</strong> Restyle every surface to match your taste.</span>
</li>
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Add an agent.</strong> Wire in your own tools, models, and flows.</span>
</li>
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Ship your own build.</strong> Self-host it or distribute it as your own.</span>
</li>
</ul>
<div class="open-stats">
<div class="tile open-stat">
<div class="open-stat-val">MIT</div>
<div class="open-stat-lbl">License · commercial-friendly</div>
</div>
<div class="open-pitch-footer">
<div class="open-pitch-meta">
<span>MIT licensed</span>
<span aria-hidden="true">·</span>
<span>{MARKETING_STATS.githubStars} stars</span>
</div>
<div class="open-pitch-actions">
<a class="btn btn-primary" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
Fork on GitHub
</a>
<a class="open-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
Browse source
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
</div>
<div class="tile open-stat">
<div class="open-stat-val">TypeScript</div>
<div class="open-stat-lbl">End-to-end, strictly typed</div>
</div>
<div class="tile open-stat">
<div class="open-stat-val">1 monorepo</div>
<div class="open-stat-lbl">Desktop · web · server · harnesses</div>
</div>
<div class="tile open-stat">
<div class="open-stat-val">No telemetry</div>
<div class="open-stat-lbl">Unless you opt in. Full stop.</div>
</div>
</div>
</div>
<div class="open-ctas">
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/></svg>
Star on GitHub
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
Fork the repo
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/blob/main/CONTRIBUTING.md" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2"/><path d="M7 10l3 2-3 2M12 16h5"/></svg>
Read CONTRIBUTING.md
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
</div>
</div>
</section>
@@ -358,8 +360,7 @@ const mobileEndorsementRows = [
<a id="cta-download-btn" class="btn btn-primary btn-lg" href="https://github.com/pingdotgg/t3code/releases">
<svg class="dl-icon dl-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="dl-icon dl-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="cta-linux-" />
<span id="cta-download-label">Download for macOS</span>
</a>
<a class="btn btn-ghost btn-lg" href="/download">Windows · Linux · other</a>
@@ -514,7 +515,7 @@ const mobileEndorsementRows = [
.hero-title {
font-size: clamp(38px, 5.6vw, 76px);
margin: 48px auto 22px;
margin: 28px auto 22px;
max-width: 20ch;
text-wrap: balance;
}
@@ -530,42 +531,12 @@ const mobileEndorsementRows = [
.hero-actions {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
gap: 10px;
justify-content: center;
flex-wrap: wrap;
margin-bottom: 56px;
}
.hero-source-link {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--fg-muted);
font-size: 14px;
font-weight: 500;
letter-spacing: -0.01em;
transition: color 0.18s ease;
}
.hero-source-link:hover {
color: var(--fg);
}
.hero-source-mark {
flex-shrink: 0;
}
.hero-source-arrow {
flex-shrink: 0;
opacity: 0.6;
transition: transform 0.18s ease, opacity 0.18s ease;
}
.hero-source-link:hover .hero-source-arrow {
transform: translate(2px, -2px);
opacity: 1;
}
/* Download button icons (platform-aware) */
.dl-icon {
display: none;
@@ -577,7 +548,7 @@ const mobileEndorsementRows = [
:global([data-platform="mac"]) .dl-icon--apple { display: block; }
:global([data-platform="win"]) .dl-icon--windows { display: block; }
:global([data-platform="linux"]) .dl-icon--linux { display: block; }
:global(html:not([data-platform])) .dl-icon--apple { display: block; }
:global(:not([data-platform])) .dl-icon--apple { display: block; }
/* Floating harness marks */
.hero-float {
@@ -685,30 +656,6 @@ const mobileEndorsementRows = [
}
}
@media (max-width: 340px) {
.hero-float-mark.hf-opencode,
.hero-float-mark.hf-cursor {
top: 580px;
width: 52px;
height: 52px;
border-radius: 14px;
}
.hero-float-mark.hf-opencode {
left: 0;
}
.hero-float-mark.hf-cursor {
right: 0;
}
.hero-float-mark.hf-opencode img,
.hero-float-mark.hf-cursor img {
width: 30px;
height: 30px;
}
}
.hero-preview {
max-width: 1180px;
margin: 0 auto;
@@ -812,11 +759,6 @@ const mobileEndorsementRows = [
margin-bottom: 18px;
}
.endorsements-count {
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.endorsements-head p {
color: var(--fg-muted);
font-size: 18px;
@@ -1020,11 +962,12 @@ const mobileEndorsementRows = [
text-align: center;
margin: 0 auto 56px;
}
.open-head p { margin: 0 auto; }
.open-grid {
display: grid;
grid-template-columns: 1.25fr 1fr;
gap: 20px;
gap: 20px; margin-bottom: 32px;
}
.open-term { padding: 0; overflow: hidden; }
@@ -1066,85 +1009,27 @@ const mobileEndorsementRows = [
animation: blink 1s steps(2) infinite;
}
.open-pitch {
padding: 32px;
display: flex;
flex-direction: column;
justify-content: center;
gap: 32px;
background:
radial-gradient(110% 75% at 100% 0%, var(--accent-dim), transparent 60%),
linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent);
}
.open-pitch-list {
list-style: none;
display: flex;
flex-direction: column;
gap: 16px;
}
.open-pitch-list li {
display: flex;
align-items: flex-start;
gap: 12px;
font-size: 15px;
line-height: 1.5;
color: var(--fg-muted);
}
.open-pitch-list strong {
color: var(--fg);
font-weight: 600;
}
.open-pitch-mark {
flex: none;
.open-stats {
display: grid;
place-items: center;
width: 22px;
height: 22px;
margin-top: 1px;
border-radius: 7px;
color: var(--accent);
background: var(--accent-dim);
border: 1px solid color-mix(in srgb, var(--accent) 28%, transparent);
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.open-stat {
padding: 22px;
display: flex; flex-direction: column; gap: 6px;
}
.open-stat-val {
font-size: 22px; font-weight: 500;
letter-spacing: -0.015em;
}
.open-stat-lbl {
font-family: var(--font-mono); font-size: 10.5px;
color: var(--fg-dim); letter-spacing: 0.04em;
}
.open-pitch-footer {
display: flex;
flex-direction: column;
gap: 18px;
}
.open-pitch-meta {
display: flex;
align-items: center;
gap: 8px;
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 11px;
}
.open-pitch-actions {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.open-source-link {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--fg-muted);
font-size: 13px;
font-weight: 500;
transition: color 0.18s ease;
}
.open-source-link:hover {
color: var(--fg);
.open-ctas {
display: flex; gap: 10px;
justify-content: center; flex-wrap: wrap;
}
/* ── Final CTA ────────────────────────────────────────── */
+1 -1
View File
@@ -16,7 +16,7 @@ This app has three variants:
Run commands from `apps/mobile`.
T3 Connect is optional and disabled in a fresh clone. Public configuration belongs in the
T3 Cloud is optional and disabled in a fresh clone. Public configuration belongs in the
repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
[`../../.env.example`](../../.env.example).
-10
View File
@@ -131,11 +131,6 @@ const config: ExpoConfig = {
{
ios: {
deploymentTarget: "18.0",
// AppCheckCore 11.3+ includes Swift and needs module maps for these Objective-C dependencies.
extraPods: [
{ name: "GoogleUtilities", modular_headers: true },
{ name: "RecaptchaInterop", modular_headers: true },
],
},
},
],
@@ -166,11 +161,6 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
tracesToken: repoEnv.EXPO_PUBLIC_OTLP_TRACES_TOKEN ?? null,
},
eas: {
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
},
+2 -2
View File
@@ -13,7 +13,7 @@
"neutral": "#F5F5F5",
"border": "#E5E5EA",
"ring": "#A3A3A3",
"muted": "#F2F2F7",
"muted": "#F5F5F5",
"shadow": "#000000"
},
"darkColors": {
@@ -30,7 +30,7 @@
"neutral": "#1C1C1C",
"border": "#2A2A2A",
"ring": "#525252",
"muted": "#0E0E0E",
"muted": "#1C1C1C",
"shadow": "#000000"
},
"design": {
+1 -2
View File
@@ -1,8 +1,7 @@
{
"cli": {
"version": ">= 18.4.0",
"appVersionSource": "remote",
"promptToConfigurePushNotifications": false
"appVersionSource": "remote"
},
"build": {
"development": {
+5 -15
View File
@@ -18,7 +18,7 @@
--color-foreground: #262626;
--color-foreground-secondary: #525252;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #8e8e93;
--color-foreground-tertiary: #a3a3a3;
/* Borders & separators */
--color-border: rgba(0, 0, 0, 0.08);
@@ -28,9 +28,6 @@
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(0, 0, 0, 0.04);
--color-subtle-strong: rgba(0, 0, 0, 0.08);
--color-inline-skill-background: rgba(217, 70, 239, 0.12);
--color-inline-skill-border: rgba(217, 70, 239, 0.25);
--color-inline-skill-foreground: #a21caf;
/* Primary action */
--color-primary: #262626;
@@ -61,8 +58,6 @@
/* Header / glass chrome */
--color-header: rgba(255, 255, 255, 0.97);
--color-header-border: rgba(0, 0, 0, 0.06);
--color-glass-surface: rgba(255, 255, 255, 0.72);
--color-glass-tint: rgba(255, 255, 255, 0.18);
/* StatusBar */
--color-status-bar: #f2f2f7;
@@ -110,8 +105,8 @@
/* Text */
--color-foreground: #f5f5f5;
--color-foreground-secondary: #a3a3a3;
--color-foreground-muted: #8e8e93;
--color-foreground-tertiary: #636366;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #525252;
/* Borders & separators */
--color-border: rgba(255, 255, 255, 0.06);
@@ -121,9 +116,6 @@
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(255, 255, 255, 0.04);
--color-subtle-strong: rgba(255, 255, 255, 0.08);
--color-inline-skill-background: rgba(217, 70, 239, 0.12);
--color-inline-skill-border: rgba(217, 70, 239, 0.25);
--color-inline-skill-foreground: #f0abfc;
/* Primary action */
--color-primary: #f5f5f5;
@@ -144,18 +136,16 @@
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-placeholder: #8e8e93;
--color-placeholder: #737373;
/* Icons */
--color-icon: #f5f5f5;
--color-icon-muted: #a3a3a3;
--color-icon-subtle: #8e8e93;
--color-icon-subtle: #737373;
/* Header / glass chrome */
--color-header: rgba(10, 10, 10, 0.97);
--color-header-border: rgba(255, 255, 255, 0.06);
--color-glass-surface: rgba(23, 23, 23, 0.78);
--color-glass-tint: rgba(23, 23, 23, 0.24);
/* StatusBar */
--color-status-bar: #0a0a0a;
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,6 +0,0 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["T3ComposerEditorModule"]
}
}
@@ -1,21 +0,0 @@
Pod::Spec.new do |s|
s.name = 'T3ComposerEditor'
s.version = '1.0.0'
s.summary = 'Native attributed composer editor for T3 Code mobile.'
s.description = 'UIKit-backed rich text composer with atomic skill and file tokens.'
s.author = 'T3 Tools'
s.homepage = 'https://t3tools.com'
s.platforms = {
:ios => '16.4',
}
s.source = { :path => '.' }
s.static_framework = true
s.dependency 'ExpoModulesCore'
# Swift/Objective-C compatibility
s.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES',
}
s.source_files = "**/*.{h,m,mm,swift,hpp,cpp}"
end
@@ -1,71 +0,0 @@
import ExpoModulesCore
public class T3ComposerEditorModule: Module {
public func definition() -> ModuleDefinition {
Name("T3ComposerEditor")
View(T3ComposerEditorView.self) {
Prop("value") { (view: T3ComposerEditorView, value: String) in
view.setValue(value)
}
Prop("tokensJson") { (view: T3ComposerEditorView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
Prop("selectionJson") { (view: T3ComposerEditorView, selectionJson: String) in
view.setSelectionJson(selectionJson)
}
Prop("themeJson") { (view: T3ComposerEditorView, themeJson: String) in
view.setThemeJson(themeJson)
}
Prop("placeholder") { (view: T3ComposerEditorView, placeholder: String) in
view.setPlaceholder(placeholder)
}
Prop("fontFamily") { (view: T3ComposerEditorView, fontFamily: String) in
view.setFontFamily(fontFamily)
}
Prop("fontSize") { (view: T3ComposerEditorView, fontSize: Double) in
view.setFontSize(CGFloat(fontSize))
}
Prop("lineHeight") { (view: T3ComposerEditorView, lineHeight: Double) in
view.setLineHeight(CGFloat(lineHeight))
}
Prop("contentInsetVertical") { (view: T3ComposerEditorView, contentInsetVertical: Double) in
view.setContentInsetVertical(CGFloat(contentInsetVertical))
}
Prop("editable") { (view: T3ComposerEditorView, editable: Bool) in
view.setEditable(editable)
}
Prop("scrollEnabled") { (view: T3ComposerEditorView, scrollEnabled: Bool) in
view.setScrollEnabled(scrollEnabled)
}
Prop("autoFocus") { (view: T3ComposerEditorView, autoFocus: Bool) in
view.setAutoFocus(autoFocus)
}
Prop("autoCorrect") { (view: T3ComposerEditorView, autoCorrect: Bool) in
view.setAutoCorrect(autoCorrect)
}
Prop("spellCheck") { (view: T3ComposerEditorView, spellCheck: Bool) in
view.setSpellCheck(spellCheck)
}
Events(
"onComposerChange",
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerPasteImages",
"onComposerContentSizeChange"
)
AsyncFunction("focus") { (view: T3ComposerEditorView) in
view.focusEditor()
}
AsyncFunction("blur") { (view: T3ComposerEditorView) in
view.blurEditor()
}
AsyncFunction("setSelection") { (view: T3ComposerEditorView, start: Int, end: Int) in
view.setSelection(start: start, end: end)
}
}
}
}
@@ -1,819 +0,0 @@
import ExpoModulesCore
import UIKit
private struct ComposerTokenPayload: Decodable {
let type: String
let source: String
let label: String
let iconUri: String?
let start: Int
let end: Int
}
private struct ComposerSelectionPayload: Decodable {
let start: Int
let end: Int
}
private struct ComposerThemePayload: Decodable {
let text: String
let placeholder: String
let chipBackground: String
let chipBorder: String
let chipText: String
let skillBackground: String
let skillBorder: String
let skillText: String
let fileTint: String
}
private struct ComposerChipStyle {
let tint: UIColor
let backgroundColor: UIColor
let borderColor: UIColor
let textColor: UIColor
}
private final class ComposerTextAttachment: NSTextAttachment {
let source: String
init(source: String, image: UIImage, size: CGSize, baselineOffset: CGFloat) {
self.source = source
super.init(data: nil, ofType: nil)
self.image = image
bounds = CGRect(x: 0, y: baselineOffset, width: size.width, height: size.height)
}
required init?(coder: NSCoder) {
nil
}
}
private final class ComposerTextView: UITextView {
private static let pastedImageDirectoryName = "t3-composer-paste"
private static let stalePastedImageAge: TimeInterval = 60 * 60
var onPasteImages: (([String]) -> Void)?
var onAttributedMutation: (() -> Void)?
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(paste(_:)) {
let pasteboard = UIPasteboard.general
if pasteboard.hasImages ||
pasteboard.itemProviders.contains(where: {
$0.canLoadObject(ofClass: UIImage.self)
}) {
return true
}
}
return super.canPerformAction(action, withSender: sender)
}
override func paste(_ sender: Any?) {
let pasteboard = UIPasteboard.general
let imageProviders = pasteboard.itemProviders.filter {
$0.canLoadObject(ofClass: UIImage.self)
}
if !imageProviders.isEmpty {
loadImages(from: imageProviders)
return
}
let images = pasteboard.images ?? []
if !images.isEmpty {
let urls = images.compactMap(Self.writeTemporaryImage)
if !urls.isEmpty {
onPasteImages?(urls)
return
}
}
super.paste(sender)
}
override func deleteBackward() {
guard selectedRange.length == 0, selectedRange.location > 0 else {
super.deleteBackward()
return
}
let previousOffset = selectedRange.location - 1
if textStorage.attribute(.attachment, at: previousOffset, effectiveRange: nil)
is ComposerTextAttachment {
replaceDisplayRange(NSRange(location: previousOffset, length: 1))
return
}
super.deleteBackward()
}
private func replaceDisplayRange(_ range: NSRange) {
guard let start = position(from: beginningOfDocument, offset: range.location),
let end = position(from: start, offset: range.length),
let textRange = textRange(from: start, to: end) else {
return
}
replace(textRange, withText: "")
}
private func loadImages(from providers: [NSItemProvider]) {
let group = DispatchGroup()
let lock = NSLock()
var images = [UIImage?](repeating: nil, count: providers.count)
for (index, provider) in providers.enumerated() {
group.enter()
provider.loadObject(ofClass: UIImage.self) { object, _ in
defer { group.leave() }
guard let image = object as? UIImage else {
return
}
lock.lock()
images[index] = image
lock.unlock()
}
}
group.notify(queue: .main) { [weak self] in
let urls = images.compactMap { $0 }.compactMap(Self.writeTemporaryImage)
if !urls.isEmpty {
self?.onPasteImages?(urls)
}
}
}
override func copy(_ sender: Any?) {
guard selectedRange.length > 0 else {
return super.copy(sender)
}
UIPasteboard.general.string = serializedText(in: selectedRange)
}
override func cut(_ sender: Any?) {
guard isEditable, selectedRange.length > 0 else {
return super.cut(sender)
}
copy(sender)
textStorage.replaceCharacters(in: selectedRange, with: "")
selectedRange = NSRange(location: selectedRange.location, length: 0)
onAttributedMutation?()
}
func serializedText() -> String {
serializedText(in: NSRange(location: 0, length: attributedText.length))
}
func serializedText(in range: NSRange) -> String {
guard range.length > 0 else {
return ""
}
let source = NSMutableString()
let nsString = attributedText.string as NSString
var cursor = range.location
let end = NSMaxRange(range)
attributedText.enumerateAttribute(.attachment, in: range) { value, attachmentRange, _ in
if attachmentRange.location > cursor {
source.append(
nsString.substring(
with: NSRange(location: cursor, length: attachmentRange.location - cursor)
)
)
}
if let attachment = value as? ComposerTextAttachment {
source.append(attachment.source)
} else {
source.append(nsString.substring(with: attachmentRange))
}
cursor = NSMaxRange(attachmentRange)
}
if cursor < end {
source.append(nsString.substring(with: NSRange(location: cursor, length: end - cursor)))
}
return source as String
}
func sourceOffset(forDisplayOffset displayOffset: Int) -> Int {
let boundedOffset = max(0, min(attributedText.length, displayOffset))
if boundedOffset == 0 {
return 0
}
var sourceOffset = 0
let range = NSRange(location: 0, length: boundedOffset)
attributedText.enumerateAttribute(.attachment, in: range) { value, attributeRange, _ in
if let attachment = value as? ComposerTextAttachment {
sourceOffset += (attachment.source as NSString).length
} else {
sourceOffset += attributeRange.length
}
}
return sourceOffset
}
private static func writeTemporaryImage(_ image: UIImage) -> String? {
guard let data = image.pngData() else {
return nil
}
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent(pastedImageDirectoryName, isDirectory: true)
do {
try FileManager.default.createDirectory(
at: directory,
withIntermediateDirectories: true
)
removeStaleTemporaryImages(in: directory)
let url = directory.appendingPathComponent("\(UUID().uuidString).png")
try data.write(to: url, options: .atomic)
return url.absoluteString
} catch {
return nil
}
}
private static func removeStaleTemporaryImages(in directory: URL) {
let cutoff = Date().addingTimeInterval(-stalePastedImageAge)
guard let urls = try? FileManager.default.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: [.contentModificationDateKey, .isRegularFileKey],
options: [.skipsHiddenFiles]
) else {
return
}
for url in urls {
guard
let values = try? url.resourceValues(
forKeys: [.contentModificationDateKey, .isRegularFileKey]
),
values.isRegularFile == true,
let modifiedAt = values.contentModificationDate,
modifiedAt < cutoff
else {
continue
}
try? FileManager.default.removeItem(at: url)
}
}
}
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
private let textView = ComposerTextView()
private let placeholderLabel = UILabel()
private var value = ""
private var tokensJson = "[]"
private var tokens: [ComposerTokenPayload] = []
private var requestedSelection: ComposerSelectionPayload?
private var theme = ComposerThemePayload(
text: "#262626",
placeholder: "#8e8e93",
chipBackground: "#f2f2f7",
chipBorder: "#dedee3",
chipText: "#262626",
skillBackground: "#f9e8fb",
skillBorder: "#e5a6eb",
skillText: "#a21caf",
fileTint: "#737373"
)
private var fontFamily = "DMSans_400Regular"
private var fontSize: CGFloat = 15
private var lineHeight: CGFloat = 22
private var contentInsetVertical: CGFloat = 0
private var shouldAutoFocus = false
private var didAutoFocus = false
private var isApplyingControlledValue = false
private var lastContentSize = CGSize.zero
private var iconImages: [String: UIImage] = [:]
private var pendingIconUris = Set<String>()
private var tokensNeedRebuild = false
let onComposerChange = EventDispatcher()
let onComposerSelectionChange = EventDispatcher()
let onComposerFocus = EventDispatcher()
let onComposerBlur = EventDispatcher()
let onComposerPasteImages = EventDispatcher()
let onComposerContentSizeChange = EventDispatcher()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
clipsToBounds = false
textView.delegate = self
textView.backgroundColor = .clear
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.keyboardDismissMode = .interactive
textView.alwaysBounceVertical = false
textView.showsVerticalScrollIndicator = true
textView.adjustsFontForContentSizeCategory = true
textView.onPasteImages = { [weak self] urls in
self?.onComposerPasteImages(["uris": urls])
}
textView.onAttributedMutation = { [weak self] in
self?.emitTextChange()
}
addSubview(textView)
placeholderLabel.numberOfLines = 0
placeholderLabel.adjustsFontForContentSizeCategory = true
addSubview(placeholderLabel)
applyTypography()
applyTheme()
}
public override func layoutSubviews() {
super.layoutSubviews()
textView.frame = bounds
let placeholderX = textView.textContainerInset.left + textView.textContainer.lineFragmentPadding
let placeholderY = textView.textContainerInset.top
let placeholderWidth = max(
0,
bounds.width - placeholderX - textView.textContainerInset.right -
textView.textContainer.lineFragmentPadding
)
placeholderLabel.frame = CGRect(
x: placeholderX,
y: placeholderY,
width: placeholderWidth,
height: max(lineHeight, placeholderLabel.font.lineHeight)
)
emitContentSizeIfNeeded()
}
public override func didMoveToWindow() {
super.didMoveToWindow()
guard window != nil, shouldAutoFocus, !didAutoFocus else {
return
}
didAutoFocus = true
DispatchQueue.main.async { [weak self] in
self?.textView.becomeFirstResponder()
}
}
func setValue(_ value: String) {
self.value = value
applyControlledDocument(force: tokensNeedRebuild)
if tokensMatchCurrentValue() {
tokensNeedRebuild = false
}
}
func setTokensJson(_ tokensJson: String) {
guard self.tokensJson != tokensJson else {
return
}
self.tokensJson = tokensJson
tokens = decode([ComposerTokenPayload].self, from: tokensJson) ?? []
tokensNeedRebuild = true
applyControlledDocument(force: true)
if tokensMatchCurrentValue() {
tokensNeedRebuild = false
}
}
func setSelectionJson(_ selectionJson: String) {
requestedSelection = decode(ComposerSelectionPayload.self, from: selectionJson)
applyRequestedSelection()
}
func setThemeJson(_ themeJson: String) {
guard let nextTheme = decode(ComposerThemePayload.self, from: themeJson) else {
return
}
theme = nextTheme
applyTheme()
applyControlledDocument(force: true)
}
func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
setNeedsLayout()
}
func setFontFamily(_ fontFamily: String) {
self.fontFamily = fontFamily
applyTypography()
applyControlledDocument(force: true)
}
func setFontSize(_ fontSize: CGFloat) {
self.fontSize = fontSize
applyTypography()
applyControlledDocument(force: true)
}
func setLineHeight(_ lineHeight: CGFloat) {
self.lineHeight = lineHeight
applyTypography()
applyControlledDocument(force: true)
}
func setContentInsetVertical(_ contentInsetVertical: CGFloat) {
self.contentInsetVertical = contentInsetVertical
textView.textContainerInset = UIEdgeInsets(
top: contentInsetVertical,
left: 0,
bottom: contentInsetVertical,
right: 0
)
setNeedsLayout()
}
func setEditable(_ editable: Bool) {
textView.isEditable = editable
}
func setScrollEnabled(_ scrollEnabled: Bool) {
textView.isScrollEnabled = scrollEnabled
}
func setAutoFocus(_ autoFocus: Bool) {
shouldAutoFocus = autoFocus
}
func setAutoCorrect(_ autoCorrect: Bool) {
textView.autocorrectionType = autoCorrect ? .yes : .no
}
func setSpellCheck(_ spellCheck: Bool) {
textView.spellCheckingType = spellCheck ? .yes : .no
}
func focusEditor() {
textView.becomeFirstResponder()
}
func blurEditor() {
textView.resignFirstResponder()
}
func setSelection(start: Int, end: Int) {
requestedSelection = ComposerSelectionPayload(start: start, end: end)
applyRequestedSelection()
}
public func textViewDidChange(_ textView: UITextView) {
emitTextChange()
}
public func textViewDidChangeSelection(_ textView: UITextView) {
guard !isApplyingControlledValue else {
return
}
emitSelection()
}
public func textViewDidBeginEditing(_ textView: UITextView) {
onComposerFocus()
}
public func textViewDidEndEditing(_ textView: UITextView) {
onComposerBlur()
}
private func applyControlledDocument(force: Bool = false) {
let currentSource = textView.serializedText()
guard force || currentSource != value || !documentMatchesExpectedTokens() else {
updatePlaceholderVisibility()
return
}
let previousSelection = sourceSelection()
isApplyingControlledValue = true
textView.attributedText = makeAttributedDocument()
let targetSelection = requestedSelection ?? previousSelection
requestedSelection = nil
textView.selectedRange = displayRange(for: targetSelection)
isApplyingControlledValue = false
updatePlaceholderVisibility()
emitContentSizeIfNeeded()
}
private func makeAttributedDocument() -> NSAttributedString {
let result = NSMutableAttributedString()
let source = value as NSString
var cursor = 0
let validTokens = tokens.filter {
$0.start >= cursor &&
$0.end > $0.start &&
$0.end <= source.length &&
source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
}
for token in validTokens {
if token.start < cursor {
continue
}
if token.start > cursor {
appendPlainText(
source.substring(with: NSRange(location: cursor, length: token.start - cursor)),
to: result
)
}
result.append(makeAttachmentString(token))
cursor = token.end
}
if cursor < source.length {
appendPlainText(
source.substring(with: NSRange(location: cursor, length: source.length - cursor)),
to: result
)
}
return result
}
private func appendPlainText(_ text: String, to result: NSMutableAttributedString) {
result.append(NSAttributedString(string: text, attributes: baseAttributes()))
}
private func makeAttachmentString(_ token: ComposerTokenPayload) -> NSAttributedString {
let isSkill = token.type == "skill"
let tint = UIColor(composerHex: isSkill ? theme.skillText : theme.fileTint) ?? .secondaryLabel
let iconName = isSkill ? "cube" : "doc"
let iconImage = token.iconUri.flatMap(iconImage(for:))
let style = ComposerChipStyle(
tint: tint,
backgroundColor: UIColor(
composerHex: isSkill ? theme.skillBackground : theme.chipBackground
) ?? .secondarySystemFill,
borderColor: UIColor(
composerHex: isSkill ? theme.skillBorder : theme.chipBorder
) ?? .separator,
textColor: UIColor(composerHex: isSkill ? theme.skillText : theme.chipText) ?? .label
)
let image = renderChip(
label: token.label,
iconName: iconName,
iconImage: iconImage,
style: style
)
let font = UIFont(name: fontFamily, size: fontSize)
?? UIFont.systemFont(ofSize: fontSize)
let baselineOffset = floor((font.capHeight - image.size.height) / 2)
let attachment = ComposerTextAttachment(
source: token.source,
image: image,
size: image.size,
baselineOffset: baselineOffset
)
return NSAttributedString(attachment: attachment)
}
private func renderChip(
label: String,
iconName: String,
iconImage: UIImage?,
style: ComposerChipStyle
) -> UIImage {
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
let fallbackIcon = UIImage(
systemName: iconName,
withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .medium)
)
let icon = iconImage ?? fallbackIcon
let textSize = (label as NSString).size(withAttributes: [.font: font])
let iconWidth = icon == nil ? 0 : 14
let iconGap = icon == nil ? 0 : 5
let height: CGFloat = 24
let width = ceil(9 + CGFloat(iconWidth + iconGap) + textSize.width + 9)
let format = UIGraphicsImageRendererFormat.preferred()
format.opaque = false
let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: format)
return renderer.image { context in
let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
let path = UIBezierPath(roundedRect: rect.insetBy(dx: 0.5, dy: 0.5), cornerRadius: 7)
style.backgroundColor.setFill()
path.fill()
style.borderColor.setStroke()
path.lineWidth = 1
path.stroke()
var x: CGFloat = 9
if let icon {
let renderedIcon = iconImage == nil
? icon.withTintColor(style.tint, renderingMode: .alwaysOriginal)
: icon
renderedIcon.draw(
in: CGRect(x: x, y: 5, width: 14, height: 14)
)
x += 19
}
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .left
(label as NSString).draw(
in: CGRect(x: x, y: 3, width: textSize.width + 1, height: 18),
withAttributes: [
.font: font,
.foregroundColor: style.textColor,
.paragraphStyle: paragraph,
]
)
context.cgContext.setAllowsAntialiasing(true)
}
}
private func iconImage(for uri: String) -> UIImage? {
if let image = iconImages[uri] {
return image
}
guard !pendingIconUris.contains(uri), let url = URL(string: uri) else {
return nil
}
if url.isFileURL, let image = UIImage(contentsOfFile: url.path) {
iconImages[uri] = image
return image
}
pendingIconUris.insert(uri)
URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
guard let self, let data, let image = UIImage(data: data) else {
DispatchQueue.main.async {
self?.pendingIconUris.remove(uri)
}
return
}
DispatchQueue.main.async {
self.pendingIconUris.remove(uri)
self.iconImages[uri] = image
self.applyControlledDocument(force: true)
}
}.resume()
return nil
}
private func baseAttributes() -> [NSAttributedString.Key: Any] {
let font = UIFont(name: fontFamily, size: fontSize)
?? UIFont.systemFont(ofSize: fontSize)
let paragraph = NSMutableParagraphStyle()
paragraph.minimumLineHeight = lineHeight
paragraph.maximumLineHeight = lineHeight
return [
.font: font,
.foregroundColor: UIColor(composerHex: theme.text) ?? .label,
.paragraphStyle: paragraph,
]
}
private func applyTypography() {
let font = UIFont(name: fontFamily, size: fontSize)
?? UIFont.systemFont(ofSize: fontSize)
textView.font = font
textView.typingAttributes = baseAttributes()
placeholderLabel.font = font
setNeedsLayout()
}
private func applyTheme() {
textView.textColor = UIColor(composerHex: theme.text) ?? .label
placeholderLabel.textColor = UIColor(composerHex: theme.placeholder) ?? .placeholderText
tintColor = UIColor.systemBlue
}
private func emitTextChange() {
guard !isApplyingControlledValue else {
return
}
value = textView.serializedText()
let selection = sourceSelection()
onComposerChange([
"value": value,
"selection": ["start": selection.start, "end": selection.end],
])
updatePlaceholderVisibility()
emitContentSizeIfNeeded()
}
private func emitSelection() {
let selection = sourceSelection()
onComposerSelectionChange([
"selection": ["start": selection.start, "end": selection.end],
])
}
private func sourceSelection() -> ComposerSelectionPayload {
ComposerSelectionPayload(
start: textView.sourceOffset(forDisplayOffset: textView.selectedRange.location),
end: textView.sourceOffset(forDisplayOffset: NSMaxRange(textView.selectedRange))
)
}
private func displayRange(for selection: ComposerSelectionPayload) -> NSRange {
let start = displayOffset(forSourceOffset: selection.start)
let end = displayOffset(forSourceOffset: selection.end)
return NSRange(location: start, length: max(0, end - start))
}
private func displayOffset(forSourceOffset sourceOffset: Int) -> Int {
let boundedOffset = max(0, min((value as NSString).length, sourceOffset))
var collapsedLength = 0
for token in tokens where token.end <= boundedOffset {
collapsedLength += max(0, token.end - token.start - 1)
}
if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {
return token.start - collapsedLength + 1
}
return boundedOffset - collapsedLength
}
private func applyRequestedSelection() {
guard let requestedSelection else {
return
}
let nextRange = displayRange(for: requestedSelection)
guard nextRange.location <= textView.attributedText.length,
NSMaxRange(nextRange) <= textView.attributedText.length else {
return
}
isApplyingControlledValue = true
textView.selectedRange = nextRange
isApplyingControlledValue = false
}
private func updatePlaceholderVisibility() {
placeholderLabel.isHidden = !value.isEmpty
}
private func emitContentSizeIfNeeded() {
let nextSize = textView.contentSize
guard abs(nextSize.width - lastContentSize.width) > 0.5 ||
abs(nextSize.height - lastContentSize.height) > 0.5 else {
return
}
lastContentSize = nextSize
onComposerContentSizeChange(["width": nextSize.width, "height": nextSize.height])
}
private func decode<T: Decodable>(_ type: T.Type, from json: String) -> T? {
guard let data = json.data(using: .utf8) else {
return nil
}
return try? JSONDecoder().decode(type, from: data)
}
private func tokensMatchCurrentValue() -> Bool {
let source = value as NSString
return tokens.allSatisfy {
$0.start >= 0 &&
$0.end > $0.start &&
$0.end <= source.length &&
source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
}
}
private func documentMatchesExpectedTokens() -> Bool {
let source = value as NSString
let expectedSources = tokens.compactMap { token -> String? in
guard token.start >= 0,
token.end > token.start,
token.end <= source.length,
source.substring(
with: NSRange(location: token.start, length: token.end - token.start)
) == token.source else {
return nil
}
return token.source
}
var renderedSources: [String] = []
textView.attributedText.enumerateAttribute(
.attachment,
in: NSRange(location: 0, length: textView.attributedText.length)
) { value, _, _ in
if let attachment = value as? ComposerTextAttachment {
renderedSources.append(attachment.source)
}
}
return renderedSources == expectedSources
}
}
private extension UIColor {
convenience init?(composerHex hex: String?) {
guard var value = hex?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
return nil
}
if value.hasPrefix("#") {
value.removeFirst()
}
guard value.count == 6 || value.count == 8,
let raw = UInt64(value, radix: 16) else {
return nil
}
if value.count == 8 {
self.init(
red: CGFloat((raw >> 24) & 0xff) / 255,
green: CGFloat((raw >> 16) & 0xff) / 255,
blue: CGFloat((raw >> 8) & 0xff) / 255,
alpha: CGFloat(raw & 0xff) / 255
)
} else {
self.init(
red: CGFloat((raw >> 16) & 0xff) / 255,
green: CGFloat((raw >> 8) & 0xff) / 255,
blue: CGFloat(raw & 0xff) / 255,
alpha: 1
)
}
}
}
@@ -1,20 +0,0 @@
MIT License
Copyright (c) 2024-25 Bluesky PBC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,25 +0,0 @@
require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
new_arch_enabled = ENV["RCT_NEW_ARCH_ENABLED"] == "1"
Pod::Spec.new do |s|
s.name = "T3MarkdownText"
s.version = package["version"]
s.summary = "Native selectable markdown renderer for T3 Code mobile."
s.description = "Fabric-backed attributed text and markdown rendering primitives owned by T3 Code."
s.homepage = "https://t3tools.com"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "T3 Tools" => "[email protected]" }
s.platforms = { :ios => min_ios_version_supported }
s.source = { :path => "." }
s.source_files = "ios/**/*.{h,m,mm,cpp}"
install_modules_dependencies(s)
if ENV["USE_FRAMEWORKS"] != nil && new_arch_enabled
add_dependency(s, "React-FabricComponents", :additional_framework_paths => [
"react/renderer/textlayoutmanager/platform/ios",
])
end
end
@@ -1,12 +0,0 @@
# Upstream Attribution
The Fabric attributed-text component in this module originated from
[`bluesky-social/react-native-uitextview`](https://github.com/bluesky-social/react-native-uitextview),
version `2.2.0`, commit `addc08fea303608f070fe1eeba4bc075f181c4af`.
The upstream project is Copyright (c) 2024-25 Bluesky PBC and licensed under
the MIT License included in this directory.
T3 Code has substantially modified and renamed the implementation, integrated
its markdown renderer, and owns the resulting module going forward. This is not
an upstream package dependency or a compatibility fork.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Loaded 100 of 1303 files, more files were not shown because too many files have changed in this diff. Show more