Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge f65e38f3d1 Remove provider environment sync effect
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 16:47:30 +00:00
HuakunandJulius Marminge d25090cf6d fix: avoid sending composer during IME enter (#2817)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 02:14:13 +00:00
Mika CohenandJulius Marminge ae39bacf0e Handle non-resumable pending user input (#2766)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 02:13:34 +00:00
Julius MarmingeandJulius Marminge 1ea17026ee [codex] fix slow websocket shutdown (#2869)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 01:39:25 +00:00
Julius Marmingeandcodex 649f4328ea [codex] Refine inline tool call timeline UI (#3052)
Co-authored-by: codex <[email protected]>
2026-06-11 18:18:27 -07:00
Magnus Alexander StrømsengandJulius Marminge 7db034905b fix(git): disable external diff for patch output (#2553)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-11 18:18:13 -07:00
Julius MarmingeandClaude Fable 5 57f6bf7edb Fix turn fold proejctions (#3041)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-06-10 23:51:43 -07:00
Julius Marmingeandcodex 0baf1986e8 [codex] Reduce Git status polling churn (#3037)
Co-authored-by: codex <[email protected]>
2026-06-10 17:10:19 -07:00
Julius Marmingeandcodex ae7e88b0e0 [codex] Sync app-server protocol, service tiers, and provider startup (#3036)
Co-authored-by: codex <[email protected]>
2026-06-10 16:24:19 -07:00
1916ac6d55 Rework message metadata, timestamps, and tool work log rows (#3022)
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-06-10 14:38:42 -07:00
Julius Marmingeandcodex 343061a053 Misc chrome polish: header badges, plan sidebar, diff panel, empty state (#3027)
Co-authored-by: codex <[email protected]>
2026-06-10 12:25:03 -07:00
0b40ea62e1 Extract changed files card with compact aligned diff stats (#3023)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-10 08:27:32 +00:00
a4757c2656 Composer polish: focus ring, send/stop buttons, command menu, context meter, answer panel (#3018)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-10 08:02:32 +00:00
3efabdcd3a Polish web context menu fallback and sidebar icon actions (#3025)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-10 07:29:21 +00:00
c5f7cd40ba Polish branch picker trigger, scroll fade, and list layout (#3024)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-06-10 07:13:34 +00:00
e2db800f7c Provider env vars table and reworked accent color picker (#3026)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 23:27:59 -07:00
31533466b0 Model picker UI Improvements, Virtualize Model List (#3021)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-10 06:22:55 +00:00
7f741a56d1 Misc markdown styling improvements (#3017)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-06-09 21:21:58 -07:00
RuzbyteandJulius Marminge cc9e81ac93 fix(marketing) : marketing showing wrong icons on linux (#2696)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 20:04:36 -07:00
238715fd6f Polish dialog/alert surfaces and unauthenticated provider banner (#3016)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 17:52:16 -07:00
b03bc4b52d Mute icons in labeled controls and suppress popup focus rings (#3015)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 17:15:09 -07:00
aca14507f7 Bundle DM Sans and JetBrains Mono fonts instead of Google Fonts (#3014)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 16:57:38 -07:00
t3-code[bot] 04f7f32ace chore(release): prepare v0.0.27 2026-06-09 21:14:36 +00:00
Julius Marmingeandcodex a3422a9bb5 Fix Clerk browser test mock (#3013)
Co-authored-by: codex <[email protected]>
2026-06-09 20:38:20 +00:00
Julius Marmingeandcodex 22f9f3058b [codex] Rebrand T3 Cloud as T3 Connect (#3011)
Co-authored-by: codex <[email protected]>
2026-06-09 12:25:02 -07:00
t3-code[bot] 983a8c7fa6 chore(release): prepare v0.0.26 2026-06-09 17:53:22 +00:00
Julius Marmingeandcodex de58ec8e24 Add Claude Fable 5 model (#3009)
Co-authored-by: codex <[email protected]>
2026-06-09 17:39:18 +00:00
Julius Marmingeandcodex 8e6f4229da [codex] Fix main CI Effect test runtimes (#3008)
Co-authored-by: codex <[email protected]>
2026-06-09 09:43:03 -07:00
Milosz JankiewiczandJulius Marminge 38ea6d483e feat(grok): add Grok CLI provider via ACP (#2809)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 09:28:40 -07:00
Julius Marmingeandcodex 0e4a43519f [codex] Extract infrastructure, telemetry, and test tooling (#2994)
Co-authored-by: codex <[email protected]>
2026-06-07 20:21:47 -07:00
Julius Marmingeandcodex 3ea6adf17d [codex] Enrich relay authorization diagnostics (#2977)
Co-authored-by: codex <[email protected]>
2026-06-05 18:01:34 -07:00
Julius Marminge a56496c7f2 Annotate relay error spans with schema fields (#2976) 2026-06-05 16:35:14 -07:00
b76f161d55 fix(desktop): stop looping macOS TCC permission prompts (#2745)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 12:07:18 -07:00
Peter Hozák 75257d64e9 "claude system message" instead of "runtime warning" when using 4.8 from claude code (#2972) 2026-06-05 11:27:37 -07:00
Abdul AzeezandJulius Marminge e1ce9f8500 fix: handle Claude Agent SDK 0.3.x system messages to stop runtime-warning flood (#2872)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 18:26:32 +00:00
Julius Marminge 602148f8fe fix(cloud): use Electron fetch for proxying Clerk IPC requests (#2973) 2026-06-05 11:08:34 -07:00
Julius Marminge 92be60e7c1 include @latest 2026-06-04 23:01:09 -07:00
Julius Marminge 0d6e9e9add we support cursor, duhhh 2026-06-04 23:00:40 -07:00
Julius Marminge 8ab58a0b26 tip 2026-06-04 22:59:28 -07:00
Julius Marminge 6f42bd9c88 cleanup 2026-06-04 22:58:53 -07:00
Julius Marminge 5b26bd408b link 2026-06-04 22:57:04 -07:00
Julius Marminge c04d15d3be document vp instead of mise 2026-06-04 22:56:18 -07:00
Julius Marminge 9da430c828 Refactor recoverable Effect fallbacks to orElseSucceed (#2968) 2026-06-05 05:47:56 +00:00
Julius Marminge a084fbbc0a Remove duplicate 'publish' argument in CLI script 2026-06-04 22:39:59 -07:00
Julius Marminge b870a6e349 Rename function for publishing arguments to vp pm (#2967) 2026-06-05 05:22:37 +00:00
Julius Marminge e1cb19b55b Use pnpm for server publish workflow (#2966) 2026-06-04 22:16:52 -07:00
Julius Marminge 94fc117561 publish deploy status on relay deploy workflow 2026-06-04 21:47:12 -07:00
Julius Marminge 113b9d84c7 remove vp staged 2026-06-04 21:41:54 -07:00
Julius Marminge f60def2054 Migrate tests to vite-plus test APIs (#2964) 2026-06-05 04:39:19 +00:00
Julius Marminge eda163ca17 bump alchemy to fix drizzle schema out attempt 2 2026-06-04 21:03:05 -07:00
Julius Marminge 3579005114 bump alchemy to fix absolute drizzle schema out 2026-06-04 20:45:34 -07:00
Julius Marminge af3dfd229e forward args directly 2026-06-04 20:19:06 -07:00
Julius Marminge 969e6d274c implicit install from vp 2026-06-04 20:16:56 -07:00
Julius Marminge 769bdd251d fallback to None when RELAY_DOMAIN is unset 2026-06-04 20:16:23 -07:00
Julius Marminge 295b9db113 dont fail if env-file is unspecified 2026-06-04 20:12:42 -07:00
Julius Marminge b5a62504d4 move 2026-06-04 20:05:30 -07:00
Julius Marminge ec18938bf9 Restructure documentation into topical folders (#2963) 2026-06-04 20:03:12 -07:00
Julius Marmingeandcodex 5ae77c0d63 feat(relay): Add managed relay tunnels and APN service (#2837)
Co-authored-by: codex <[email protected]>
2026-06-04 19:53:56 -07:00
Julius MarmingeandJulius Marminge 300f7fd11d [codex] Avoid shell for system executables (#2950)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 15:25:46 -07:00
Guilherme Vieira 53042f47f8 fix(composer): support spaces in file mentions (#2625) 2026-06-04 15:19:06 -07:00
Julius MarmingeandJulius Marminge 6ce6f678b5 [codex] Avoid shell for Windows environment probe (#2951)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 15:15:26 -07:00
Julius MarmingeandJulius Marminge a74dfd4f3c [codex] Avoid shell for Node executable spawns (#2952)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 15:14:07 -07:00
Guilherme VieiraandJulius Marminge 49c1b64687 fix(source-control): handle self-hosted GitLab, multi-account GitHub auth & azure devops web url (#2480)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 15:13:04 -07:00
Julius MarmingeandJulius Marminge dfdb5a46db [codex] fix release finalize install (#2961)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 21:57:43 +00:00
Julius Marminge b0fa60a121 Prevent settings layout shifts with scrollbar gutters (#2960) 2026-06-04 14:31:24 -07:00
Julius MarmingeandJulius Marminge 348a9140e9 fix(cli): bundle patched diff parser dependency (#2957)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 18:53:47 +00:00
Julius Marminge 9fc485afaf fix(release): install hosted web workspace closure (#2949) 2026-06-04 17:31:54 +00:00
Julius Marmingeandcodex a6edad1974 [codex] Filter staged desktop patched dependencies (#2945)
Co-authored-by: codex <[email protected]>
2026-06-03 23:47:20 -07:00
Julius Marmingeandcodex 203f58e456 [codex] Fix desktop packaging patched dependencies (#2944)
Co-authored-by: codex <[email protected]>
2026-06-04 06:34:21 +00:00
Julius MarmingeandJulius Marminge 52ae8e88df fix(release): preserve desktop artifact arch (#2943)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 06:29:19 +00:00
Julius MarmingeandJulius Marminge 80b40ce96a [codex] fix mobile native static analysis source discovery (#2942)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 23:13:01 -07:00
Julius MarmingeandJulius Marminge 4c262c4b4e [codex] split ci workflow jobs (#2940)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 22:57:42 -07:00
Julius MarmingeandJulius Marminge 4f3d00f063 fix(release): install dependency closures in partial jobs (#2941)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 05:54:33 +00:00
Julius MarmingeandJulius Marminge 37bf0f0d1d [codex] remove duplicated pnpm root config (#2939)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 05:34:23 +00:00
Julius MarmingeandJulius Marminge 6a1c4da528 fix(release): use workspace electron-builder for desktop packaging (#2938)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 22:15:15 -07:00
Yash SinghandJulius Marminge dca93d0ee8 chore: setup eas ci (#2911)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 22:08:34 -07:00
Julius MarmingeandJulius Marminge 1288909b66 fix(release): surface desktop packaging subprocess output (#2937)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 20:47:20 -07:00
Julius MarmingeandJulius Marminge 30d36b8c48 ci: let setup-vp install dependencies (#2936)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 19:37:03 -07:00
Julius MarmingeandJulius Marminge e4643eccc7 fix: build web before desktop release packaging (#2934)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 19:15:06 -07:00
Mike OlsonandJulius Marminge 4956415f7f fix(desktop): Preserve SSH HTTP auth status (#2923)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 02:10:17 +00:00
Mike Olson f5849f7d78 fix(ssh): Surface redacted stdout for failed commands (#2920) 2026-06-03 18:50:13 -07:00
Mike Olson 6e6163255d test(web): CI stability - prebundle react-dom client for browser tests (#2928) 2026-06-03 18:45:34 -07:00
b440dd1812 Migrate workspace to Vite+ and pnpm (#2899)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-06-03 16:16:53 -07:00
d78e02cd0b Probe Cursor models via list_available_models (#2428)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 17:06:52 +00:00
821 changed files with 87139 additions and 11547 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# 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-...
+87 -75
View File
@@ -7,81 +7,105 @@ on:
- main
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
check:
name: Check
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Cache Bun and Turbo
uses: actions/cache@v5
with:
path: |
~/.bun/install/cache
.turbo
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install dependencies
run: bun install --frozen-lockfile
cache: true
run-install: true
- name: Ensure Electron runtime is installed
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
run: vp run --filter @t3tools/desktop ensure:electron
- name: Format
run: bun run fmt:check
- name: Lint
run: bun run lint
- name: Check
run: vp check
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
- name: Install browser test runtime
run: |
cd apps/web
bunx playwright install --with-deps chromium
- name: Browser test
run: bun run --cwd apps/web test:browser
run: vpr typecheck
- name: Build desktop pipeline
run: bun run build:desktop
run: vp run build:desktop
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
test:
name: Test
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: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- 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
@@ -90,24 +114,18 @@ jobs:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
cache: true
run-install: true
- name: Install mobile native static analysis tools
run: brew bundle install --file apps/mobile/Brewfile
- name: Lint mobile native sources
run: node scripts/mobile-native-static-check.ts
run: vp run lint:mobile
release_smoke:
name: Release Smoke
@@ -117,18 +135,12 @@ jobs:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
cache: true
run-install: true
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+80
View File
@@ -0,0 +1,80 @@
name: Deploy T3 Connect relay
on:
push:
branches:
- main
permissions:
contents: read
id-token: none
statuses: write
concurrency:
group: relay-production
cancel-in-progress: false
jobs:
deploy_relay:
name: Deploy production relay
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 15
environment:
name: production
env:
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}
APNS_TEAM_ID: ${{ vars.APNS_TEAM_ID }}
APNS_KEY_ID: ${{ vars.APNS_KEY_ID }}
APNS_BUNDLE_ID: ${{ vars.APNS_BUNDLE_ID }}
ALCHEMY_TELEMETRY_DISABLED: "1"
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Deploy production relay stage
id: deploy
run: vp run --filter t3code-relay deploy --stage prod --yes --github-output
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
- name: Publish relay deploy commit status
uses: actions/github-script@v8
with:
script: |
const result = "${{ steps.deploy.outputs.result }}";
const changed = "${{ steps.deploy.outputs.changed }}" === "true";
const description = changed
? "Relay production deploy applied infrastructure changes."
: result === "noop"
? "Relay production deploy was a no-op."
: `Relay production deploy completed with result: ${result}.`;
await github.rest.repos.createCommitStatus({
owner: context.repo.owner,
repo: context.repo.repo,
sha: context.sha,
state: "success",
context: "Relay deploy / production",
description,
target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,
});
+78
View File
@@ -0,0 +1,78 @@
name: Mobile EAS Preview
on:
pull_request:
jobs:
preview:
name: EAS Preview
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
pull-requests: write
env:
APP_VARIANT: preview
NODE_OPTIONS: --max-old-space-size=8192
MOBILE_VERSION_POLICY: fingerprint
steps:
- id: expo-token
name: Check for EXPO_TOKEN
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
if [ -n "$EXPO_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "EXPO_TOKEN is not available; skipping EAS preview."
fi
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup EAS
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull preview --non-interactive
- name: Deploy with fingerprint check
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action/continuous-deploy-fingerprint@main
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
with:
profile: preview:dev
branch: pr-${{ github.event.pull_request.number }}
platform: all
environment: preview
working-directory: apps/mobile
github-token: ${{ secrets.GITHUB_TOKEN }}
+134 -99
View File
@@ -85,26 +85,15 @@ jobs:
with:
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
cache: true
run-install: true
- name: Ensure Electron runtime is installed
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
run: vp run --filter @t3tools/desktop ensure:electron
- id: release_meta
name: Resolve release version
@@ -160,14 +149,14 @@ jobs:
fi
fi
- name: Lint
run: bun run lint
- name: Check
run: vp check
- name: Typecheck
run: bun run typecheck
run: vp run typecheck
- name: Test
run: bun run test
run: vp run test
- id: previous_tag
name: Resolve previous release tag
@@ -177,12 +166,69 @@ jobs:
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
build:
name: Build ${{ matrix.label }}
relay_public_config:
name: Resolve T3 Connect public config
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 5
environment:
name: production
outputs:
clerk_publishable_key: ${{ steps.public_config.outputs.clerk_publishable_key }}
clerk_jwt_template: ${{ steps.public_config.outputs.clerk_jwt_template }}
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
relay_url: ${{ steps.public_config.outputs.relay_url }}
env:
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:
- id: public_config
name: Resolve production relay public config
shell: bash
run: |
set -euo pipefail
relay_domain="${RELAY_DOMAIN:-}"
if [[ -z "$relay_domain" && -n "${RELAY_API_ZONE_NAME:-}" ]]; then
relay_domain="relay.$RELAY_API_ZONE_NAME"
fi
required=(
relay_domain
CLERK_PUBLISHABLE_KEY
CLERK_JWT_TEMPLATE
CLERK_CLI_OAUTH_CLIENT_ID
)
missing=()
for name in "${required[@]}"; do
if [[ -z "${!name:-}" ]]; then
missing+=("$name")
fi
done
if (( ${#missing[@]} > 0 )); then
printf 'Missing required relay deployment configuration: %s\n' "${missing[*]}" >&2
exit 1
fi
echo "clerk_publishable_key=$CLERK_PUBLISHABLE_KEY" >> "$GITHUB_OUTPUT"
echo "clerk_jwt_template=$CLERK_JWT_TEMPLATE" >> "$GITHUB_OUTPUT"
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
build:
name: Build ${{ matrix.label }}
needs: [preflight, relay_public_config]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
env:
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
strategy:
fail-fast: false
matrix:
@@ -219,18 +265,12 @@ jobs:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
cache: true
run-install: true
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -390,7 +430,7 @@ jobs:
echo "Signing disabled for ${{ matrix.platform }}."
fi
bun run dist:desktop:artifact -- "${args[@]}"
vp run dist:desktop:artifact "${args[@]}"
- name: Collect release assets
shell: bash
@@ -439,41 +479,43 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
needs: [preflight, relay_public_config, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: read
id-token: write
env:
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
cache: true
run-install: |
args:
- --filter=t3...
- --filter=@t3tools/web...
- --filter=@t3tools/scripts...
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build web package
run: bun --filter=@t3tools/web run build
run: vp run --filter @t3tools/web build
- name: Build CLI package
run: bun --filter=t3 run build
run: vp run --filter t3 build
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
@@ -498,18 +540,14 @@ jobs:
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
@@ -601,11 +639,14 @@ jobs:
deploy_web:
name: Deploy hosted web app
needs: [preflight, release]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
needs: [preflight, relay_public_config, release]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.release.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
env:
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
@@ -619,24 +660,21 @@ jobs:
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Install release tooling dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts --filter=@t3tools/web
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Refresh release lockfile
run: bun install --lockfile-only --ignore-scripts
run: vp install --lockfile-only --ignore-scripts
- name: Deploy and alias channel
shell: bash
@@ -668,25 +706,28 @@ jobs:
echo "Deploying hosted web app for $channel_name channel."
deployment_url="$(
bunx [email protected] deploy \
vp dlx [email protected] deploy \
--prod \
--skip-domain \
--yes \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}" \
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
echo "Aliasing $deployment_url to $channel_domain."
bunx [email protected] alias set "$deployment_url" "$channel_domain" \
vp dlx [email protected] alias set "$deployment_url" "$channel_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
echo "Aliasing $deployment_url to router domain $router_domain."
bunx [email protected] alias set "$deployment_url" "$router_domain" \
vp dlx [email protected] alias set "$deployment_url" "$router_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
fi
@@ -724,18 +765,15 @@ jobs:
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/oxlint-plugin-t3code...
- id: update_versions
name: Update version strings
@@ -745,11 +783,11 @@ jobs:
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: bunx [email protected] apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
run: vp fmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
run: bun install --lockfile-only --ignore-scripts
run: vp install --lockfile-only --ignore-scripts
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
@@ -757,7 +795,7 @@ jobs:
env:
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
run: |
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml; then
echo "No version changes to commit."
exit 0
fi
@@ -765,7 +803,7 @@ jobs:
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml
git commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
@@ -774,10 +812,11 @@ jobs:
if: |
always() && !cancelled() &&
needs.preflight.result == 'success' &&
needs.relay_public_config.result == 'success' &&
needs.release.result == 'success' &&
needs.deploy_web.result == 'success' &&
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
needs: [preflight, release, deploy_web, finalize]
needs: [preflight, relay_public_config, release, deploy_web, finalize]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
@@ -786,18 +825,14 @@ jobs:
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Announce prerelease on Discord
if: needs.preflight.outputs.is_prerelease == 'true'
+6
View File
@@ -5,6 +5,7 @@ node_modules
*.log
*.tsbuildinfo
apps/*/dist
infra/*/dist
.astro
packages/*/dist
.env
@@ -26,3 +27,8 @@ squashfs-root/
.gstack/
dist-electron/
.electron-runtime/
node_modules/
.alchemy/
*.log
.env*
!.env.example
-3
View File
@@ -1,3 +0,0 @@
[tools]
node = "24.13.1"
bun = "1.3.9"
-29
View File
@@ -1,29 +0,0 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".repos/**",
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/mobile/android/**",
"apps/mobile/ios/**",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
"apps/mobile/uniwind-types.d.ts",
"*.icon/**"
],
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
}
-30
View File
@@ -1,30 +0,0 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"dist",
"dist-electron",
".repos/**",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/mobile/android/**",
"apps/mobile/ios/**",
"apps/mobile/uniwind-types.d.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"jsPlugins": ["./oxlint-plugin-t3code/index.ts"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
"perf": "warn"
},
"rules": {
"unicorn/no-array-sort": "off",
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off",
"eslint/no-underscore-dangle": "off",
"t3code/no-inline-schema-compile": "warn"
}
}
+1
View File
@@ -6,6 +6,7 @@
},
"oxc.unusedDisableDirectives": "warn",
"js/ts.tsdk.path": "node_modules/typescript/lib",
"typescript.native-preview.tsdk": "node_modules/@typescript/native-preview",
"typescript.preferences.autoImportFileExcludePatterns": [".repos/**"],
"javascript.preferences.autoImportFileExcludePatterns": [".repos/**"],
"files.watcherExclude": {
+5 -19
View File
@@ -2,9 +2,9 @@
## Task Completion Requirements
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- If changing native mobile code, `bun lint:mobile` must also pass.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
- `vp check` and `vp run typecheck` must pass before considering tasks completed.
- If changing native mobile code, `vp run lint:mobile` must also pass.
- Use `vp test` for the built-in Vite+ test command and `vp run test` when you specifically need the `test` package script.
## Project Snapshot
@@ -29,22 +29,8 @@ Long term maintainability is a core priority. If you add new functionality, firs
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
## Codex App Server (Important)
T3 Code is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages.
How we use it in this codebase:
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
- Web app consumes orchestration domain events via WebSocket push on channel `orchestration.domainEvent` (provider runtime activity is projected into orchestration events server-side).
Docs:
- Codex App Server docs: https://developers.openai.com/codex/sdk/#app-server
- `packages/shared`: Shared runtime utilities consumed by both server and client applications. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
- `packages/client-runtime`: Shared runtime package for sharing client code across web and mobile.
## Reference Repos
+35 -8
View File
@@ -1,23 +1,26 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, and OpenCode.
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
### Run without installing
```bash
npx t3
npx t3@latest
```
Tip: Use `npx t3@latest --help` for the full CLI reference.
### Desktop app
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
@@ -46,16 +49,40 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
## Documentation
- [Getting started](./docs/getting-started/quick-start.md)
- [Architecture overview](./docs/architecture/overview.md)
- [Provider guides](./docs/providers/codex.md)
- [Operations](./docs/operations/ci.md)
- [Reference](./docs/reference/encyclopedia.md)
## If you REALLY want to contribute still.... read this first
Before local development, prepare the environment and install dependencies:
### Install `vp`
T3 Code uses Vite+ so you'll need to install the global `vp` command-line tool.
#### macOS / Linux
```bash
# Optional: only needed if you use mise for dev tool management.
mise install
bun install .
curl -fsSL https://vite.plus | bash
```
#### Windows
```bash
irm https://vite.plus/ps1 | iex
```
Checkout their getting started guide for more information: https://viteplus.dev/guide/
### Install dependencies
```bash
vp i
```
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+6 -8
View File
@@ -1,17 +1,14 @@
{
"name": "@t3tools/desktop",
"version": "0.0.24",
"version": "0.0.27",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "node scripts/dev-electron.mjs",
"build": "tsdown",
"ensure:electron": "node scripts/ensure-electron-runtime.mjs",
"start": "node scripts/start-electron.mjs",
"typecheck": "tsgo --noEmit",
"test": "vitest run --passWithNoTests",
"test": "vp test run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
@@ -28,8 +25,9 @@
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"tsdown": "catalog:",
"vitest": "catalog:"
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"vite-plus": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
+20 -10
View File
@@ -2,7 +2,7 @@ import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import { desktopDir, resolveElectronPath } 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();
@@ -28,6 +28,7 @@ const watchedDirectories = [
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
await waitForResources({
baseDir: desktopDir,
@@ -38,6 +39,11 @@ await waitForResources({
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const devProtocolClient = resolveDevProtocolClient();
if (devProtocolClient) {
childEnv.T3CODE_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId;
childEnv.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1";
}
let shuttingDown = false;
let restartTimer = null;
@@ -67,15 +73,17 @@ function startApp() {
return;
}
const app = spawn(
resolveElectronPath(),
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
{
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
},
);
const electronArgs = remoteDebuggingPort
? [`--remote-debugging-port=${remoteDebuggingPort}`]
: [];
const launchArgs = devProtocolClient
? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const app = spawn(resolveElectronPath(), launchArgs, {
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
});
currentApp = app;
@@ -125,6 +133,7 @@ async function stopApp() {
app.once("exit", finish);
app.kill("SIGTERM");
killChildTreeByPid(app.pid, "TERM");
cleanupStaleDevApps();
setTimeout(() => {
if (settled) {
@@ -133,6 +142,7 @@ async function stopApp() {
app.kill("SIGKILL");
killChildTreeByPid(app.pid, "KILL");
cleanupStaleDevApps();
finish();
}, forcedShutdownTimeoutMs).unref();
});
+167 -12
View File
@@ -3,6 +3,7 @@
import { spawnSync } from "node:child_process";
import {
copyFileSync,
chmodSync,
cpSync,
existsSync,
mkdirSync,
@@ -13,20 +14,34 @@ import {
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import { dirname, join, resolve } from "node:path";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LAUNCHER_VERSION = 2;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const devBundleIdSuffix = basename(repoRoot)
.toLowerCase()
.replaceAll(/[^a-z0-9]+/g, "");
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 10;
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
function resolveDevelopmentProtocolCallbackPort() {
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
return configuredPort + 1;
}
return 13774;
}
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
encoding: "utf8",
@@ -46,6 +61,26 @@ function setPlistString(plistPath, key, value) {
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function setPlistJson(plistPath, key, value) {
const serialized = JSON.stringify(value);
const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
if (insertResult.status === 0) {
return;
}
const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
@@ -56,6 +91,71 @@ function runChecked(command, args) {
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
}
function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`;
const envEntries = [
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
["T3CODE_HOME", process.env.T3CODE_HOME],
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"],
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
writeFileSync(
targetBinaryPath,
[
"#!/bin/sh",
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
'for arg in "$@"; do',
' case "$arg" in',
" t3code-dev://auth/callback*)",
' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then',
' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0',
" fi",
" ;;",
" esac",
"done",
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
);
chmodSync(targetBinaryPath, 0o755);
}
function registerMacLauncherBundle(appBundlePath) {
runChecked(
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
["-f", appBundlePath],
);
if (!isDevelopment) {
return;
}
for (const scheme of APP_PROTOCOL_SCHEMES) {
runChecked("osascript", [
"-l",
"JavaScript",
"-e",
[
'ObjC.import("CoreServices");',
`const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`,
`const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`,
"const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);",
"if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);",
].join(" "),
]);
}
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
@@ -114,12 +214,49 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
{
CFBundleURLName: APP_BUNDLE_ID,
CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
},
]);
const resourcesDir = join(appBundlePath, "Contents", "Resources");
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
const helperBundleNames = [
["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
];
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
const infoPlistPath = join(
appBundlePath,
"Contents",
"Frameworks",
bundleName,
"Contents",
"Info.plist",
);
if (!existsSync(infoPlistPath)) {
continue;
}
setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
setPlistString(
infoPlistPath,
"CFBundleIdentifier",
`${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
);
}
}
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
@@ -129,7 +266,7 @@ function readJson(path) {
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
@@ -143,6 +280,8 @@ function buildMacLauncher(electronBinaryPath) {
sourceAppBundlePath,
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: statSync(iconPath).mtimeMs,
appBundleId: APP_BUNDLE_ID,
appProtocolSchemes: APP_PROTOCOL_SCHEMES,
};
const currentMetadata = readJson(metadataPath);
@@ -151,18 +290,26 @@ function buildMacLauncher(electronBinaryPath) {
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
}
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
}
export function resolveElectronPath() {
ensureElectronRuntime();
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
@@ -170,11 +317,19 @@ export function resolveElectronPath() {
return electronBinaryPath;
}
// Dev launches do not need a renamed app bundle badly enough to risk breaking
// Electron helper resource lookup on macOS.
if (isDevelopment) {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
export function resolveDevProtocolClient() {
if (process.platform !== "darwin" || !isDevelopment) {
return null;
}
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."),
appBundleId: APP_BUNDLE_ID,
};
}
@@ -0,0 +1,176 @@
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
const require = createRequire(import.meta.url);
function getPlatformPath() {
switch (process.platform) {
case "darwin":
return "Electron.app/Contents/MacOS/Electron";
case "freebsd":
case "openbsd":
case "linux":
return "electron";
case "win32":
return "electron.exe";
default:
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
}
}
function ensureExecutable(filePath) {
if (process.platform !== "win32") {
chmodSync(filePath, 0o755);
}
}
function repairPathFile(electronDir, platformPath) {
const pathFile = join(electronDir, "path.txt");
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
if (currentPath !== platformPath) {
writeFileSync(pathFile, platformPath);
}
}
function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [join(electronDir, "dist", platformPath)];
if (process.platform === "darwin") {
paths.push(
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
join(
electronDir,
"dist",
"Electron.app",
"Contents",
"Frameworks",
"Electron Framework.framework",
"Electron Framework",
),
);
}
return paths;
}
function isMachO(filePath) {
if (process.platform !== "darwin") {
return true;
}
const result = spawnSync("file", ["-b", filePath], {
encoding: "utf8",
});
return result.status === 0 && result.stdout.includes("Mach-O");
}
function missingRuntimePaths(electronDir, platformPath) {
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
return !existsSync(runtimePath);
});
}
function invalidRuntimePaths(electronDir, platformPath) {
if (process.platform !== "darwin") {
return [];
}
return [
join(electronDir, "dist", platformPath),
join(
electronDir,
"dist",
"Electron.app",
"Contents",
"Frameworks",
"Electron Framework.framework",
"Electron Framework",
),
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
}
function runChecked(command, args) {
const result = spawnSync(command, args, {
encoding: "utf8",
stdio: "inherit",
});
if (result.status === 0) {
return;
}
throw new Error(
`${command} ${args.join(" ")} failed with exit code ${result.status ?? "unknown"}`,
);
}
function installElectronRuntime(electronDir, version) {
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
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}-${process.platform}-${process.arch}.zip`,
"-o",
zipPath,
]);
if (process.platform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
} else {
runChecked("python3", [
"-c",
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
zipPath,
join(electronDir, "dist"),
]);
}
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
}
export function ensureElectronRuntime() {
const electronPackageJsonPath = require.resolve("electron/package.json");
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = dirname(electronPackageJsonPath);
const platformPath = getPlatformPath();
const electronPath = join(electronDir, "dist", platformPath);
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
if (existsSync(join(electronDir, "dist"))) {
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
}
rmSync(join(electronDir, "path.txt"), { force: true });
installElectronRuntime(electronDir, electronPackageJson.version);
}
const missingAfterInstall = missingRuntimePaths(electronDir, platformPath);
const invalidAfterInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingAfterInstall.length > 0 || invalidAfterInstall.length > 0) {
throw new Error(
`Electron runtime is incomplete after install.\nMissing:\n${missingAfterInstall
.map((runtimePath) => `- ${runtimePath}`)
.join("\n")}\nInvalid:\n${invalidAfterInstall
.map((runtimePath) => `- ${runtimePath}`)
.join("\n")}`,
);
}
ensureExecutable(electronPath);
repairPathFile(electronDir, platformPath);
return electronPath;
}
if (import.meta.url === `file://${process.argv[1]}`) {
const electronPath = ensureElectronRuntime();
process.stdout.write(`${electronPath}\n`);
}
+4 -1
View File
@@ -1,16 +1,17 @@
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as NetService from "@t3tools/shared/Net";
import * as Crypto from "effect/Crypto";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
@@ -190,6 +191,7 @@ const startup = Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const updates = yield* DesktopUpdates.DesktopUpdates;
@@ -207,6 +209,7 @@ const startup = Effect.gen(function* () {
yield* appIdentity.configure;
yield* lifecycle.register;
yield* cloudAuth.configure;
yield* electronApp.whenReady.pipe(
Effect.withSpan("desktop.electron.whenReady"),
@@ -53,6 +53,9 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
calls.setAboutPanelOptions.push(options);
}),
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: (iconPath) =>
Effect.sync(() => {
+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.catch(() => Effect.succeed(Option.none<string>())),
Effect.orElseSucceed(() => Option.none<string>()),
),
});
});
@@ -0,0 +1,302 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthHarness {
readonly app: ElectronApp.ElectronAppShape;
readonly window: ElectronWindow.ElectronWindowShape;
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
readonly protocolRegistrations: {
readonly protocol: string;
readonly path?: string;
readonly args?: readonly string[];
}[];
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
readonly reveals: unknown[];
readonly layer: Layer.Layer<
| DesktopCloudAuth.DesktopCloudAuth
| DesktopEnvironment.DesktopEnvironment
| ElectronApp.ElectronApp
| ElectronWindow.ElectronWindow
>;
}
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
const sends: CloudAuthHarness["sends"] = [];
const reveals: unknown[] = [];
const mainWindow = { id: "main-window" };
const app = ElectronApp.ElectronApp.of({
metadata: Effect.succeed({
appVersion: "0.0.0-test",
appPath: "/tmp/t3-code-test",
isPackaged: !input.isDevelopment,
resourcesPath: "/tmp/t3-code-test/resources",
runningUnderArm64Translation: false,
}),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: (protocol, path, args) =>
Effect.sync(() => {
protocolRegistrations.push({
protocol,
...(path === undefined ? {} : { path }),
...(args === undefined ? {} : { args }),
});
return true;
}),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
on: (eventName, listener) =>
Effect.sync(() => {
const erasedListener = listener as (...args: readonly unknown[]) => void;
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
}),
});
const window = ElectronWindow.ElectronWindow.of({
create: () => Effect.die("not used"),
main: Effect.succeed(Option.some(mainWindow as never)),
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
setMain: () => Effect.void,
clearMain: () => Effect.void,
reveal: (target) =>
Effect.sync(() => {
reveals.push(target);
}),
sendAll: (channel, ...args) =>
Effect.sync(() => {
sends.push({ channel, args });
}),
destroyAll: Effect.void,
syncAllAppearance: () => Effect.void,
});
const environment = DesktopEnvironment.DesktopEnvironment.of({
isDevelopment: input.isDevelopment,
} as DesktopEnvironment.DesktopEnvironmentShape);
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
return {
app,
window,
listeners,
protocolRegistrations,
sends,
reveals,
layer: Layer.mergeAll(
DesktopCloudAuth.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provide(NodeServices.layer),
),
Layer.succeed(ElectronApp.ElectronApp, app),
Layer.succeed(ElectronWindow.ElectronWindow, window),
),
};
}
function emitAppEvent(
harness: CloudAuthHarness,
eventName: string,
...args: readonly unknown[]
): void {
for (const listener of harness.listeners.get(eventName) ?? []) {
listener(...args);
}
}
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
describe("DesktopCloudAuth", () => {
it("uses separate callback schemes for packaged and development builds", () => {
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
"t3code",
);
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
"t3code-dev",
);
});
it("builds a native callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code",
state: "state-1",
}),
"t3code://auth/callback?t3_state=state-1",
);
});
it("accepts only the expected scheme, host, path, and state", () => {
assert.isNotNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
});
it("builds a native development callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code-dev",
state: "state-1",
}),
"t3code-dev://auth/callback?t3_state=state-1",
);
});
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
let prevented = false;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => (prevented = true) },
callbackUrl.toString(),
);
yield* flushCloudAuthDispatch;
assert.isTrue(prevented);
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code-dev"],
);
assert.isString(harness.protocolRegistrations[0]?.path);
assert.isArray(harness.protocolRegistrations[0]?.args);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.lengthOf(harness.reveals, 1);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
const harness = makeHarness({ isDevelopment: false });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const validCallback = new URL(redirectUrl);
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
const invalidCallback = new URL(validCallback);
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
invalidCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, []);
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code"],
);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [validCallback.toString()],
},
]);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect(
"routes second-instance callbacks and reveals the window for non-callback launches",
() => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
yield* flushCloudAuthDispatch;
const revealCountAfterCallback = harness.reveals.length;
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.equal(revealCountAfterCallback, 1);
assert.equal(harness.reveals.length, 2);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
},
);
});
+330
View File
@@ -0,0 +1,330 @@
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import type * as Electron from "electron";
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
"DesktopCloudAuthCallbackServerError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to start the desktop cloud auth callback server.";
}
}
interface PendingCloudAuthRequest {
readonly state: string;
readonly redirectUrl: string;
readonly close: () => void;
}
export interface DesktopCloudAuthShape {
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
"@t3tools/desktop/app/DesktopCloudAuth",
) {}
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
}
export function buildCloudAuthCallbackUrl(input: {
readonly scheme: string;
readonly state: string;
}): string {
const url = new URL(
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
);
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
return url.toString();
}
export function parseCloudAuthCallbackUrl(input: {
readonly rawUrl: unknown;
readonly scheme: string;
readonly state: string;
}): URL | null {
if (typeof input.rawUrl !== "string") {
return null;
}
try {
const url = new URL(input.rawUrl);
if (url.protocol !== `${input.scheme}:`) return null;
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
return url;
} catch {
return null;
}
}
export function findCloudAuthCallbackUrl(input: {
readonly values: readonly unknown[];
readonly scheme: string;
readonly state: string;
}): URL | null {
for (const value of input.values) {
const url = parseCloudAuthCallbackUrl({
rawUrl: value,
scheme: input.scheme,
state: input.state,
});
if (url) return url;
}
return null;
}
export function resolveProtocolClientLaunchArgs(input: {
readonly argv: readonly string[];
}): readonly string[] {
return input.argv.slice(1);
}
function resolveConfiguredProtocolClient(): {
readonly path: string;
readonly args: readonly string[];
} | null {
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
if (!path) return null;
return {
path,
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
.split("\n")
.map((arg) => arg.trim())
.filter((arg) => arg.length > 0),
};
}
function isProtocolRegistrationManagedExternally(): boolean {
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
}
function resolveProtocolCallbackForwardUrl(): URL | null {
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
if (!rawUrl) return null;
try {
const url = new URL(rawUrl);
if (url.protocol !== "http:") return null;
if (url.hostname !== "127.0.0.1") return null;
if (url.pathname !== "/auth/callback") return null;
if (!url.port) return null;
return url;
} catch {
return null;
}
}
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
request?.close();
return null;
};
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
}
function ignoreCloudAuthCallback(_rawUrl: string) {}
function startProtocolCallbackForwardServer(
callbackUrl: URL,
dispatch: (rawUrl: string) => void,
): Effect.Effect<void, never, Scope.Scope> {
const port = Number.parseInt(callbackUrl.port, 10);
const routesLayer = HttpRouter.add(
"POST",
"/auth/callback",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const rawUrl = yield* request.text;
yield* Effect.sync(() => {
dispatch(rawUrl);
});
return HttpServerResponse.empty({ status: 204 });
}),
);
return Effect.gen(function* () {
const NodeHttp = yield* Effect.promise(() => import("node:http"));
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
host: callbackUrl.hostname,
port,
});
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
Effect.forkScoped,
);
});
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
const makeCloudAuthRequestState = Effect.gen(function* () {
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
return `${left}${right}`.replaceAll("-", "");
});
return DesktopCloudAuth.of({
createRequest: Effect.gen(function* () {
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
const state = yield* makeCloudAuthRequestState.pipe(
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
);
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
const timeout = createCloudAuthRequestTimeout(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
});
pendingAuthRequest = {
state,
redirectUrl,
close: () => clearTimeout(timeout),
};
return redirectUrl;
}),
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const scope = yield* Scope.Scope;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
yield* Scope.addFinalizer(
scope,
Effect.sync(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
}),
);
if (isProtocolRegistrationManagedExternally()) {
// Development macOS launchers set the default URL handler before the stock Electron
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
} else if (environment.isDevelopment) {
const configuredClient = resolveConfiguredProtocolClient();
if (configuredClient) {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
configuredClient.path,
configuredClient.args,
);
} else {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
process.execPath,
resolveProtocolClientLaunchArgs({ argv: process.argv }),
);
}
} else {
yield* electronApp.setAsDefaultProtocolClient(scheme);
}
dispatchCloudAuthCallback = (rawUrl: string) => {
const pending = pendingAuthRequest;
const callbackUrl = pending
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
: null;
if (!callbackUrl) {
return;
}
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
void runPromise(
Effect.gen(function* () {
yield* electronWindow.sendAll(
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
callbackUrl.toString(),
);
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
};
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
if (environment.isDevelopment && protocolCallbackForwardUrl) {
yield* startProtocolCallbackForwardServer(
protocolCallbackForwardUrl,
dispatchCloudAuthCallback,
);
}
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
if (!hasInstanceLock) {
return yield* electronApp.quit;
}
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
event.preventDefault?.();
dispatchCloudAuthCallback(rawUrl);
});
yield* electronApp.on<[Electron.Event, readonly string[]]>(
"second-instance",
(_event, argv) => {
const values = resolveProtocolClientLaunchArgs({ argv });
const pending = pendingAuthRequest;
const callbackUrl = pending
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
: null;
if (callbackUrl) {
dispatchCloudAuthCallback(callbackUrl.toString());
return;
}
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
},
);
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
});
});
export const layer = Layer.effect(DesktopCloudAuth, make);
@@ -0,0 +1,96 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
function makeSafeStorageLayer(input: { readonly available: boolean }) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(input.available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
decryptString: (value) => {
const decoded = textDecoder.decode(value);
if (!decoded.startsWith("enc:")) {
return Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted token"),
}),
);
}
return Effect.succeed(decoded.slice("enc:".length));
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopCloudAuthTokenStore.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
Layer.provideMerge(NodeServices.layer),
);
}
const withTokenStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
input?: { readonly encryptionAvailable?: boolean },
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-cloud-auth-token-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopCloudAuthTokenStore", () => {
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
yield* tokenStore.clear;
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
),
);
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
{ encryptionAvailable: false },
),
);
});
@@ -0,0 +1,155 @@
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthTokenDocument {
readonly version: number;
readonly encryptedClientJwt: string;
}
const CloudAuthTokenDocumentSchema = Schema.Struct({
version: Schema.Number,
encryptedClientJwt: Schema.String,
});
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
}
}
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode desktop cloud auth token.";
}
}
export interface DesktopCloudAuthTokenStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopCloudAuthTokenStoreDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
token: string,
) => Effect.Effect<
boolean,
| DesktopCloudAuthTokenStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopCloudAuthTokenStore extends Context.Service<
DesktopCloudAuthTokenStore,
DesktopCloudAuthTokenStoreShape
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
tokenPath: string,
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
fileSystem.readFileString(tokenPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
}),
),
);
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly tokenPath: string;
readonly document: CloudAuthTokenDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.tokenPath);
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.tokenPath);
});
export const layer = Layer.effect(
DesktopCloudAuthTokenStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
return DesktopCloudAuthTokenStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, tokenPath);
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
tokenPath,
document: { version: 1, encryptedClientJwt },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
return true;
}),
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
Effect.catch(() => Effect.void),
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
),
});
}),
);
+1
View File
@@ -37,6 +37,7 @@ export const DesktopConfig = Config.all({
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
t3Home: trimmedString("T3CODE_HOME"),
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
devRemoteT3ServerEntryPath: trimmedString("T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH"),
configuredBackendPort: Config.port("T3CODE_PORT").pipe(Config.option),
commitHashOverride: trimmedString("T3CODE_COMMIT_HASH"),
@@ -93,6 +93,20 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("uses a configured app user model id override", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
{},
{
T3CODE_DESKTOP_APP_USER_MODEL_ID: " com.t3tools.t3code.dev.local ",
VITE_DEV_SERVER_URL: "http://localhost:5173",
},
);
assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev.local");
}),
);
it.effect("resolves picker defaults without nullish sentinels", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment();
+3 -1
View File
@@ -199,7 +199,9 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
otlpExportIntervalMs: config.otlpExportIntervalMs,
branding,
displayName,
appUserModelId: isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code",
appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () =>
isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code",
),
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
userDataDirName,
@@ -64,6 +64,13 @@ 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",
@@ -86,6 +93,7 @@ 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);
@@ -97,7 +105,7 @@ function makeLayer(input: {
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(mockSpawnerLayer()),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
Layer.provideMerge(networkLayer),
Layer.provideMerge(DesktopConfig.layerTest(env)),
Layer.provideMerge(environmentLayer),
@@ -116,13 +124,23 @@ 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 })));
return yield* effect.pipe(
Effect.provide(
makeLayer({
baseDir,
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
}),
),
);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopServerExposure", () => {
@@ -239,6 +257,27 @@ describe("DesktopServerExposure", () => {
),
);
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
// mode stays at default "local-only", tailscaleServeEnabled stays false.
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
// would have crashed the test if the gate was missing.
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["http://127.0.0.1:4173/"],
);
}),
{},
dieOnSpawnLayer(),
),
);
it.effect("uses ConfigProvider desktop exposure overrides", () =>
withHarness(
lanNetworkInterfaces,
@@ -12,6 +12,7 @@ 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";
@@ -22,8 +23,11 @@ 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";
@@ -412,6 +416,18 @@ 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));
@@ -516,11 +532,20 @@ const make = Effect.gen(function* () {
exposure: toResolvedExposure(state),
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
});
// Don't spawn the Tailscale CLI when the user hasn't opted into any
// network exposure. The spawn itself triggers a macOS "Other apps"
// TCC prompt on Mac App Store Tailscale builds.
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
return coreEndpoints;
}
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: state.port,
serveEnabled: state.tailscaleServeEnabled,
servePort: state.tailscaleServePort,
networkInterfaces: currentNetworkInterfaces,
readMagicDnsName: cachedReadMagicDnsName,
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
@@ -104,6 +104,25 @@ describe("tailscale endpoint provider", () => {
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
Effect.gen(function* () {
let readerCalls = 0;
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
readMagicDnsName: Effect.sync(() => {
readerCalls += 1;
return "desktop.tail.ts.net";
}),
});
assert.equal(readerCalls, 1);
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["https://desktop.tail.ts.net/"],
);
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect(
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
() =>
@@ -105,6 +105,11 @@ 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[],
@@ -112,15 +117,18 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const readDnsName =
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
);
const dnsName =
input.statusJson === undefined
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(null)),
)
? yield* readDnsName
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
)
: null;
const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({
+10 -1
View File
@@ -1,18 +1,21 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
const {
appendSwitchMock,
exitMock,
getAppPathMock,
getVersionMock,
isDefaultProtocolClientMock,
onMock,
quitMock,
relaunchMock,
removeListenerMock,
requestSingleInstanceLockMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
setDesktopNameMock,
setDockIconMock,
setNameMock,
@@ -23,12 +26,15 @@ const {
exitMock: vi.fn(),
getAppPathMock: vi.fn(() => "/app"),
getVersionMock: vi.fn(() => "1.2.3"),
isDefaultProtocolClientMock: vi.fn(() => false),
onMock: vi.fn(),
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
requestSingleInstanceLockMock: vi.fn(() => true),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
setDesktopNameMock: vi.fn(),
setDockIconMock: vi.fn(),
setNameMock: vi.fn(),
@@ -46,14 +52,17 @@ vi.mock("electron", () => ({
},
getAppPath: getAppPathMock,
getVersion: getVersionMock,
isDefaultProtocolClient: isDefaultProtocolClientMock,
isPackaged: true,
name: "T3 Code",
on: onMock,
quit: quitMock,
relaunch: relaunchMock,
removeListener: removeListenerMock,
requestSingleInstanceLock: requestSingleInstanceLockMock,
runningUnderARM64Translation: false,
setAboutPanelOptions: setAboutPanelOptionsMock,
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
setAppUserModelId: setAppUserModelIdMock,
setDesktopName: setDesktopNameMock,
setName: setNameMock,
+17
View File
@@ -29,6 +29,13 @@ export interface ElectronAppShape {
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
@@ -93,6 +100,16 @@ const make = ElectronApp.of({
Effect.sync(() => {
Electron.app.setAppUserModelId(id);
}),
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
isDefaultProtocolClient: (protocol) =>
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
setAsDefaultProtocolClient: (protocol, path, args) =>
Effect.sync(() => {
if (path === undefined) {
return Electron.app.setAsDefaultProtocolClient(protocol);
}
return Electron.app.setAsDefaultProtocolClient(protocol, path, [...(args ?? [])]);
}),
setDesktopName: (desktopName) =>
Effect.sync(() => {
const linuxApp = Electron.app as Electron.App & {
@@ -2,7 +2,7 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type { BrowserWindow } from "electron";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
import * as ElectronDialog from "./ElectronDialog.ts";
@@ -2,7 +2,7 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
const { buildFromTemplateMock, createFromNamedImageMock, setApplicationMenuMock } = vi.hoisted(
() => ({
@@ -44,6 +44,12 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
continue;
}
// Header items are decorative section labels for the web fallback only —
// Electron's native menu has no equivalent affordance, so we skip them.
if (sourceItem.header === true) {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
@@ -3,7 +3,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
vi.hoisted(() => ({
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
const { openExternalMock, writeTextMock } = vi.hoisted(() => ({
openExternalMock: vi.fn(),
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
onMock: vi.fn(),
@@ -1,7 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
const { autoUpdaterMock } = vi.hoisted(() => ({
autoUpdaterMock: {
@@ -1,7 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type * as Electron from "electron";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
appFocusMock: vi.fn(),
+12 -1
View File
@@ -1,6 +1,13 @@
import * as Effect from "effect/Effect";
import * as DesktopIpc from "./DesktopIpc.ts";
import {
clearCloudAuthToken,
createCloudAuthRequest,
fetchCloudAuth,
getCloudAuthToken,
setCloudAuthToken,
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
getSavedEnvironmentRegistry,
@@ -75,7 +82,11 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(createCloudAuthRequest);
yield* ipc.handle(getCloudAuthToken);
yield* ipc.handle(setCloudAuthToken);
yield* ipc.handle(clearCloudAuthToken);
yield* ipc.handle(fetchCloudAuth);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
+6
View File
@@ -3,6 +3,12 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
@@ -0,0 +1,97 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { afterEach } from "vite-plus/test";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const originalFetch = globalThis.fetch;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
const calls: Array<FetchCall> = [];
let responseIndex = 0;
const fetchFn = ((input, init) => {
calls.push([input, init ?? {}]);
const response = responses[responseIndex++];
if (!response) {
return Promise.reject(new Error("Unexpected fetch call"));
}
return Promise.resolve(response);
}) satisfies typeof fetch;
return { fetchFn, calls };
};
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
}
});
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"x-mobile": "1",
},
body,
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert.equal(
new Headers(init.headers).get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://clerk.t3.codes/v1/client",
method: "GET",
headers: {},
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
},
);
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
assert.throws(
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
/restricted to Clerk Frontend API HTTPS hosts/u,
);
});
});
+177
View File
@@ -0,0 +1,177 @@
import {
DesktopCloudAuthFetchInputSchema,
DesktopCloudAuthFetchResultSchema,
} from "@t3tools/contracts";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
readonly reason: string;
readonly cause?: unknown;
}> {
override get message() {
return this.reason;
}
}
function configuredClerkFrontendApiHostname(): string | null {
const publishableKey =
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? ""
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
if (!publishableKey) return null;
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
}
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
throw new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
});
}
return url;
}
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
return Effect.gen(function* () {
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(headers),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
HttpClient.execute,
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed to execute.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
});
}
const electronNetFetchLayer = Layer.unwrap(
Effect.gen(function* () {
const electronFetch = yield* Effect.promise(async () => {
const electron = (await import("electron")) as {
readonly net?: { readonly fetch?: typeof globalThis.fetch };
};
return typeof electron.net?.fetch === "function"
? electron.net.fetch.bind(electron.net)
: null;
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
if (!electronFetch) {
yield* Effect.logWarning(
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
);
}
return FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
);
}),
);
export const createCloudAuthRequest = makeIpcMethod({
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
payload: Schema.Void,
result: Schema.String,
handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
return yield* cloudAuth.createRequest;
}),
});
export const getCloudAuthToken = makeIpcMethod({
channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return Option.getOrNull(yield* tokenStore.get);
}),
});
export const setCloudAuthToken = makeIpcMethod({
channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return yield* tokenStore.set(token);
}),
});
export const clearCloudAuthToken = makeIpcMethod({
channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
yield* tokenStore.clear;
}),
});
export const fetchCloudAuth = makeIpcMethod({
channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
payload: DesktopCloudAuthFetchInputSchema,
result: DesktopCloudAuthFetchResultSchema,
handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
const url = yield* Effect.try({
try: () => validateClerkFrontendApiUrl(input.url),
catch: (cause) =>
cause instanceof DesktopCloudAuthFetchError
? cause
: new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch received an invalid URL.",
cause,
}),
});
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
}),
});
+55 -5
View File
@@ -3,8 +3,11 @@ import {
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime";
import {
EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema,
DesktopSshBearerBootstrapInputSchema,
DesktopSshBearerRequestInputSchema,
@@ -15,10 +18,15 @@ import {
DesktopSshPasswordPromptCancelledType,
DesktopSshPasswordPromptResolutionInputSchema,
ExecutionEnvironmentDescriptor,
EnvironmentInternalError,
EnvironmentOperationForbiddenError,
EnvironmentRequestInvalidError,
EnvironmentScopeRequiredError,
AuthAccessTokenResult,
AuthSessionState,
AuthWebSocketTicketResult,
} from "@t3tools/contracts";
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
@@ -35,26 +43,68 @@ type DesktopSshEnvironmentRequestOperation =
| "fetch-session-state"
| "issue-websocket-ticket";
type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
if (
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
cause instanceof SshHttpBridgeError
) {
return cause.status ?? null;
}
if (isEnvironmentRequestInvalidError(cause)) {
return 400;
}
if (isEnvironmentAuthInvalidError(cause)) {
return 401;
}
if (isEnvironmentScopeRequiredError(cause)) {
return 403;
}
if (isEnvironmentOperationForbiddenError(cause)) {
return 403;
}
if (isEnvironmentInternalError(cause)) {
return 500;
}
return null;
}
export class DesktopSshEnvironmentRequestError extends Data.TaggedError(
"DesktopSshEnvironmentRequestError",
)<{
readonly operation: DesktopSshEnvironmentRequestOperation;
readonly cause: unknown;
readonly cause: DesktopSshEnvironmentRequestCause;
readonly sshHttpStatus: number | null;
}> {
override get message() {
return `SSH remote API request failed during ${this.operation}.`;
const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `;
return `${prefix}SSH remote API request failed during ${this.operation}.`;
}
}
const withLoopbackSshApi =
<A, E, R>(
<A, R>(
operation: DesktopSshEnvironmentRequestOperation,
use: (httpBaseUrl: string) => Effect.Effect<A, E, R>,
use: (httpBaseUrl: string) => Effect.Effect<A, RemoteEnvironmentAuthError, R>,
) =>
(httpBaseUrl: string): Effect.Effect<A, DesktopSshEnvironmentRequestError, R> =>
resolveLoopbackSshHttpBaseUrl(httpBaseUrl).pipe(
Effect.flatMap(use),
Effect.mapError((cause) => new DesktopSshEnvironmentRequestError({ operation, cause })),
Effect.mapError(
(cause) =>
new DesktopSshEnvironmentRequestError({
operation,
cause,
sshHttpStatus: readSshHttpStatus(cause),
}),
),
);
export const discoverSshHosts = makeIpcMethod({
+4
View File
@@ -26,6 +26,8 @@ import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
import * as ElectronWindow from "./electron/ElectronWindow.ts";
import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
@@ -111,6 +113,7 @@ const desktopFoundationLayer = Layer.mergeAll(
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopSavedEnvironments.layer,
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
@@ -135,6 +138,7 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopCloudAuth.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
+17
View File
@@ -96,6 +96,23 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }),
}),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
createCloudAuthRequest: () => ipcRenderer.invoke(IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL),
getCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL),
setCloudAuthToken: (token: string) =>
ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token),
clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL),
fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input),
onCloudAuthCallback: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => {
if (typeof rawUrl !== "string") return;
listener(rawUrl);
};
ipcRenderer.on(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
};
},
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
@@ -209,7 +209,7 @@ function readSettings(
onSome: (raw) =>
decodeDesktopSettingsJson(raw).pipe(
Effect.map((parsed) => normalizeDesktopSettingsDocument(parsed, appVersion)),
Effect.catch(() => Effect.succeed(defaultSettings)),
Effect.orElseSucceed(() => defaultSettings),
),
}),
),
@@ -63,7 +63,7 @@ const readClientSettings = (
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.catch(() => Effect.succeed(Option.none<ClientSettings>())),
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
),
}),
),
@@ -53,6 +53,7 @@ const PersistedSavedEnvironmentStorageRecordSchema = Schema.Struct({
createdAt: Schema.String,
lastConnectedAt: Schema.NullOr(Schema.String),
desktopSsh: Schema.optionalKey(DesktopSshTargetSchema),
relayManaged: Schema.optionalKey(Schema.Struct({ relayUrl: Schema.String })),
encryptedBearerToken: Schema.optionalKey(Schema.String),
});
@@ -134,7 +135,11 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
return {
...nextRecord,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),
};
}
function toSavedEnvironmentStorageRecord(
@@ -149,20 +154,13 @@ function toSavedEnvironmentStorageRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
const desktopSsh = record.desktopSsh;
if (desktopSsh) {
return Option.match(encryptedBearerToken, {
onNone: () => ({ ...nextRecord, desktopSsh }),
onSome: (value) => ({
...nextRecord,
desktopSsh,
encryptedBearerToken: value,
}),
});
}
const metadata = {
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),
};
return Option.match(encryptedBearerToken, {
onNone: () => nextRecord,
onSome: (value) => ({ ...nextRecord, encryptedBearerToken: value }),
onNone: () => ({ ...nextRecord, ...metadata }),
onSome: (value) => ({ ...nextRecord, ...metadata, encryptedBearerToken: value }),
});
}
@@ -187,7 +185,7 @@ function readRegistryDocument(
onSome: (raw) =>
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.catch(() => Effect.succeed({ version: 1, records: [] })),
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
),
}),
),
@@ -196,7 +196,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
.pipe(
Effect.timeoutOption(input.timeout),
Effect.map(Option.getOrElse(() => "")),
Effect.catch(() => Effect.succeed("")),
Effect.orElseSucceed(() => ""),
);
});
@@ -241,7 +241,6 @@ 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.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
);
}
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
createInitialDesktopUpdateState,
@@ -39,6 +39,9 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
+74 -8
View File
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import type * as Electron from "electron";
import { vi } from "vitest";
import { vi } from "vite-plus/test";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
@@ -32,10 +32,13 @@ const environmentInput = {
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
function makeFakeBrowserWindow() {
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
isLoadingMainFrame: vi.fn(() => false),
on: vi.fn(),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
}),
once: vi.fn(),
openDevTools: vi.fn(),
replaceMisspelling: vi.fn(),
@@ -63,6 +66,7 @@ function makeFakeBrowserWindow() {
window: window as unknown as Electron.BrowserWindow,
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
webContentsListeners,
};
}
@@ -96,11 +100,6 @@ const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenuShape);
const electronShellLayer = Layer.succeed(ElectronShell.ElectronShell, {
openExternal: () => Effect.succeed(true),
copyText: () => Effect.void,
} satisfies ElectronShell.ElectronShellShape);
const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
shouldUseDarkColors: Effect.succeed(false),
setSource: () => Effect.void,
@@ -123,6 +122,7 @@ function makeTestLayer(input: {
readonly window: Electron.BrowserWindow;
readonly createCount: Ref.Ref<number>;
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
readonly openedExternalUrls?: unknown[];
}) {
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
create: () => Ref.update(input.createCount, (count) => count + 1).pipe(Effect.as(input.window)),
@@ -145,7 +145,14 @@ function makeTestLayer(input: {
desktopServerExposureLayer,
DesktopState.layer,
electronMenuLayer,
electronShellLayer,
Layer.succeed(ElectronShell.ElectronShell, {
openExternal: (url) =>
Effect.sync(() => {
input.openedExternalUrls?.push(url);
return true;
}),
copyText: () => Effect.void,
} satisfies ElectronShell.ElectronShellShape),
electronThemeLayer,
electronWindowLayer,
),
@@ -154,6 +161,27 @@ function makeTestLayer(input: {
}
describe("DesktopWindow", () => {
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/connections",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "https://accounts.microsoft.com/oauth",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "not a url",
}),
);
});
it.effect("does not open a development window until the backend is ready", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
@@ -177,4 +205,42 @@ describe("DesktopWindow", () => {
}).pipe(Effect.provide(layer));
}),
);
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const openedExternalUrls: unknown[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
openedExternalUrls,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady;
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
if (!willNavigate) {
return yield* Effect.die("will-navigate listener was not registered");
}
let prevented = false;
willNavigate(
{
preventDefault: () => {
prevented = true;
},
},
"https://accounts.microsoft.com/oauth",
);
yield* Effect.promise(() => Promise.resolve());
assert.isTrue(prevented);
assert.deepEqual(openedExternalUrls, ["https://accounts.microsoft.com/oauth"]);
}).pipe(Effect.provide(layer));
}),
);
});
+31 -3
View File
@@ -92,6 +92,17 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
}
export function isSameOriginRendererNavigation(input: {
readonly applicationUrl: string;
readonly navigationUrl: string;
}): boolean {
try {
return new URL(input.applicationUrl).origin === new URL(input.navigationUrl).origin;
} catch {
return false;
}
}
function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
if (process.platform === "darwin") {
return {
@@ -159,6 +170,9 @@ const make = Effect.gen(function* () {
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
backendHttpUrl: URL,
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
const applicationUrl = environment.isDevelopment
? yield* resolveDesktopDevServerUrl(environment)
: backendHttpUrl.href;
const iconPaths = yield* assets.iconPaths;
const iconOption = getIconOption(iconPaths);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
@@ -235,6 +249,21 @@ const make = Effect.gen(function* () {
}
return { action: "deny" };
});
window.webContents.on("will-navigate", (event, url) => {
if (
isSameOriginRendererNavigation({
applicationUrl,
navigationUrl: url,
})
) {
return;
}
event.preventDefault();
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
void runPromise(electronShell.openExternal(url));
}
});
window.on("page-title-updated", (event) => {
event.preventDefault();
@@ -276,11 +305,10 @@ const make = Effect.gen(function* () {
});
if (environment.isDevelopment) {
const devServerUrl = yield* resolveDesktopDevServerUrl(environment);
void window.loadURL(devServerUrl);
void window.loadURL(applicationUrl);
window.webContents.openDevTools({ mode: "detach" });
} else {
void window.loadURL(backendHttpUrl.href);
void window.loadURL(applicationUrl);
}
window.on("closed", () => {
+1 -1
View File
@@ -5,5 +5,5 @@
"types": ["node", "electron"],
"lib": ["ESNext", "DOM", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
"include": ["src", "vite.config.ts", "../../scripts/lib"]
}
-21
View File
@@ -1,21 +0,0 @@
import { defineConfig } from "tsdown";
const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
};
export default defineConfig([
{
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
entry: ["src/preload.ts"],
},
]);
-24
View File
@@ -1,24 +0,0 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist-electron/**"],
},
"dev": {
"dependsOn": ["t3#build"],
"persistent": true,
},
"start": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"persistent": true,
},
"smoke-test": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"outputs": [],
},
},
}
+60
View File
@@ -0,0 +1,60 @@
import { defineConfig } from "vite-plus";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
const repoEnv = loadRepoEnv();
const shouldLaunchElectronAfterPack = process.env.T3CODE_DESKTOP_DEV === "1";
const publicConfigDefine = {
__T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify(
repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "",
),
};
export default defineConfig({
run: {
tasks: {
build: {
command: "vp pack",
dependsOn: ["t3#build"],
cache: false,
},
dev: {
command: "cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
dependsOn: ["t3#build"],
cache: false,
},
"dev:bundle": {
command: "vp pack --watch",
cache: false,
},
"dev:electron": {
command: "node scripts/dev-electron.mjs",
dependsOn: ["t3#build"],
cache: false,
},
},
},
pack: [
{
format: "cjs",
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/main.ts"],
clean: true,
deps: {
alwaysBundle: (id) => id.startsWith("@t3tools/"),
},
...(shouldLaunchElectronAfterPack ? { onSuccess: "node scripts/dev-electron.mjs" } : {}),
},
{
format: "cjs",
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/preload.ts"],
},
],
});
+1
View File
@@ -14,6 +14,7 @@
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
"@vercel/config": "^0.3.0",
"typescript": "catalog:"
}
}
@@ -1,53 +0,0 @@
---
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>
+1
View File
@@ -0,0 +1 @@
/// <reference types="astro/client" />
+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 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>
<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
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
+6 -6
View File
@@ -1,6 +1,5 @@
---
import Layout from "../layouts/Layout.astro";
import TuxIcon from "../components/TuxIcon.astro";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -53,7 +52,7 @@ 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>
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="hero-linux-" />
<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
<span id="download-label">Download for macOS</span>
</a>
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
@@ -298,9 +297,9 @@ const mobileEndorsementRows = [
<div class="open-term-body">
<div><span class="prompt">$</span> gh repo fork pingdotgg/t3code --clone</div>
<div class="dim">✓ Cloned t3code into ./t3code</div>
<div><span class="prompt">$</span> cd t3code &amp;&amp; bun install</div>
<div><span class="prompt">$</span> cd t3code &amp;&amp; vp install</div>
<div class="dim">✓ 1 284 packages installed in 4.2s</div>
<div><span class="prompt">$</span> bun dev</div>
<div><span class="prompt">$</span> vp run dev</div>
<div class="dim">▲ T3 Code dev server → <span class="accent">http://localhost:4001</span></div>
<div class="cursor"><span class="prompt">$</span><span class="caret"></span></div>
</div>
@@ -360,7 +359,8 @@ 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>
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="cta-linux-" />
<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
<span id="cta-download-label">Download for macOS</span>
</a>
<a class="btn btn-ghost btn-lg" href="/download">Windows · Linux · other</a>
@@ -548,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(:not([data-platform])) .dl-icon--apple { display: block; }
:global(html:not([data-platform])) .dl-icon--apple { display: block; }
/* Floating harness marks */
.hero-float {
+7
View File
@@ -0,0 +1,7 @@
import type { VercelConfig } from "@vercel/config/v1";
export const config: VercelConfig = {
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing'",
buildCommand: "vp run --filter @t3tools/marketing build",
outputDirectory: "dist",
};
+24
View File
@@ -0,0 +1,24 @@
# Expo artifacts
.expo/
.eas/
# Build outputs
android/
ios/
dist/
web-build/
# Test files
**/*.test.ts
**/*.test.tsx
# Docs
*.md
# Local env
.env
.env.local
.env*.local
# TypeScript
*.tsbuildinfo
+27 -10
View File
@@ -16,30 +16,34 @@ 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
repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
[`../../.env.example`](../../.env.example).
## Development
Start Metro for the dev client:
```bash
bun run dev:client
vp run dev:client
```
Build and run the local iOS dev client:
```bash
bun run ios:dev
vp run ios:dev
```
Build and run the local iOS preview app:
```bash
bun run ios:preview
vp run ios:preview
```
Force the review diff highlighter engine:
```bash
EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript bun run ios:dev
EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript vp run ios:dev
```
`javascript` is the default and recommended setting for the review diff screen. Set `EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=native` only when you explicitly want to test the native Shiki engine.
@@ -47,8 +51,8 @@ EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript bun run ios:dev
Inspect the resolved Expo config for a variant:
```bash
bun run config:dev
bun run config:preview
vp run config:dev
vp run config:preview
```
Run static checks for mobile native code:
@@ -61,21 +65,34 @@ The native lint task runs SwiftLint for Swift plus ktlint and detekt for Kotlin.
## EAS Builds
CI uses Expo fingerprinting with the `preview:dev` profile to reuse an existing compatible build when possible, or start a new internal EAS build when native runtime inputs change. Production and default local builds continue to use the `appVersion` runtime policy.
For preview or production EAS environments, set `T3CODE_CLERK_PUBLISHABLE_KEY`,
`T3CODE_CLERK_JWT_TEMPLATE`, and `T3CODE_RELAY_URL`
as EAS environment variables. Expo config maps the canonical values into the mobile build.
Create a PR preview dev-client build manually:
```bash
vp run eas:ios:preview:dev
```
Create a cloud dev-client build:
```bash
bun run eas:ios:dev
vp run eas:ios:dev
```
Create a persistent preview build:
```bash
bun run eas:ios:preview
vp run eas:ios:preview
```
Android equivalents:
```bash
bun run eas:android:dev
bun run eas:android:preview
vp run eas:android:dev
vp run eas:android:preview:dev
vp run eas:android:preview
```
+42 -6
View File
@@ -1,8 +1,13 @@
import type { ExpoConfig } from "expo/config";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
type AppVariant = "development" | "preview" | "production";
const APP_VARIANT = resolveAppVariant(process.env.APP_VARIANT);
const repoEnv = loadRepoEnv();
Object.assign(process.env, repoEnv);
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
const VARIANT_CONFIG: Record<
AppVariant,
@@ -53,10 +58,11 @@ const variant = VARIANT_CONFIG[APP_VARIANT];
const config: ExpoConfig = {
name: variant.appName,
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "0.1.0",
runtimeVersion: {
policy: "appVersion",
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
},
orientation: "portrait",
icon: "./assets/icon.png",
@@ -95,6 +101,11 @@ const config: ExpoConfig = {
favicon: "./assets/favicon.png",
},
plugins: [
"expo-router",
"expo-font",
"expo-secure-store",
["@clerk/expo", { theme: "./clerk-theme.json" }],
"expo-web-browser",
[
"expo-camera",
{
@@ -119,17 +130,42 @@ const config: ExpoConfig = {
"expo-build-properties",
{
ios: {
deploymentTarget: "16.4",
deploymentTarget: "18.0",
},
},
],
"expo-secure-store",
"expo-router",
"expo-font",
[
"expo-widgets",
{
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
enablePushNotifications: true,
widgets: [
{
name: "AgentActivity",
displayName: "Agent Activity",
description: "Shows the current state of active T3 Code agents.",
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
},
],
},
],
"./plugins/withAndroidCleartextTraffic.cjs",
],
extra: {
appVariant: APP_VARIANT,
relay: {
url: repoEnv.T3CODE_RELAY_URL ?? null,
},
clerk: {
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",
},
+39
View File
@@ -0,0 +1,39 @@
{
"colors": {
"primary": "#262626",
"background": "#F2F2F7",
"input": "#FFFFFF",
"danger": "#DC2626",
"success": "#059669",
"warning": "#D97706",
"foreground": "#262626",
"mutedForeground": "#737373",
"primaryForeground": "#FFFFFF",
"inputForeground": "#262626",
"neutral": "#F5F5F5",
"border": "#E5E5EA",
"ring": "#A3A3A3",
"muted": "#F5F5F5",
"shadow": "#000000"
},
"darkColors": {
"primary": "#F5F5F5",
"background": "#0E0E0E",
"input": "#171717",
"danger": "#FCA5A5",
"success": "#34D399",
"warning": "#FBBF24",
"foreground": "#F5F5F5",
"mutedForeground": "#A3A3A3",
"primaryForeground": "#0A0A0A",
"inputForeground": "#F5F5F5",
"neutral": "#1C1C1C",
"border": "#2A2A2A",
"ring": "#525252",
"muted": "#1C1C1C",
"shadow": "#000000"
},
"design": {
"borderRadius": 18
}
}
+15
View File
@@ -17,13 +17,28 @@
"APP_VARIANT": "preview"
},
"channel": "preview",
"environment": "preview",
"distribution": "internal"
},
"preview:dev": {
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint"
},
"channel": "preview",
"environment": "preview",
"developmentClient": true,
"distribution": "internal",
"android": {
"buildType": "apk"
}
},
"production": {
"env": {
"APP_VARIANT": "production"
},
"channel": "production",
"environment": "production",
"autoIncrement": true
}
},
+2
View File
@@ -38,6 +38,7 @@
--color-secondary: #ffffff;
--color-secondary-foreground: #262626;
--color-secondary-border: rgba(0, 0, 0, 0.08);
--color-switch-active: #34c759;
/* Danger */
--color-danger: #fef2f2;
@@ -125,6 +126,7 @@
--color-secondary: rgba(255, 255, 255, 0.04);
--color-secondary-foreground: #f5f5f5;
--color-secondary-border: rgba(255, 255, 255, 0.06);
--color-switch-active: #30d158;
/* Danger */
--color-danger: rgba(239, 68, 68, 0.14);
+12 -1
View File
@@ -16,6 +16,7 @@
"android:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"eas:android:dev": "eas build --profile development -p android",
"eas:android:preview": "eas build --profile preview -p android",
"eas:android:preview:dev": "eas build --profile preview:dev -p android",
"eas:android:prod": "eas build --profile production -p android",
"ios": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"ios:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
@@ -23,23 +24,28 @@
"ios:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"eas:ios:dev": "eas build --profile development -p ios",
"eas:ios:preview": "eas build --profile preview -p ios",
"eas:ios:preview:dev": "eas build --profile preview:dev -p ios",
"eas:ios:prod": "eas build --profile production -p ios",
"eas:dev": "eas build --profile development",
"eas:preview": "eas build --profile preview",
"eas:preview:dev": "eas build --profile preview:dev",
"eas:prod": "eas build --profile production",
"config:dev": "APP_VARIANT=development expo config",
"config:preview": "APP_VARIANT=preview expo config",
"config:prod": "APP_VARIANT=production expo config",
"profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
"test": "vitest run",
"test": "vp test run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@callstack/liquid-glass": "^0.7.1",
"@clerk/expo": "^3.3.0",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/ui": "~56.0.8",
"@legendapp/list": "3.0.0-beta.44",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
"@react-native-menu/menu": "^2.0.0",
"@shikijs/core": "3.23.0",
@@ -55,6 +61,7 @@
"diff": "8.0.3",
"effect": "catalog:",
"expo": "^56.0.0",
"expo-auth-session": "~56.0.12",
"expo-build-properties": "~56.0.15",
"expo-camera": "~56.0.7",
"expo-clipboard": "~56.0.3",
@@ -67,12 +74,15 @@
"expo-haptics": "~56.0.3",
"expo-image-picker": "~56.0.14",
"expo-linking": "~56.0.12",
"expo-notifications": "~56.0.14",
"expo-paste-input": "^0.1.15",
"expo-router": "~56.2.7",
"expo-secure-store": "~56.0.4",
"expo-splash-screen": "~56.0.10",
"expo-symbols": "~56.0.5",
"expo-updates": "~56.0.17",
"expo-web-browser": "~56.0.5",
"expo-widgets": "~56.0.15",
"punycode": "^2.3.1",
"react": "19.2.3",
"react-dom": "19.2.3",
@@ -93,6 +103,7 @@
"uniwind": "^1.6.2"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/react": "~19.2.0",
"babel-preset-expo": "~56.0.0",
"tailwindcss": "^4.0.0",
+26 -11
View File
@@ -10,7 +10,7 @@ import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { useCSSVariable, useResolveClassNames } from "uniwind";
import { useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
@@ -20,12 +20,15 @@ import {
} from "../state/use-remote-environment-registry";
import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry";
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation";
function AppNavigator() {
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const colorScheme = useColorScheme();
const statusBarBg = useCSSVariable("--color-status-bar");
const statusBarBg = colorScheme === "dark" ? "#0a0a0a" : "#f2f2f7";
const sheetStyle = useResolveClassNames("bg-sheet");
useAgentNotificationNavigation();
const newTaskScreenOptions = {
contentStyle: sheetStyle,
@@ -45,6 +48,11 @@ function AppNavigator() {
sheetGrabberVisible: true,
};
const settingsSheetScreenOptions = {
...connectionSheetScreenOptions,
sheetAllowedDetents: [0.7],
};
if (isLoadingSavedConnection) {
return <LoadingScreen message="Loading remote workspace…" />;
}
@@ -66,6 +74,7 @@ function AppNavigator() {
headerShadowVisible: false,
}}
/>
<Stack.Screen name="settings" options={settingsSheetScreenOptions} />
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
<Stack.Screen name="new" options={newTaskScreenOptions} />
<Stack.Screen
@@ -91,14 +100,20 @@ export default function RootLayout() {
useRemoteEnvironmentBootstrap();
return (
<RegistryContext value={appAtomRegistry}>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
{fontsLoaded ? <AppNavigator /> : <LoadingScreen message="Loading remote workspace…" />}
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</RegistryContext>
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
{fontsLoaded ? (
<AppNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</CloudAuthProvider>
</RegistryContext.Provider>
);
}
+4 -4
View File
@@ -1,16 +1,16 @@
import Stack from "expo-router/stack";
import { useColorScheme } from "react-native";
import { useResolveClassNames } from "uniwind";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function ConnectionsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const connSheetBg = String(useThemeColor("--color-sheet"));
const headerTint = String(useThemeColor("--color-icon"));
const isDark = useColorScheme() === "dark";
const connSheetBg = isDark ? "rgba(14, 14, 14, 0.98)" : "rgba(242, 242, 247, 0.98)";
const headerTint = isDark ? "#f5f5f5" : "#262626";
return (
<Stack
+10 -16
View File
@@ -1,8 +1,8 @@
import { Link, Stack } from "expo-router";
import { Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -18,11 +18,11 @@ export default function ConnectionsRouteScreen() {
onRemoveEnvironmentPress,
onUpdateEnvironment,
} = useRemoteConnections();
const router = useRouter();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const primaryFg = useThemeColor("--color-primary-foreground");
const accentColor = useThemeColor("--color-icon-muted");
const handleToggle = useCallback((environmentId: EnvironmentId) => {
@@ -34,21 +34,15 @@ export default function ConnectionsRouteScreen() {
<Stack.Screen
options={{
title: "Environments",
headerRight: () => (
<Link href="/connections/new" asChild>
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary active:opacity-70">
<SymbolView
name="plus"
size={18}
tintColor={primaryFg}
type="monochrome"
weight="semibold"
/>
</Pressable>
</Link>
),
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="plus"
onPress={() => router.push("/connections/new")}
separateBackground
/>
</Stack.Toolbar>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
+14 -23
View File
@@ -1,8 +1,7 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useState } from "react";
import { Alert, Pressable, ScrollView, View } from "react-native";
import { Alert, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -31,7 +30,6 @@ export default function ConnectionsNewRouteScreen() {
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const textColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
@@ -128,28 +126,21 @@ export default function ConnectionsNewRouteScreen() {
<Stack.Screen
options={{
title: showScanner ? "Scan QR Code" : "Add Environment",
headerRight: () => (
<Pressable
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
onPress={() => {
if (showScanner) {
closeScanner();
} else {
void openScanner();
}
}}
>
<SymbolView
name={showScanner ? "xmark" : "qrcode.viewfinder"}
size={showScanner ? 14 : 18}
tintColor={textColor}
type="monochrome"
weight="semibold"
/>
</Pressable>
),
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon={showScanner ? "xmark" : "qrcode.viewfinder"}
onPress={() => {
if (showScanner) {
closeScanner();
} else {
void openScanner();
}
}}
separateBackground
/>
</Stack.Toolbar>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
+6 -12
View File
@@ -1,7 +1,6 @@
import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { buildThreadRoutePath } from "../lib/routes";
import { useRemoteCatalog } from "../state/use-remote-catalog";
@@ -17,7 +16,7 @@ export default function HomeRouteScreen() {
const [searchQuery, setSearchQuery] = useState("");
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
const iconColor = isDark ? "#f5f5f5" : "#262626";
return (
<>
@@ -78,16 +77,11 @@ export default function HomeRouteScreen() {
</Stack.Toolbar>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="ellipsis.circle" separateBackground>
<Stack.Toolbar.Label>More</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
icon="desktopcomputer"
onPress={() => router.push("/connections")}
subtitle="Manage connected hosts"
>
<Stack.Toolbar.Label>Environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
<Stack.Toolbar.Button
icon="gearshape"
onPress={() => router.push("/settings")}
separateBackground
/>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
+26 -4
View File
@@ -1,4 +1,5 @@
import Stack from "expo-router/stack";
import { useColorScheme } from "react-native";
import { useResolveClassNames } from "uniwind";
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
@@ -9,20 +10,41 @@ export const unstable_settings = {
export default function NewTaskLayout() {
const sheetStyle = useResolveClassNames("bg-sheet");
const isDark = useColorScheme() === "dark";
const sheetBg = isDark ? "rgba(14, 14, 14, 0.98)" : "rgba(242, 242, 247, 0.98)";
const headerTint = isDark ? "#f5f5f5" : "#262626";
return (
<NewTaskFlowProvider>
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerLargeTitle: false,
headerShadowVisible: false,
headerStyle: { backgroundColor: sheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="index" options={{ animation: "none", title: "Choose project" }} />
<Stack.Screen
name="add-project"
options={{ animation: "slide_from_right", headerShown: false }}
name="add-project/index"
options={{ animation: "slide_from_right", title: "New project" }}
/>
<Stack.Screen name="draft" options={{ animation: "slide_from_right" }} />
<Stack.Screen
name="add-project/repository"
options={{ animation: "slide_from_right", title: "Repository" }}
/>
<Stack.Screen
name="add-project/destination"
options={{ animation: "slide_from_right", title: "Clone destination" }}
/>
<Stack.Screen
name="add-project/local"
options={{ animation: "slide_from_right", title: "Local folder" }}
/>
<Stack.Screen name="draft" options={{ animation: "slide_from_right", title: "New task" }} />
</Stack>
</NewTaskFlowProvider>
);
@@ -1,17 +0,0 @@
import { Stack } from "expo-router";
import { useThemeColor } from "../../../lib/useThemeColor";
export default function AddProjectLayout() {
const sheetStyle = {
backgroundColor: useThemeColor("--color-sheet"),
};
return (
<Stack screenOptions={{ headerShown: false, contentStyle: sheetStyle }}>
<Stack.Screen name="index" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="repository" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="destination" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="local" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
@@ -1,12 +1,5 @@
import { Stack } from "expo-router";
import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectDestinationRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectDestinationScreen />
</>
);
return <AddProjectDestinationScreen />;
}
@@ -1,12 +1,5 @@
import { Stack } from "expo-router";
import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectSourceScreen />
</>
);
return <AddProjectSourceScreen />;
}
@@ -1,12 +1,5 @@
import { Stack } from "expo-router";
import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectLocalRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectLocalFolderScreen />
</>
);
return <AddProjectLocalFolderScreen />;
}
@@ -1,11 +1,22 @@
import { Stack } from "expo-router";
import { Stack, useLocalSearchParams } from "expo-router";
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime";
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRepositoryRoute() {
const params = useLocalSearchParams<{ source?: string | string[] }>();
const source = Array.isArray(params.source) ? params.source[0] : params.source;
const title =
source === "github" ||
source === "gitlab" ||
source === "bitbucket" ||
source === "azure-devops"
? addProjectRemoteSourceLabel(source)
: "Git URL";
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<Stack.Screen options={{ title }} />
<AddProjectRepositoryScreen />
</>
);
+6 -1
View File
@@ -6,11 +6,16 @@ export default function NewTaskDraftRoute() {
const params = useLocalSearchParams<{
environmentId?: string | string[];
projectId?: string | string[];
title?: string | string[];
}>();
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<Stack.Screen
options={{
title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
}}
/>
<NewTaskDraftScreen
initialProjectRef={{
environmentId: Array.isArray(params.environmentId)
+28 -42
View File
@@ -8,7 +8,6 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { NewTaskSheetHeader } from "../../features/threads/NewTaskSheetHeader";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { type RemoteCatalogState, useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
@@ -102,9 +101,14 @@ export default function NewTaskRoute() {
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ headerShown: false }} />
<NewTaskSheetHeader title="Choose project" />
<Stack.Screen options={{ title: "Choose project" }} />
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="plus"
onPress={() => router.push("/new/add-project")}
separateBackground
/>
</Stack.Toolbar>
<ScrollView
showsVerticalScrollIndicator={false}
@@ -148,6 +152,7 @@ export default function NewTaskRoute() {
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
return (
<Link
@@ -166,25 +171,33 @@ export default function NewTaskRoute() {
className="bg-card"
style={{
paddingHorizontal: 16,
paddingVertical: 18,
paddingVertical: 14,
borderTopWidth: isFirst ? 0 : 1,
borderTopColor: borderSubtleColor,
borderTopLeftRadius: isFirst ? 24 : 0,
borderTopRightRadius: isFirst ? 24 : 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
borderBottomLeftRadius: isLast ? 24 : 0,
borderBottomRightRadius: isLast ? 24 : 0,
}}
>
<View className="flex-row items-center justify-between gap-3">
<ProjectFavicon
size={22}
projectTitle={item.title}
httpBaseUrl={savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null}
workspaceRoot={item.workspaceRoot}
bearerToken={savedConnectionsById[item.environmentId]?.bearerToken ?? null}
/>
<View className="h-7 w-7 items-center justify-center">
<ProjectFavicon
size={20}
projectTitle={item.title}
httpBaseUrl={
savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null
}
workspaceRoot={item.workspaceRoot}
bearerToken={
savedConnectionsById[item.environmentId]?.bearerToken ?? null
}
/>
</View>
<View className="flex-1">
<Text className="text-[18px] font-t3-bold">{item.title}</Text>
<Text className="text-[16px] leading-[21px] font-t3-bold">
{item.title}
</Text>
</View>
<SymbolView
name="chevron.right"
@@ -197,33 +210,6 @@ export default function NewTaskRoute() {
</Link>
);
})}
<Pressable
className="bg-card"
style={{
paddingHorizontal: 16,
paddingVertical: 18,
borderTopWidth: 1,
borderTopColor: borderSubtleColor,
borderBottomLeftRadius: 24,
borderBottomRightRadius: 24,
}}
onPress={() => router.push("/new/add-project")}
>
<View className="flex-row items-center justify-between gap-3">
<View className="h-[22px] w-[22px] items-center justify-center rounded-full bg-subtle">
<SymbolView name="plus" size={13} tintColor={accentColor} type="monochrome" />
</View>
<View className="flex-1">
<Text className="text-[18px] font-t3-bold">Add new project</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</View>
</Pressable>
</View>
)}
</ScrollView>
+41
View File
@@ -0,0 +1,41 @@
import Stack from "expo-router/stack";
import { useColorScheme } from "react-native";
import { useResolveClassNames } from "uniwind";
export const unstable_settings = {
anchor: "index",
};
export default function SettingsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const isDark = useColorScheme() === "dark";
const sheetBg = isDark ? "rgba(14, 14, 14, 0.98)" : "rgba(242, 242, 247, 0.98)";
const headerTint = isDark ? "#f5f5f5" : "#262626";
return (
<Stack
screenOptions={{
contentStyle,
headerBackButtonDisplayMode: "minimal",
headerShadowVisible: false,
headerStyle: { backgroundColor: sheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
}}
>
<Stack.Screen name="index" options={{ animation: "none", title: "Settings" }} />
<Stack.Screen
name="environments"
options={{ animation: "slide_from_right", title: "Environments" }}
/>
<Stack.Screen
name="environment-new"
options={{ animation: "slide_from_right", title: "Add Environment" }}
/>
<Stack.Screen
name="waitlist"
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
/>
</Stack>
);
}
@@ -0,0 +1 @@
export { default } from "../connections/new";
@@ -0,0 +1,275 @@
import { useAuth } from "@clerk/expo";
import { Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Effect from "effect/Effect";
import { useCallback, useMemo, useState } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { connectCloudEnvironment } from "../../features/cloud/linkEnvironment";
import {
hasCloudPublicConfig,
resolveRelayClerkTokenOptions,
} from "../../features/cloud/publicConfig";
import {
useManagedRelayEnvironments,
useManagedRelayEnvironmentStatus,
} from "../../features/cloud/managedRelayState";
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
import { cn } from "../../lib/cn";
import { mobileRuntime } from "../../lib/runtime";
import { useThemeColor } from "../../lib/useThemeColor";
import {
connectSavedEnvironment,
useRemoteConnections,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
export default function SettingsEnvironmentsRouteScreen() {
const {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onUpdateEnvironment,
} = useRemoteConnections();
const router = useRouter();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const accentColor = useThemeColor("--color-icon-muted");
const handleToggle = useCallback((environmentId: EnvironmentId) => {
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
}, []);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: "Environments",
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="plus"
onPress={() => router.push("/settings/environment-new")}
separateBackground
/>
</Stack.Toolbar>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
{hasEnvironments ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{connectedEnvironments.map((environment, index) => (
<View
key={environment.environmentId}
collapsable={false}
style={{
borderTopWidth: index === 0 ? 0 : 1,
}}
className={cn(index !== 0 && "border-border")}
>
<ConnectionEnvironmentRow
environment={environment}
expanded={expandedId === environment.environmentId}
onToggle={() => handleToggle(environment.environmentId)}
onReconnect={onReconnectEnvironment}
onRemove={onRemoveEnvironmentPress}
onUpdate={onUpdateEnvironment}
/>
</View>
))}
</View>
) : (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
<View className="h-12 w-12 items-center justify-center rounded-[16px] bg-subtle">
<SymbolView
name="point.3.connected.trianglepath.dotted"
size={20}
tintColor={accentColor}
type="monochrome"
/>
</View>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
No environments connected yet.{"\n"}Tap{" "}
<Text className="font-t3-bold text-foreground">+</Text> to add one.
</Text>
</View>
)}
{hasCloudPublicConfig() ? <ConfiguredCloudEnvironmentRows /> : null}
</ScrollView>
</View>
);
}
function ConfiguredCloudEnvironmentRows() {
const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { savedConnectionsById } = useRemoteEnvironmentState();
const cloudEnvironmentsState = useManagedRelayEnvironments();
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>(
null,
);
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = useMemo(
() =>
(cloudEnvironmentsState.data ?? []).filter(
(environment) => savedConnectionsById[environment.environmentId] === undefined,
),
[cloudEnvironmentsState.data, savedConnectionsById],
);
const handleConnectCloudEnvironment = useCallback(
async (environment: RelayClientEnvironmentRecord) => {
setConnectingCloudEnvironmentId(environment.environmentId);
try {
const token = await getToken(resolveRelayClerkTokenOptions());
if (!token) {
throw new Error("Sign in to T3 Cloud before connecting.");
}
await mobileRuntime.runPromise(
connectCloudEnvironment({
clerkToken: token,
environment,
}).pipe(Effect.flatMap(connectSavedEnvironment)),
);
} catch (error) {
Alert.alert(
"Connect failed",
error instanceof Error ? error.message : "Could not connect to this environment.",
);
} finally {
setConnectingCloudEnvironmentId(null);
}
},
[getToken],
);
if (!isSignedIn) return null;
return (
<View collapsable={false} className="mt-5 gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable
accessibilityRole="button"
disabled={cloudEnvironmentsState.isPending}
onPress={cloudEnvironmentsState.refresh}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{cloudEnvironmentsState.isPending ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
)}
</Pressable>
</View>
{availableCloudEnvironments.length > 0 ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
isConnecting={connectingCloudEnvironmentId === environment.environmentId}
onConnect={() => handleConnectCloudEnvironment(environment)}
/>
))}
</View>
) : cloudEnvironmentsState.data === null ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : cloudEnvironmentsState.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-[15px] font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-[13px] leading-[18px] text-foreground-muted">
{cloudEnvironmentsState.error}
</Text>
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-[14px] leading-[20px] text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
</View>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayClientEnvironmentRecord;
readonly borderTop: boolean;
readonly isConnecting: boolean;
readonly onConnect: () => void;
}) {
const mutedColor = useThemeColor("--color-icon-muted");
const statusState = useManagedRelayEnvironmentStatus(props.environment);
const status = statusState.data;
const disabled = props.isConnecting;
const statusText =
status === null
? (statusState.error ?? (statusState.isPending ? "Checking status..." : "Status unavailable"))
: status.status === "online"
? "Online"
: (status.error ?? "Offline");
return (
<View
collapsable={false}
className={cn(
"flex-row items-center gap-3 bg-card px-4 py-3.5",
props.borderTop && "border-t border-border",
)}
>
<View className="h-9 w-9 items-center justify-center rounded-[14px] bg-subtle">
<SymbolView
name="cloud"
size={17}
tintColor={mutedColor}
type="monochrome"
weight="semibold"
/>
</View>
<View className="min-w-0 flex-1 gap-0.5">
<Text className="text-[16px] font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
{props.environment.label}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{props.environment.endpoint.httpBaseUrl}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{statusText}
</Text>
</View>
<Pressable
accessibilityRole="button"
disabled={disabled}
onPress={props.onConnect}
className="min-h-[40px] min-w-[88px] items-center justify-center rounded-[14px] bg-primary px-4 active:opacity-70 disabled:opacity-50"
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">
{props.isConnecting ? "Connecting" : "Connect"}
</Text>
</Pressable>
</View>
);
}
+446
View File
@@ -0,0 +1,446 @@
import { useAuth, useUser } from "@clerk/expo";
import * as Notifications from "expo-notifications";
import { Link, Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import * as Effect from "effect/Effect";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { ComponentProps, ReactNode } from "react";
import { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences";
import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions";
import { refreshAgentAwarenessRegistration } from "../../features/agent-awareness/remoteRegistration";
import { refreshManagedRelayEnvironments } from "../../features/cloud/managedRelayState";
import {
hasCloudPublicConfig,
resolveRelayClerkTokenOptions,
} from "../../features/cloud/publicConfig";
import { mobileRuntime } from "../../lib/runtime";
import { loadPreferences } from "../../lib/storage";
import { useThemeColor } from "../../lib/useThemeColor";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
export default function SettingsRouteScreen() {
return hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />;
}
function LocalSettingsRouteScreen() {
const insets = useSafeAreaInsets();
const { savedConnectionsById } = useRemoteEnvironmentState();
const environmentCount = Object.keys(savedConnectionsById).length;
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ title: "Settings" }} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<SettingsSection title="Configuration">
<SettingsRow
icon="desktopcomputer"
label="Environments"
value={`${environmentCount}`}
href="/settings/environments"
/>
</SettingsSection>
<AppSettingsSection />
</ScrollView>
</View>
);
}
function ConfiguredSettingsRouteScreen() {
const insets = useSafeAreaInsets();
const { push } = useRouter();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { savedConnectionsById } = useRemoteEnvironmentState();
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
const environmentCount = connections.length;
const accountLabel = useMemo(() => {
if (!isLoaded) return "Checking";
if (!isSignedIn) return "Request access";
return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
}, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
const refreshNotifications = useCallback(async () => {
if (process.env.EXPO_OS !== "ios") {
setNotificationStatus("unsupported");
return;
}
const permission = await Notifications.getPermissionsAsync();
setNotificationStatus(permission.granted ? "enabled" : "disabled");
}, []);
useEffect(() => {
void refreshNotifications();
}, [refreshNotifications]);
useEffect(() => {
if (!isLoaded) {
setLiveActivityStatus("checking");
return;
}
if (!isSignedIn) {
setLiveActivityStatus("signed-out");
return;
}
void loadPreferences().then(
(preferences) => {
setLiveActivityStatus(preferences.liveActivitiesEnabled === false ? "disabled" : "enabled");
},
() => {
setLiveActivityStatus("enabled");
},
);
}, [isLoaded, isSignedIn]);
const requestNotifications = useCallback(async () => {
try {
const result = await mobileRuntime.runPromise(
requestAgentNotificationPermission.pipe(
Effect.tap((permission) =>
permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
),
),
);
if (result.type === "granted") {
setNotificationStatus("enabled");
Alert.alert(
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
);
return;
}
if (result.type === "unsupported") {
setNotificationStatus("unsupported");
Alert.alert(
"Notifications unavailable",
"Live Activity notifications are only available on iOS.",
);
return;
}
setNotificationStatus("disabled");
if (result.canAskAgain) {
Alert.alert("Notifications disabled", "Notifications were not enabled.");
return;
}
Alert.alert(
"Notifications disabled",
"Notifications were denied for this app. Open Settings to enable them.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
);
} catch (error) {
Alert.alert(
"Notifications unavailable",
error instanceof Error ? error.message : "Could not request notification permission.",
);
}
}, []);
const promptSignIn = useCallback(() => {
Alert.alert(
"Request T3 Cloud access",
"Live Activity updates require approved T3 Cloud access so relay can deliver updates to this device.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Continue", onPress: () => push("/settings/waitlist") },
],
);
}, [push]);
const linkEnvironments = useCallback(async () => {
if (!isSignedIn) {
promptSignIn();
return;
}
setLiveActivityStatus("linking");
try {
const token = await getToken(resolveRelayClerkTokenOptions());
if (!token) {
promptSignIn();
setLiveActivityStatus("signed-out");
return;
}
await mobileRuntime.runPromise(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: token,
connections,
}),
);
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
} catch (error) {
setLiveActivityStatus("disabled");
Alert.alert(
"Live Activities unavailable",
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
);
}
}, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
const handleDeviceNotificationsChange = useCallback(
(enabled: boolean) => {
if (enabled) {
void requestNotifications();
return;
}
Alert.alert(
"Disable notifications",
"Notification permission is controlled by iOS. Open Settings to disable notifications for T3 Code.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
);
},
[requestNotifications],
);
const handleLiveActivitiesChange = useCallback(
(enabled: boolean) => {
if (!enabled) {
setLiveActivityStatus("disabled");
void (async () => {
try {
const token = isSignedIn ? await getToken(resolveRelayClerkTokenOptions()) : null;
await mobileRuntime.runPromise(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: token,
connections,
}),
);
refreshManagedRelayEnvironments();
} catch {
// The switch is optimistic; a future refresh reconciles relay state.
}
})();
return;
}
if (!isSignedIn) {
promptSignIn();
return;
}
void linkEnvironments();
},
[connections, getToken, isSignedIn, linkEnvironments, promptSignIn],
);
const openAccount = useCallback(() => {
if (!isLoaded) return;
if (!isSignedIn) {
push("/settings/waitlist");
return;
}
Alert.alert(
"T3 Cloud unavailable",
"Native T3 Cloud account management is not available in this build.",
);
}, [isLoaded, isSignedIn, push]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ title: "Settings" }} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<View className="gap-3">
<SettingsSection title="Account">
<SettingsRow
icon="person.crop.circle"
label="T3 Account"
value={accountLabel}
onPress={openAccount}
/>
</SettingsSection>
<Text className="px-2 text-[13px] leading-[18px] text-foreground-muted">
T3 Code works locally without signing in. Cloud features are optional.
</Text>
</View>
<SettingsSection title="Configuration">
<SettingsRow
icon="desktopcomputer"
label="Environments"
value={`${environmentCount}`}
href="/settings/environments"
/>
<SettingsSwitchRow
icon="bell.badge"
label="Device Notifications"
disabled={notificationStatus === "checking" || notificationStatus === "unsupported"}
value={notificationStatus === "enabled"}
onValueChange={handleDeviceNotificationsChange}
/>
<SettingsSwitchRow
disabled={
!isLoaded || liveActivityStatus === "checking" || liveActivityStatus === "linking"
}
icon="bolt.circle"
label="Live Activity Updates"
value={liveActivityStatus === "enabled" || liveActivityStatus === "linking"}
onValueChange={handleLiveActivitiesChange}
/>
</SettingsSection>
<AppSettingsSection />
</ScrollView>
</View>
);
}
type SymbolName = ComponentProps<typeof SymbolView>["name"];
function SettingsSection(props: { readonly title: string; readonly children: ReactNode }) {
return (
<View className="gap-2">
<Text className="px-2 font-t3-bold text-[17px] text-foreground-tertiary">{props.title}</Text>
<View
className="overflow-hidden rounded-[28px] bg-card"
style={{ borderCurve: "continuous" }}
>
{props.children}
</View>
</View>
);
}
function AppSettingsSection() {
const icon = useThemeColor("--color-icon");
return (
<SettingsSection title="App">
<View className="flex-row items-center gap-4 p-4">
<SymbolView
name="info.circle"
size={22}
tintColor={icon}
type="monochrome"
weight="regular"
/>
<Text className="flex-1 text-[17px] text-foreground">Version</Text>
<Text className="text-[17px] text-foreground-muted">Alpha</Text>
</View>
</SettingsSection>
);
}
function SettingsRow(props: {
readonly disabled?: boolean;
readonly icon: SymbolName;
readonly label: string;
readonly value?: string;
readonly href?: "/settings/environments";
readonly onPress?: () => void;
}) {
const icon = useThemeColor("--color-icon");
const chevron = useThemeColor("--color-chevron");
const content = (
<View
className="flex-row items-center gap-4 p-4"
style={{ opacity: props.disabled ? 0.45 : 1 }}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
{props.value ? (
<Text
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
numberOfLines={1}
>
{props.value}
</Text>
) : null}
<SymbolView
name="chevron.right"
size={16}
tintColor={chevron}
type="monochrome"
weight="semibold"
/>
</View>
);
if (props.href) {
return (
<Link href={props.href} asChild>
<Pressable>{content}</Pressable>
</Link>
);
}
return (
<Pressable accessibilityRole="button" disabled={props.disabled} onPress={props.onPress}>
{content}
</Pressable>
);
}
function SettingsSwitchRow(props: {
readonly disabled?: boolean;
readonly icon: SymbolName;
readonly label: string;
readonly value: boolean;
readonly onValueChange: (value: boolean) => void;
}) {
const icon = useThemeColor("--color-icon");
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
return (
<View
className="flex-row items-center gap-4 p-4"
style={{ opacity: props.disabled ? 0.45 : 1 }}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { Redirect, Stack } from "expo-router";
import { ScrollView } from "react-native";
import { CloudWaitlistEnrollment } from "../../features/cloud/CloudWaitlistEnrollment";
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
import { useNativeClerkAuthModal } from "../../features/cloud/useNativeClerkAuthModal";
export default function SettingsWaitlistRouteScreen() {
return hasCloudPublicConfig() ? (
<ConfiguredSettingsWaitlistRouteScreen />
) : (
<Redirect href="/settings" />
);
}
function ConfiguredSettingsWaitlistRouteScreen() {
const { presentAuth } = useNativeClerkAuthModal();
return (
<>
<Stack.Screen options={{ title: "Join the waitlist" }} />
<ScrollView
automaticallyAdjustKeyboardInsets
contentContainerStyle={{
paddingBottom: 32,
paddingHorizontal: 20,
paddingTop: 12,
}}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="interactive"
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
<CloudWaitlistEnrollment onSignIn={() => void presentAuth()} />
</ScrollView>
</>
);
}
@@ -17,6 +17,7 @@ export default function ThreadLayout() {
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
headerTitle: "",
}}
/>
<Stack.Screen
@@ -0,0 +1,247 @@
import { SymbolView } from "expo-symbols";
import type { ComponentProps, ReactNode } from "react";
import { useCallback, useMemo, useState } from "react";
import {
Pressable,
ScrollView,
View,
useColorScheme,
type LayoutChangeEvent,
type NativeScrollEvent,
type NativeSyntheticEvent,
type StyleProp,
type ViewStyle,
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
import { AppText as Text } from "./AppText";
export const COMPOSER_TOOLBAR_CONTROL_HEIGHT = 44;
export const COMPOSER_TOOLBAR_GAP = 8;
export const COMPOSER_TOOLBAR_FADE_WIDTH = 18;
const COMPOSER_TOOLBAR_SCROLL_EPSILON = 4;
export function ComposerToolbarRow(props: {
readonly children: ReactNode;
readonly paddingBottom?: number;
readonly paddingHorizontal?: number;
readonly paddingTop?: number;
readonly style?: StyleProp<ViewStyle>;
}) {
return (
<View
style={[
{
alignItems: "center",
flexDirection: "row",
gap: 6,
paddingBottom: props.paddingBottom ?? 8,
paddingHorizontal: props.paddingHorizontal ?? 6,
paddingTop: props.paddingTop ?? 8,
},
props.style,
]}
>
{props.children}
</View>
);
}
export function ComposerToolbarScroller(props: {
readonly children: ReactNode;
readonly fadeOpaque: string;
readonly fadeTransparent: string;
readonly contentPaddingRight?: number;
}) {
const [metrics, setMetrics] = useState({
contentWidth: 0,
offsetX: 0,
viewportWidth: 0,
});
const scrollEdges = useMemo(() => {
const maxOffset = Math.max(0, metrics.contentWidth - metrics.viewportWidth);
return {
showLeftFade: metrics.offsetX > COMPOSER_TOOLBAR_SCROLL_EPSILON,
showRightFade: metrics.offsetX < maxOffset - COMPOSER_TOOLBAR_SCROLL_EPSILON,
};
}, [metrics]);
const handleLayout = useCallback((event: LayoutChangeEvent) => {
const viewportWidth = event.nativeEvent.layout.width;
setMetrics((current) =>
current.viewportWidth === viewportWidth ? current : { ...current, viewportWidth },
);
}, []);
const handleContentSizeChange = useCallback((contentWidth: number) => {
setMetrics((current) =>
current.contentWidth === contentWidth ? current : { ...current, contentWidth },
);
}, []);
const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
const offsetX = event.nativeEvent.contentOffset.x;
setMetrics((current) =>
Math.abs(current.offsetX - offsetX) < 1 ? current : { ...current, offsetX },
);
}, []);
return (
<View className="min-w-0 flex-1" style={{ position: "relative" }}>
<ScrollView
horizontal
keyboardShouldPersistTaps="always"
onContentSizeChange={handleContentSizeChange}
onLayout={handleLayout}
onScroll={handleScroll}
scrollEventThrottle={16}
showsHorizontalScrollIndicator={false}
contentContainerStyle={{
alignItems: "center",
gap: COMPOSER_TOOLBAR_GAP,
paddingLeft: 0,
paddingRight: props.contentPaddingRight ?? 1,
}}
>
{props.children}
</ScrollView>
{scrollEdges.showLeftFade ? (
<View
pointerEvents="none"
style={{
bottom: 0,
experimental_backgroundImage: `linear-gradient(to right, ${props.fadeOpaque} 0%, ${props.fadeTransparent} 100%)`,
left: 0,
position: "absolute",
top: 0,
width: COMPOSER_TOOLBAR_FADE_WIDTH,
}}
/>
) : null}
{scrollEdges.showRightFade ? (
<View
pointerEvents="none"
style={{
bottom: 0,
experimental_backgroundImage: `linear-gradient(to right, ${props.fadeTransparent} 0%, ${props.fadeOpaque} 100%)`,
position: "absolute",
right: 0,
top: 0,
width: COMPOSER_TOOLBAR_FADE_WIDTH,
}}
/>
) : null}
</View>
);
}
export function ComposerToolbarButton(props: {
readonly icon?: ComponentProps<typeof SymbolView>["name"];
readonly iconNode?: ReactNode;
readonly label?: string;
readonly accessibilityLabel?: string;
readonly active?: boolean;
readonly disabled?: boolean;
readonly maxWidth?: number;
readonly minWidth?: number;
readonly onPress?: () => void;
readonly showChevron?: boolean;
readonly textTransform?: "none" | "uppercase";
readonly variant?: "default" | "primary" | "danger";
readonly style?: StyleProp<ViewStyle>;
}) {
const isDarkMode = useColorScheme() === "dark";
const iconColor = useThemeColor("--color-icon");
const iconSubtle = useThemeColor("--color-icon-subtle");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const variant = props.variant ?? "default";
const isCircle = !props.label && props.showChevron === false;
const defaultBorderColor = isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)";
const activeBorderColor = isDarkMode ? "rgba(255,255,255,0.13)" : "rgba(0,0,0,0.1)";
const filledBorderColor =
variant === "danger"
? "rgba(255,255,255,0.14)"
: props.disabled
? defaultBorderColor
: "rgba(255,255,255,0.18)";
const iconTintColor =
variant === "primary"
? props.disabled
? iconSubtle
: primaryFg
: variant === "danger"
? dangerFg
: iconColor;
return (
<Pressable
accessibilityLabel={props.accessibilityLabel ?? props.label}
accessibilityRole="button"
disabled={props.disabled}
onPress={props.onPress}
className={cn(
"h-11 flex-row items-center justify-center rounded-full active:opacity-70",
isCircle ? "w-11" : "gap-2 px-3.5",
variant === "primary"
? props.disabled
? "bg-subtle-strong"
: "bg-primary"
: variant === "danger"
? "bg-danger"
: props.active
? "bg-subtle-strong"
: "bg-subtle",
)}
style={({ pressed }) => [
{
borderColor:
variant === "default"
? props.active
? activeBorderColor
: defaultBorderColor
: filledBorderColor,
borderWidth: 1,
maxWidth: props.maxWidth ?? 172,
minWidth: props.minWidth,
opacity: props.disabled ? 0.55 : pressed ? 0.72 : 1,
shadowColor: "#000",
shadowOffset: { width: 0, height: isDarkMode ? 3 : 2 },
shadowOpacity: props.disabled ? 0 : isDarkMode ? 0.24 : 0.08,
shadowRadius: isDarkMode ? 10 : 8,
},
props.style,
]}
>
{props.iconNode ? (
<View className="h-4 w-4 items-center justify-center">{props.iconNode}</View>
) : props.icon ? (
<SymbolView name={props.icon} size={16} tintColor={iconTintColor} type="monochrome" />
) : null}
{props.label ? (
<Text
className={cn(
"shrink text-center text-[13px] font-t3-bold",
variant === "primary"
? props.disabled
? "text-foreground-muted"
: "text-primary-foreground"
: "text-foreground",
)}
ellipsizeMode="tail"
numberOfLines={1}
style={{ textTransform: props.textTransform ?? "none" }}
>
{props.label}
</Text>
) : null}
{props.showChevron === false ? null : (
<SymbolView name="chevron.down" size={11} tintColor={iconTintColor} type="monochrome" />
)}
</Pressable>
);
}
export const ComposerToolbarTrigger = ComposerToolbarButton;
+11 -2
View File
@@ -5,10 +5,14 @@ import { useThemeColor } from "../lib/useThemeColor";
import { AppText as Text } from "./AppText";
import { BrandMark } from "./BrandMark";
export function LoadingScreen(props: { readonly message: string }) {
export function LoadingScreen(props: {
readonly message: string;
readonly messagePlacement?: "above-spinner" | "below-spinner";
}) {
const colorScheme = useColorScheme();
const screenBg = useThemeColor("--color-screen");
const insets = useSafeAreaInsets();
const messagePlacement = props.messagePlacement ?? "below-spinner";
return (
<View className="flex-1 bg-screen" style={{ paddingTop: insets.top }}>
@@ -19,8 +23,13 @@ export function LoadingScreen(props: { readonly message: string }) {
/>
<View className="flex-1 items-center justify-center gap-5 px-6">
<BrandMark compact />
{messagePlacement === "above-spinner" ? (
<Text className="font-t3-bold text-lg text-foreground">{props.message}</Text>
) : null}
<ActivityIndicator size="large" />
<Text className="font-t3-bold text-lg text-foreground">{props.message}</Text>
{messagePlacement === "below-spinner" ? (
<Text className="font-t3-bold text-lg text-foreground">{props.message}</Text>
) : null}
</View>
</View>
);
@@ -0,0 +1,122 @@
import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type { EnvironmentId } from "@t3tools/contracts";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import { HttpClient } from "effect/unstable/http";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
vi.mock("../../lib/storage", () => ({
savePreferencesPatch: vi.fn(() => Promise.resolve()),
}));
vi.mock("../cloud/linkEnvironment", () => ({
linkEnvironmentToCloud: vi.fn(() => Effect.void),
}));
vi.mock("./remoteRegistration", () => ({
refreshAgentAwarenessRegistration: vi.fn(() => Effect.void),
}));
const connection: SavedRemoteConnection = {
environmentId: "env-1" as EnvironmentId,
environmentLabel: "Desktop",
pairingUrl: "https://desktop.example.test/",
displayUrl: "https://desktop.example.test/",
httpBaseUrl: "https://desktop.example.test/",
wsBaseUrl: "wss://desktop.example.test/ws",
bearerToken: "local-bearer",
};
const runWithHttpClient = <A, E>(
effect: Effect.Effect<A, E, HttpClient.HttpClient | ManagedRelayClient>,
): Promise<A> =>
Effect.runPromise(
effect.pipe(
Effect.provideService(ManagedRelayClient, null as never),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
),
);
describe("liveActivityPreferences", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("pushes disabled Live Activity preferences to relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: "clerk-token",
connections: [connection],
}),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
it("pushes enabled Live Activity preferences to relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: "clerk-token",
connections: [connection],
}),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
it("keeps local preferences refreshable when signed out", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: null,
connections: [connection],
}),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
});
it("does not try to re-link managed relay connections without bearer credentials", async () => {
const managedConnection: SavedRemoteConnection = {
...connection,
bearerToken: null,
};
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: "clerk-token",
connections: [connection, managedConnection],
}),
);
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
});
@@ -0,0 +1,34 @@
import * as Effect from "effect/Effect";
import { HttpClient } from "effect/unstable/http";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
export function setLiveActivityUpdatesEnabled(input: {
readonly enabled: boolean;
readonly clerkToken: string | null;
readonly connections: ReadonlyArray<SavedRemoteConnection>;
}): Effect.Effect<void, unknown, HttpClient.HttpClient | ManagedRelayClient> {
return Effect.gen(function* () {
yield* Effect.tryPromise({
try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }),
catch: (error) => error,
});
yield* refreshAgentAwarenessRegistration();
const clerkToken = input.clerkToken;
if (!clerkToken) {
return;
}
yield* Effect.forEach(
input.connections.filter((connection) => connection.bearerToken !== null),
(connection) => linkEnvironmentToCloud({ clerkToken, connection }),
{ concurrency: "unbounded" },
);
});
}
@@ -0,0 +1,106 @@
import { describe, expect, it } from "vite-plus/test";
import {
extractAgentNotificationDeepLink,
routeAgentNotificationResponseOnce,
} from "./notificationPayload";
function responseWithData(data: Record<string, unknown>, identifier = "notification-1") {
return {
notification: {
request: {
identifier,
content: {
data,
},
},
},
};
}
describe("extractAgentNotificationDeepLink", () => {
it("uses explicit deep links from APNs payload data", () => {
expect(
extractAgentNotificationDeepLink(
responseWithData({
deepLink: "/threads/env/thread",
environmentId: "ignored",
threadId: "ignored",
}),
),
).toBe("/threads/env/thread");
});
it("normalizes explicit thread deep links from APNs payload data", () => {
expect(
extractAgentNotificationDeepLink(
responseWithData({
deepLink: "/threads/env%201/thread%2F2",
}),
),
).toBe("/threads/env%201/thread%2F2");
});
it("falls back to the thread route from environment and thread ids", () => {
expect(
extractAgentNotificationDeepLink(
responseWithData({
environmentId: "env 1",
threadId: "thread/2",
}),
),
).toBe("/threads/env%201/thread%2F2");
});
it("falls back to ids when explicit deep link is not an agent thread route", () => {
expect(
extractAgentNotificationDeepLink(
responseWithData({
deepLink: "/",
environmentId: "env",
threadId: "thread",
}),
),
).toBe("/threads/env/thread");
});
it("ignores malformed or external links", () => {
expect(
extractAgentNotificationDeepLink(responseWithData({ deepLink: "https://example.com" })),
).toBeNull();
expect(
extractAgentNotificationDeepLink(responseWithData({ deepLink: "/settings" })),
).toBeNull();
expect(
extractAgentNotificationDeepLink(responseWithData({ deepLink: "//example.com" })),
).toBeNull();
expect(
extractAgentNotificationDeepLink(responseWithData({ deepLink: "/threads/env/thread?x=1" })),
).toBeNull();
expect(extractAgentNotificationDeepLink({})).toBeNull();
});
});
describe("routeAgentNotificationResponseOnce", () => {
it("does not navigate twice when the initial and listener responses refer to one notification", () => {
const handledResponseIds = new Set<string>();
const navigations: Array<string> = [];
const response = responseWithData({
environmentId: "env",
threadId: "thread",
});
routeAgentNotificationResponseOnce({
handledResponseIds,
response,
navigate: (deepLink) => navigations.push(deepLink),
});
routeAgentNotificationResponseOnce({
handledResponseIds,
response,
navigate: (deepLink) => navigations.push(deepLink),
});
expect(navigations).toEqual(["/threads/env/thread"]);
});
});
@@ -0,0 +1,35 @@
import { useEffect, useRef } from "react";
import * as Notifications from "expo-notifications";
import { useRouter } from "expo-router";
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
export function useAgentNotificationNavigation(): void {
const router = useRouter();
const handledResponseIds = useRef(new Set<string>());
useEffect(() => {
const handleResponse = (response: Notifications.NotificationResponse): void => {
routeAgentNotificationResponseOnce({
handledResponseIds: handledResponseIds.current,
response,
navigate: (deepLink) => router.push(deepLink as never),
});
};
const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
void Notifications.getLastNotificationResponseAsync()
.then((response) => {
if (response) {
handleResponse(response);
return Notifications.clearLastNotificationResponseAsync();
}
return undefined;
})
.catch(() => undefined);
return () => {
subscription.remove();
};
}, [router]);
}
@@ -0,0 +1,106 @@
function dataFromNotificationResponse(response: unknown): Record<string, unknown> | null {
if (typeof response !== "object" || response === null) {
return null;
}
const notification = (response as { readonly notification?: unknown }).notification;
if (typeof notification !== "object" || notification === null) {
return null;
}
const request = (notification as { readonly request?: unknown }).request;
if (typeof request !== "object" || request === null) {
return null;
}
const content = (request as { readonly content?: unknown }).content;
if (typeof content !== "object" || content === null) {
return null;
}
const data = (content as { readonly data?: unknown }).data;
return typeof data === "object" && data !== null ? (data as Record<string, unknown>) : null;
}
function identifierFromNotificationResponse(response: unknown): string | null {
if (typeof response !== "object" || response === null) {
return null;
}
const notification = (response as { readonly notification?: unknown }).notification;
if (typeof notification !== "object" || notification === null) {
return null;
}
const request = (notification as { readonly request?: unknown }).request;
if (typeof request !== "object" || request === null) {
return null;
}
const identifier = (request as { readonly identifier?: unknown }).identifier;
return typeof identifier === "string" ? identifier : null;
}
function encodeThreadDeepLink(input: {
readonly environmentId: string;
readonly threadId: string;
}): string | null {
if (input.environmentId.length === 0 || input.threadId.length === 0) {
return null;
}
return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`;
}
function normalizeThreadDeepLink(value: string): string | null {
if (
value.trim() !== value ||
value.startsWith("//") ||
value.includes("?") ||
value.includes("#")
) {
return null;
}
const parts = value.split("/");
if (parts.length !== 4 || parts[0] !== "" || parts[1] !== "threads") {
return null;
}
try {
return encodeThreadDeepLink({
environmentId: decodeURIComponent(parts[2] ?? ""),
threadId: decodeURIComponent(parts[3] ?? ""),
});
} catch {
return null;
}
}
export function extractAgentNotificationDeepLink(response: unknown): string | null {
const data = dataFromNotificationResponse(response);
const deepLink = data?.deepLink;
if (typeof deepLink === "string") {
const normalizedDeepLink = normalizeThreadDeepLink(deepLink);
if (normalizedDeepLink) {
return normalizedDeepLink;
}
}
const environmentId = data?.environmentId;
const threadId = data?.threadId;
if (typeof environmentId === "string" && typeof threadId === "string") {
return encodeThreadDeepLink({ environmentId, threadId });
}
return null;
}
export function routeAgentNotificationResponseOnce(input: {
readonly handledResponseIds: Set<string>;
readonly response: unknown;
readonly navigate: (deepLink: string) => void;
}): void {
const responseId = identifierFromNotificationResponse(input.response);
if (responseId && input.handledResponseIds.has(responseId)) {
return;
}
if (responseId) {
input.handledResponseIds.add(responseId);
}
const deepLink = extractAgentNotificationDeepLink(input.response);
if (deepLink) {
input.navigate(deepLink);
}
}
@@ -0,0 +1,44 @@
import * as Notifications from "expo-notifications";
import * as Effect from "effect/Effect";
import { Platform } from "react-native";
export type NotificationPermissionResult =
| { readonly type: "unsupported" }
| { readonly type: "granted" }
| { readonly type: "denied"; readonly canAskAgain: boolean };
export const requestAgentNotificationPermission: Effect.Effect<
NotificationPermissionResult,
unknown
> = Effect.gen(function* () {
if (Platform.OS !== "ios") {
return { type: "unsupported" };
}
const existing = yield* Effect.tryPromise({
try: () => Notifications.getPermissionsAsync(),
catch: (error) => error,
});
if (existing.granted) {
return { type: "granted" };
}
if (!existing.canAskAgain) {
return { type: "denied", canAskAgain: false };
}
const requested = yield* Effect.tryPromise({
try: () =>
Notifications.requestPermissionsAsync({
ios: {
allowAlert: true,
allowBadge: true,
allowSound: true,
},
}),
catch: (error) => error,
});
return requested.granted
? { type: "granted" }
: { type: "denied", canAskAgain: requested.canAskAgain };
});
Loaded 100 of 821 files, more files were not shown because too many files have changed in this diff. Show more