Compare commits

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

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

test: clean up tests by removing cloudflare settings from configuration

feat: implement ManagedEndpointDnsClient for DNS operations with Cloudflare

refactor: simplify ManagedEndpointProvider by removing HTTP client dependencies

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

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

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

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
# Optional: T3 Cloud source builds
# Leave these unset to disable optional T3 Cloud features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
# 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
+59
View File
@@ -0,0 +1,59 @@
name: Deploy T3 Cloud relay
on:
push:
branches:
- main
permissions:
contents: read
id-token: none
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: false
- name: Install dependencies
run: vp install --frozen-lockfile
- name: Deploy production relay stage
run: vp run --filter t3code-relay deploy -- --stage prod --yes
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
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 }}
+76 -7
View File
@@ -166,12 +166,69 @@ jobs:
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
build:
name: Build ${{ matrix.label }}
relay_public_config:
name: Resolve T3 Cloud 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:
@@ -422,13 +479,18 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
needs: [preflight, relay_public_config, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: read
id-token: write
env:
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -577,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 }}
@@ -648,6 +713,9 @@ jobs:
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}" \
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
@@ -743,10 +811,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:
+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
+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": {
+2 -16
View File
@@ -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
+8
View File
@@ -48,6 +48,10 @@ We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
Relay observability: [docs/relay-observability.md](./docs/relay-observability.md)
T3 Cloud Clerk setup: [docs/t3-cloud-clerk.md](./docs/t3-cloud-clerk.md)
## If you REALLY want to contribute still.... read this first
Before local development, prepare the environment and install dependencies:
@@ -58,6 +62,10 @@ mise install
vp install
```
T3 Cloud is optional and disabled in a fresh clone. To enable it for web, desktop, and mobile source
builds, copy [`.env.example`](./.env.example) to `.env` at the repository root and set the canonical
public configuration there.
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
+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();
});
+163 -11
View File
@@ -3,6 +3,7 @@
import { spawnSync } from "node:child_process";
import {
copyFileSync,
chmodSync,
cpSync,
existsSync,
mkdirSync,
@@ -13,21 +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",
@@ -47,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) {
@@ -57,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 });
@@ -115,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"));
@@ -144,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);
@@ -152,13 +290,19 @@ 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;
}
@@ -173,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,
};
}
+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(() => {
@@ -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,
@@ -7,12 +7,15 @@ const {
exitMock,
getAppPathMock,
getVersionMock,
isDefaultProtocolClientMock,
onMock,
quitMock,
relaunchMock,
removeListenerMock,
requestSingleInstanceLockMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
setDesktopNameMock,
setDockIconMock,
setNameMock,
@@ -23,12 +26,15 @@ const {
exitMock: vi.fn(),
getAppPathMock: vi.fn(() => "/app"),
getVersionMock: vi.fn(() => "1.2.3"),
isDefaultProtocolClientMock: vi.fn(() => false),
onMock: vi.fn(),
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
requestSingleInstanceLockMock: vi.fn(() => true),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
setDesktopNameMock: vi.fn(),
setDockIconMock: vi.fn(),
setNameMock: vi.fn(),
@@ -46,14 +52,17 @@ vi.mock("electron", () => ({
},
getAppPath: getAppPathMock,
getVersion: getVersionMock,
isDefaultProtocolClient: isDefaultProtocolClientMock,
isPackaged: true,
name: "T3 Code",
on: onMock,
quit: quitMock,
relaunch: relaunchMock,
removeListener: removeListenerMock,
requestSingleInstanceLock: requestSingleInstanceLockMock,
runningUnderARM64Translation: false,
setAboutPanelOptions: setAboutPanelOptionsMock,
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
setAppUserModelId: setAppUserModelIdMock,
setDesktopName: setDesktopNameMock,
setName: setNameMock,
+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 & {
+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,105 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { afterEach } from "vitest";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
function makeHttpClientLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
);
}
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
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";
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "sign_in_attempt" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
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,
});
assert(forwardedRequest !== null);
assert.equal(
forwardedRequest.headers["content-type"],
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(forwardedRequest.body._tag, "Uint8Array");
if (forwardedRequest.body._tag === "Uint8Array") {
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
}
}).pipe(Effect.provide(layer));
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "client" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://clerk.t3.codes/v1/client",
method: "GET",
headers: {},
});
assert(forwardedRequest !== null);
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
}).pipe(Effect.provide(layer));
},
);
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,
);
});
});
+154
View File
@@ -0,0 +1,154 @@
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 * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { Headers, 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;
}
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,
}),
});
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
url,
{
headers: input.headers,
},
);
const request =
input.body === undefined
? requestWithoutBody
: HttpClientRequest.bodyText(
requestWithoutBody,
input.body,
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
);
const response = yield* HttpClient.execute(request).pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
}),
});
+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;
@@ -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 }),
});
}
@@ -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,
+73 -7
View File
@@ -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/cloud",
}),
);
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", "vite.config.ts"]
"include": ["src", "vite.config.ts", "../../scripts/lib"]
}
+10
View File
@@ -1,6 +1,14 @@
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: {
@@ -32,6 +40,7 @@ export default defineConfig({
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/main.ts"],
clean: true,
deps: {
@@ -44,6 +53,7 @@ export default defineConfig({
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/preload.ts"],
},
],
+8
View File
@@ -16,6 +16,10 @@ This app has three variants:
Run commands from `apps/mobile`.
T3 Cloud is optional and disabled in a fresh clone. Public configuration belongs in the
repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
[`../../.env.example`](../../.env.example).
## Development
Start Metro for the dev client:
@@ -63,6 +67,10 @@ The native lint task runs SwiftLint for Swift plus ktlint and detekt for Kotlin.
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
+35 -5
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,
@@ -96,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",
{
@@ -120,17 +130,37 @@ 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,
},
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
}
}
+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);
+8
View File
@@ -39,10 +39,13 @@
},
"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",
@@ -58,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",
@@ -70,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",
@@ -96,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>
);
}
+451
View File
@@ -0,0 +1,451 @@
import { useAuth, useUser, useUserProfileModal } 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 { isAvailable: isUserProfileModalAvailable, presentUserProfile } = useUserProfileModal();
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;
}
if (isUserProfileModalAvailable) {
void presentUserProfile();
return;
}
Alert.alert(
"T3 Cloud unavailable",
"Native T3 Cloud account management is not available in this build.",
);
}, [isLoaded, isSignedIn, isUserProfileModalAvailable, presentUserProfile, 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,256 @@
import { afterEach, beforeEach, vi } from "vitest";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import type { EnvironmentId, OrchestrationShellSnapshot, ThreadId } from "@t3tools/contracts";
import {
__resetAgentLiveActivitiesForTest,
refreshActiveLiveActivityRemoteRegistration,
syncAgentLiveActivitiesForSnapshot,
} from "./liveActivityController";
import { registerLiveActivityPushToken } from "./remoteRegistration";
const mocks = vi.hoisted(() => {
const existingActivity = {
update: vi.fn(() => Promise.resolve()),
end: vi.fn((_dismissal: unknown, _props?: unknown, _endedAt?: unknown) => Promise.resolve()),
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
return {
existingActivity,
getInstances: vi.fn(() => [existingActivity]),
start: vi.fn(() => existingActivity),
registerLiveActivityPushToken: vi.fn(
(): Effect.Effect<boolean, unknown> => Effect.succeed(true),
),
};
});
vi.mock("react-native", () => ({
Platform: {
OS: "ios",
},
}));
vi.mock("expo-linking", () => ({
default: {
createURL: vi.fn((path: string) => `t3code://${path}`),
},
createURL: vi.fn((path: string) => `t3code://${path}`),
}));
vi.mock("expo-widgets", () => ({
after: (date: Date) => ({ after: date }),
}));
vi.mock("../../lib/runtime", () => ({
mobileRuntime: {
runPromise: <A, E>(operation: Effect.Effect<A, E>) => Effect.runPromise(operation),
},
}));
vi.mock("../../widgets/AgentActivity", () => ({
default: {
getInstances: mocks.getInstances,
start: mocks.start,
},
}));
vi.mock("./remoteRegistration", () => ({
registerLiveActivityPushToken: mocks.registerLiveActivityPushToken,
}));
const runManagedRelayEffect = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> =>
Effect.runPromise(effect.pipe(Effect.provideService(ManagedRelayClient, null as never)));
function runningSnapshot(): OrchestrationShellSnapshot {
return {
projects: [
{
id: "project-1",
title: "Project",
},
],
threads: [
{
id: "thread-1" as ThreadId,
projectId: "project-1",
title: "Thread",
modelSelection: {
model: "gpt-5",
},
session: {
status: "running",
providerName: "Codex",
},
latestTurn: {
state: "running",
},
updatedAt: "2026-05-25T00:00:00.000Z",
hasPendingApprovals: false,
hasPendingUserInput: false,
},
],
} as unknown as OrchestrationShellSnapshot;
}
function completedSnapshot(): OrchestrationShellSnapshot {
return {
projects: [
{
id: "project-1",
title: "Project",
},
],
threads: [
{
id: "thread-1" as ThreadId,
projectId: "project-1",
title: "Thread",
modelSelection: {
model: "gpt-5",
},
session: null,
latestTurn: {
state: "completed",
},
updatedAt: "2026-05-25T00:01:00.000Z",
hasPendingApprovals: false,
hasPendingUserInput: false,
},
],
} as unknown as OrchestrationShellSnapshot;
}
describe("liveActivityController", () => {
beforeEach(() => {
vi.stubGlobal("__DEV__", false);
__resetAgentLiveActivitiesForTest();
mocks.existingActivity.update.mockClear();
mocks.existingActivity.end.mockClear();
mocks.existingActivity.getPushToken.mockClear();
mocks.existingActivity.addPushTokenListener.mockClear();
mocks.getInstances.mockClear();
mocks.getInstances.mockReturnValue([mocks.existingActivity]);
mocks.start.mockClear();
mocks.registerLiveActivityPushToken.mockClear();
mocks.registerLiveActivityPushToken.mockReturnValue(Effect.succeed(true));
});
afterEach(() => {
vi.useRealTimers();
});
it("adopts an existing remote-started Live Activity instead of creating a duplicate", async () => {
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
expect(mocks.getInstances).toHaveBeenCalledTimes(1);
expect(mocks.existingActivity.update).toHaveBeenCalledTimes(1);
expect(mocks.start).not.toHaveBeenCalled();
expect(registerLiveActivityPushToken).toHaveBeenCalledWith({
activity: mocks.existingActivity,
});
});
it("keeps skipped remote token registrations retryable after cloud sign-in", async () => {
mocks.registerLiveActivityPushToken
.mockReturnValueOnce(Effect.succeed(false))
.mockReturnValueOnce(Effect.succeed(true));
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
await runManagedRelayEffect(refreshActiveLiveActivityRemoteRegistration());
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2);
expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(2, {
activity: mocks.existingActivity,
});
});
it("retries cloud sign-in Live Activity token refresh failures", async () => {
vi.useFakeTimers();
mocks.registerLiveActivityPushToken
.mockReturnValueOnce(Effect.succeed(true))
.mockReturnValueOnce(Effect.fail(new Error("relay unavailable")))
.mockReturnValueOnce(Effect.succeed(true));
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
await runManagedRelayEffect(refreshActiveLiveActivityRemoteRegistration());
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(15_000);
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(3);
expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(3, {
activity: mocks.existingActivity,
});
});
it("retries adopted remote-start Live Activity token registration when the token is initially unavailable", async () => {
vi.useFakeTimers();
mocks.registerLiveActivityPushToken
.mockReturnValueOnce(Effect.succeed(false))
.mockReturnValueOnce(Effect.succeed(true));
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(15_000);
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2);
expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(2, {
activity: mocks.existingActivity,
});
});
it("ends active Live Activities with the terminal thread content state", async () => {
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: completedSnapshot(),
}),
);
expect(mocks.existingActivity.end).toHaveBeenCalledTimes(1);
expect(mocks.existingActivity.end.mock.calls[0]?.[1]).toMatchObject({
activeCount: 1,
activities: [
{
environmentId: "env-1",
threadId: "thread-1",
phase: "completed",
status: "Done",
},
],
});
});
});
@@ -0,0 +1,605 @@
import {
isTerminalAgentAwarenessPhase,
projectThreadAwareness,
type AgentAwarenessState,
} from "@t3tools/shared/agentAwareness";
import type {
EnvironmentId,
OrchestrationProjectShell,
OrchestrationShellSnapshot,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Semaphore from "effect/Semaphore";
import { after, type LiveActivity } from "expo-widgets";
import * as Linking from "expo-linking";
import { Platform } from "react-native";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import { mobileRuntime } from "../../lib/runtime";
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
import { registerLiveActivityPushToken } from "./remoteRegistration";
const MAX_LOCAL_LIVE_ACTIVITIES = 3;
const FINAL_ACTIVITY_DISMISSAL_MS = 5 * 60 * 1_000;
const REMOTE_TOKEN_REGISTRATION_RETRY_MS = 15_000;
const MISSING_STATE_GRACE_MS = 30_000;
interface ActiveDeviceActivity {
readonly instance: LiveActivity<AgentActivityProps>;
readonly props: AgentActivityProps;
readonly lastRemoteTokenRegistrationAttemptAt: number | null;
readonly remoteTokenRegistered: boolean;
readonly remoteTokenRetryScheduled: boolean;
readonly missingSince: number | null;
}
let activeActivity: ActiveDeviceActivity | null = null;
const environmentStates = new Map<EnvironmentId, ReadonlyArray<AgentAwarenessState>>();
let localLiveActivitiesEnabled = true;
const liveActivitySyncSemaphore = Effect.runSync(Semaphore.make(1));
function canUseLocalLiveActivities(): boolean {
return localLiveActivitiesEnabled && Platform.OS === "ios";
}
function logLiveActivityDebug(context: string, details?: unknown): void {
if (!__DEV__) {
return;
}
console.log(`[agent-awareness] ${context}`, details ?? "");
}
function logLiveActivityWarning(context: string, error: unknown): void {
if (!__DEV__) {
return;
}
console.warn(
`[agent-awareness] ${context}`,
error instanceof Error ? error.message : String(error),
);
}
function statusForPhase(phase: AgentAwarenessState["phase"]): string {
switch (phase) {
case "waiting_for_approval":
return "Approval";
case "waiting_for_input":
return "Input";
case "completed":
return "Done";
case "failed":
return "Failed";
case "starting":
return "Starting";
case "running":
return "Working";
case "stale":
return "Waiting";
}
}
function epochMillis(iso: string): number {
return Option.match(DateTime.make(iso), {
onNone: () => Number.NaN,
onSome: (dt) => dt.epochMilliseconds,
});
}
function currentTimeMillis(): number {
return Date.now();
}
function currentDateTime(): DateTime.Utc {
return DateTime.nowUnsafe();
}
function toActivityProps(states: ReadonlyArray<AgentAwarenessState>): AgentActivityProps {
const updatedAt = states.reduce<string | null>((latest, state) => {
if (latest === null) {
return state.updatedAt;
}
return epochMillis(state.updatedAt) > epochMillis(latest) ? state.updatedAt : latest;
}, null);
return {
title: "T3 Code",
subtitle: "Agent work in progress",
activeCount: states.length,
updatedAt: updatedAt ?? DateTime.formatIso(currentDateTime()),
activities: states.slice(0, MAX_LOCAL_LIVE_ACTIVITIES).map((state) => ({
environmentId: state.environmentId,
threadId: state.threadId,
projectTitle: state.projectTitle,
threadTitle: state.threadTitle,
modelTitle: state.modelTitle,
phase: state.phase,
status: statusForPhase(state.phase),
updatedAt: state.updatedAt,
deepLink: state.deepLink,
})),
};
}
function hasSameActivityContent(left: AgentActivityProps, right: AgentActivityProps): boolean {
return JSON.stringify(left) === JSON.stringify(right);
}
function sortByUpdatedAtDesc(left: AgentAwarenessState, right: AgentAwarenessState): number {
return epochMillis(right.updatedAt) - epochMillis(left.updatedAt);
}
function projectSnapshotAwareness(input: {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot;
}): ReadonlyArray<AgentAwarenessState> {
const projectsById = new Map<string, OrchestrationProjectShell>(
input.snapshot.projects.map((project) => [project.id, project]),
);
const states: AgentAwarenessState[] = [];
for (const thread of input.snapshot.threads) {
const project = projectsById.get(thread.projectId);
if (!project) {
continue;
}
const state = projectThreadAwareness({
environmentId: input.environmentId,
project,
thread,
});
if (state) {
states.push(state);
}
}
return states;
}
export function syncAgentLiveActivitiesForSnapshot(input: {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot | null;
}): Effect.Effect<void, unknown> {
return enqueueLiveActivitySync(
Effect.gen(function* () {
if (!canUseLocalLiveActivities()) {
return;
}
if (input.snapshot === null) {
return yield* endEnvironmentLiveActivitiesNow(input.environmentId);
}
const states = projectSnapshotAwareness({
environmentId: input.environmentId,
snapshot: input.snapshot,
});
environmentStates.set(input.environmentId, states);
return yield* syncAgentLiveActivities();
}),
);
}
export function endEnvironmentLiveActivities(
environmentId: EnvironmentId,
): Effect.Effect<void, unknown> {
return enqueueLiveActivitySync(endEnvironmentLiveActivitiesNow(environmentId));
}
function endEnvironmentLiveActivitiesNow(
environmentId: EnvironmentId,
): Effect.Effect<void, unknown> {
return Effect.gen(function* () {
environmentStates.delete(environmentId);
return yield* syncAgentLiveActivities();
});
}
export function endAllAgentLiveActivities(): Effect.Effect<void, unknown> {
return enqueueLiveActivitySync(endAllAgentLiveActivitiesNow());
}
function endAllAgentLiveActivitiesNow(): Effect.Effect<void, unknown> {
return Effect.gen(function* () {
environmentStates.clear();
return yield* endActiveActivity(null, "all-ended");
});
}
function enqueueLiveActivitySync<T, R>(
operation: Effect.Effect<T, unknown, R>,
): Effect.Effect<T, unknown, R> {
return liveActivitySyncSemaphore.withPermits(1)(operation);
}
function syncAgentLiveActivities(): Effect.Effect<void, unknown> {
const states = [...environmentStates.values()].flat().sort(sortByUpdatedAtDesc);
const activeNonTerminalStates = states.filter(
(state) => !isTerminalAgentAwarenessPhase(state.phase),
);
const terminalState = states.find((state) => isTerminalAgentAwarenessPhase(state.phase)) ?? null;
if (activeNonTerminalStates.length === 0) {
if (!activeActivity) {
return Effect.void;
}
if (terminalState) {
return endActiveActivity(terminalState, "terminal-state");
}
const now = currentTimeMillis();
if (activeActivity.missingSince === null) {
activeActivity = { ...activeActivity, missingSince: now };
logLiveActivityDebug("live activity missing state; waiting before ending", {
graceMs: MISSING_STATE_GRACE_MS,
});
return Effect.void;
}
if (now - activeActivity.missingSince >= MISSING_STATE_GRACE_MS) {
return endActiveActivity(null, "missing-state");
}
return Effect.void;
}
return startOrUpdateActivity(activeNonTerminalStates);
}
function startOrUpdateActivity(
states: ReadonlyArray<AgentAwarenessState>,
): Effect.Effect<void, unknown> {
const props = toActivityProps(states);
const primaryState = states[0];
if (activeActivity) {
const active = activeActivity;
if (!hasSameActivityContent(active.props, props)) {
logLiveActivityDebug("updating live activity", {
activeCount: props.activeCount,
primaryThreadId: primaryState?.threadId ?? null,
});
return runLiveActivityOperation(
"update",
Effect.tryPromise({
try: () => active.instance.update(props),
catch: (error) => error,
}),
).pipe(
Effect.flatMap((updated) =>
Effect.sync(() => {
if (!updated.ok) {
activeActivity = null;
return;
}
activeActivity = { ...active, props, missingSince: null };
retryRemoteTokenRegistration(activeActivity.instance);
}),
),
);
} else if (activeActivity.missingSince !== null) {
activeActivity = { ...activeActivity, missingSince: null };
}
retryRemoteTokenRegistration(activeActivity.instance);
return Effect.void;
}
return adoptExistingActivity(props, primaryState).pipe(
Effect.flatMap((adopted) => {
if (adopted) {
return Effect.void;
}
logLiveActivityDebug("starting live activity", {
activeCount: props.activeCount,
primaryThreadId: primaryState?.threadId ?? null,
});
return runLiveActivityOperation(
"start",
Effect.try({
try: () => AgentActivity.start(props, Linking.createURL(primaryState?.deepLink ?? "/")),
catch: (error) => error,
}),
).pipe(
Effect.flatMap((started) =>
Effect.sync(() => {
const instance = started.ok ? started.value : undefined;
if (instance) {
logLiveActivityDebug("live activity started", {
primaryThreadId: primaryState?.threadId ?? null,
localActivityCount: AgentActivity.getInstances().length,
rowCount: props.activeCount,
});
activeActivity = {
instance,
props,
lastRemoteTokenRegistrationAttemptAt: null,
remoteTokenRegistered: false,
remoteTokenRetryScheduled: false,
missingSince: null,
};
retryRemoteTokenRegistration(instance);
}
}),
),
);
}),
);
}
function adoptExistingActivity(
props: AgentActivityProps,
primaryState: AgentAwarenessState | undefined,
): Effect.Effect<boolean, unknown> {
const existingActivity = AgentActivity.getInstances()[0];
if (!existingActivity) {
return Effect.succeed(false);
}
logLiveActivityDebug("adopting existing live activity", {
activeCount: props.activeCount,
primaryThreadId: primaryState?.threadId ?? null,
});
return runLiveActivityOperation(
"update",
Effect.tryPromise({
try: () => existingActivity.update(props),
catch: (error) => error,
}),
).pipe(
Effect.flatMap((updated) =>
Effect.sync(() => {
if (!updated.ok) {
return false;
}
activeActivity = {
instance: existingActivity,
props,
lastRemoteTokenRegistrationAttemptAt: null,
remoteTokenRegistered: false,
remoteTokenRetryScheduled: false,
missingSince: null,
};
retryRemoteTokenRegistration(existingActivity);
return true;
}),
),
);
}
function retryRemoteTokenRegistration(activity: LiveActivity<AgentActivityProps>): void {
if (!activeActivity) {
return;
}
if (activeActivity.remoteTokenRegistered) {
return;
}
const now = currentTimeMillis();
if (
activeActivity.lastRemoteTokenRegistrationAttemptAt !== null &&
now - activeActivity.lastRemoteTokenRegistrationAttemptAt < REMOTE_TOKEN_REGISTRATION_RETRY_MS
) {
return;
}
activeActivity = {
...activeActivity,
lastRemoteTokenRegistrationAttemptAt: now,
};
void mobileRuntime
.runPromise(
registerRemoteActivityToken(activity).pipe(
Effect.flatMap((registered) =>
Effect.sync(() => {
if (!registered) {
scheduleRemoteTokenRegistrationRetry(activity);
}
}),
),
Effect.catch((error) =>
Effect.sync(() => {
logLiveActivityWarning(
"live activity token registration failed; retry scheduled",
error,
);
scheduleRemoteTokenRegistrationRetry(activity);
}),
),
),
)
.catch((error: unknown) => {
logLiveActivityWarning("unexpected live activity token registration failure", error);
});
}
function registerRemoteActivityToken(
activity: LiveActivity<AgentActivityProps>,
): Effect.Effect<boolean, unknown, ManagedRelayClient> {
return registerLiveActivityPushToken({ activity }).pipe(
Effect.flatMap((registered) =>
Effect.sync(() => {
if (registered && activeActivity?.instance === activity) {
activeActivity = {
...activeActivity,
remoteTokenRegistered: true,
remoteTokenRetryScheduled: false,
};
}
return registered;
}),
),
);
}
function scheduleRemoteTokenRegistrationRetry(activity: LiveActivity<AgentActivityProps>): void {
if (
!activeActivity ||
activeActivity.instance !== activity ||
activeActivity.remoteTokenRegistered ||
activeActivity.remoteTokenRetryScheduled
) {
return;
}
activeActivity = {
...activeActivity,
remoteTokenRetryScheduled: true,
};
void mobileRuntime
.runPromise(
Effect.sleep(Duration.millis(REMOTE_TOKEN_REGISTRATION_RETRY_MS)).pipe(
Effect.flatMap(() =>
enqueueLiveActivitySync(
Effect.sync(() => {
if (!activeActivity || activeActivity.instance !== activity) {
return;
}
activeActivity = {
...activeActivity,
remoteTokenRetryScheduled: false,
lastRemoteTokenRegistrationAttemptAt: null,
};
retryRemoteTokenRegistration(activity);
}),
),
),
Effect.catch((error) =>
Effect.sync(() => {
logLiveActivityWarning("live activity token retry failed", error);
}),
),
),
)
.catch((error: unknown) => {
logLiveActivityWarning("unexpected live activity token retry failure", error);
});
}
export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
void,
unknown,
ManagedRelayClient
> {
return enqueueLiveActivitySync(
Effect.gen(function* () {
if (!activeActivity || !canUseLocalLiveActivities()) {
return;
}
const activity = activeActivity.instance;
activeActivity = {
...activeActivity,
remoteTokenRegistered: false,
remoteTokenRetryScheduled: false,
lastRemoteTokenRegistrationAttemptAt: currentTimeMillis(),
};
yield* registerRemoteActivityToken(activity).pipe(
Effect.flatMap((registered) =>
Effect.sync(() => {
if (!registered) {
scheduleRemoteTokenRegistrationRetry(activity);
}
}),
),
Effect.catch((error) =>
Effect.sync(() => {
logLiveActivityWarning("live activity token refresh failed; retry scheduled", error);
scheduleRemoteTokenRegistrationRetry(activity);
}),
),
);
}),
);
}
function endActiveActivity(
finalState: AgentAwarenessState | null,
reason: string,
): Effect.Effect<void, unknown> {
const active = activeActivity;
if (!active) {
return Effect.void;
}
activeActivity = null;
logLiveActivityDebug("ending live activity", {
reason,
finalPhase: finalState?.phase ?? null,
});
if (finalState) {
const now = currentDateTime();
return runLiveActivityOperation(
"end",
Effect.tryPromise({
try: () =>
active.instance.end(
after(
DateTime.toDateUtc(DateTime.add(now, { milliseconds: FINAL_ACTIVITY_DISMISSAL_MS })),
),
toActivityProps([finalState]),
DateTime.toDateUtc(now),
),
catch: (error) => error,
}),
).pipe(Effect.asVoid);
}
return runLiveActivityOperation(
"end",
Effect.tryPromise({
try: () => active.instance.end("immediate"),
catch: (error) => error,
}),
).pipe(Effect.asVoid);
}
type LiveActivityOperationResult<T> =
| {
readonly ok: true;
readonly value: T;
}
| {
readonly ok: false;
};
function runLiveActivityOperation<T>(
operationName: "start" | "update" | "end",
operation: Effect.Effect<T, unknown>,
): Effect.Effect<LiveActivityOperationResult<T>> {
return operation.pipe(
Effect.match({
onSuccess: (value) => ({ ok: true, value }) as const,
onFailure: (error): LiveActivityOperationResult<T> => {
if (
(operationName === "end" || operationName === "update") &&
isMissingNativeLiveActivityError(error)
) {
logLiveActivityWarning(
`live activity ${operationName} skipped; native activity was already gone`,
error,
);
return { ok: false };
}
logLiveActivityWarning(
"live activity operation failed; disabling local live activities",
error,
);
localLiveActivitiesEnabled = false;
activeActivity = null;
environmentStates.clear();
return { ok: false };
},
}),
);
}
function isMissingNativeLiveActivityError(error: unknown): boolean {
return error instanceof Error && error.message.includes("Can't find live activity with id:");
}
export function __resetAgentLiveActivitiesForTest(): void {
localLiveActivitiesEnabled = true;
activeActivity = null;
environmentStates.clear();
}
@@ -0,0 +1,129 @@
import { beforeEach, vi } from "vitest";
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 { endAllAgentLiveActivities } from "./liveActivityController";
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("./liveActivityController", () => ({
endAllAgentLiveActivities: 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 local and relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: "clerk-token",
connections: [connection],
}),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(endAllAgentLiveActivities).toHaveBeenCalledTimes(1);
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
it("pushes enabled Live Activity preferences without ending active local activities", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: "clerk-token",
connections: [connection],
}),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(endAllAgentLiveActivities).not.toHaveBeenCalled();
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,39 @@
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 { endAllAgentLiveActivities } from "./liveActivityController";
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,
});
if (!input.enabled) {
yield* endAllAgentLiveActivities();
}
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 "vitest";
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 };
});
@@ -0,0 +1,33 @@
import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
import type { MobilePreferences } from "../../lib/storage";
export function makeRelayDeviceRegistrationRequest(input: {
readonly deviceId: string;
readonly label: string;
readonly iosMajorVersion: number;
readonly appVersion?: string;
readonly pushToken?: string;
readonly pushToStartToken?: string;
readonly notificationsEnabled: boolean;
readonly preferences: MobilePreferences;
}): RelayDeviceRegistrationRequest {
const liveActivitiesEnabled = input.preferences.liveActivitiesEnabled !== false;
return {
deviceId: input.deviceId,
label: input.label,
platform: "ios",
iosMajorVersion: input.iosMajorVersion,
appVersion: input.appVersion,
...(input.pushToken ? { pushToken: input.pushToken } : {}),
...(input.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
preferences: {
liveActivitiesEnabled,
notificationsEnabled: input.notificationsEnabled,
notifyOnApproval: true,
notifyOnInput: true,
notifyOnCompletion: true,
notifyOnFailure: true,
},
};
}
@@ -0,0 +1,413 @@
/// <reference types="node" />
import * as NodeCrypto from "node:crypto";
import { beforeEach, vi } from "vitest";
import { describe, expect, it } from "@effect/vitest";
import Constants from "expo-constants";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import type { ManagedRelayClient } from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { verifyDpopProof } from "@t3tools/shared/dpop";
import type { SavedRemoteConnection } from "../../lib/connection";
import { mobileCryptoLayer } from "../cloud/dpop";
import { mobileManagedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
__resetAgentAwarenessRemoteRegistrationForTest,
refreshAgentAwarenessRegistration,
normalizeAgentAwarenessRelayBaseUrl,
registerAgentAwarenessConnection,
registerLiveActivityPushToken,
setAgentAwarenessRelayTokenProvider,
shouldRegisterAgentAwarenessDeviceForProvider,
unregisterAgentAwarenessConnection,
} from "./remoteRegistration";
import * as Notifications from "expo-notifications";
const secureStore = vi.hoisted(() => new Map<string, string>());
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
version: "1.0.0",
extra: {},
},
},
}));
vi.mock("expo-widgets", () => ({
addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })),
}));
vi.mock("expo-notifications", () => ({
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
getPermissionsAsync: vi.fn(() => Promise.resolve({ granted: true })),
}));
vi.mock("expo-crypto", () => ({
CryptoDigestAlgorithm: {
SHA1: "SHA-1",
SHA256: "SHA-256",
SHA384: "SHA-384",
SHA512: "SHA-512",
},
getRandomBytes: (byteCount: number) => new Uint8Array(NodeCrypto.randomBytes(byteCount)),
getRandomBytesAsync: (byteCount: number) =>
Promise.resolve(new Uint8Array(NodeCrypto.randomBytes(byteCount))),
digest: (algorithm: string, data: unknown) => {
if (!(data instanceof Uint8Array)) {
return Promise.reject(new TypeError("expo-crypto digest data must be a typed array."));
}
return Promise.resolve(
new Uint8Array(NodeCrypto.createHash(algorithm).update(data).digest()).buffer,
);
},
}));
vi.mock("expo-secure-store", () => ({
getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null),
setItemAsync: (key: string, value: string) => {
secureStore.set(key, value);
return Promise.resolve();
},
}));
vi.mock("react-native", () => ({
Platform: {
OS: "ios",
Version: "18.0",
},
}));
vi.mock("../../lib/runtime", () => ({
mobileRuntime: {
runPromise: <A, E>(operation: Effect.Effect<A, E>) =>
Effect.runPromise(
operation.pipe(
Effect.provide(
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
),
),
),
),
},
}));
vi.mock("../../lib/storage", () => ({
loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadPreferences: vi.fn(() => Promise.resolve({})),
}));
function proofIat(proof: string): number {
const payload = proof.split(".")[1];
if (!payload) {
throw new Error("Missing DPoP payload.");
}
const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
readonly iat: number;
};
return decoded.iat;
}
function savedConnection(): SavedRemoteConnection {
return {
environmentId: "env-1" as EnvironmentId,
environmentLabel: "Desktop",
pairingUrl: "https://desktop.example/pair",
displayUrl: "https://desktop.example",
httpBaseUrl: "https://desktop.example",
wsBaseUrl: "wss://desktop.example/ws",
bearerToken: "bearer-token",
};
}
const runRegistrationEffect = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> =>
Effect.runPromise(
effect.pipe(
Effect.provide(
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
),
),
),
);
async function waitForFetchCalls(
fetchMock: ReturnType<typeof vi.fn>,
count: number,
): Promise<void> {
for (let attempt = 0; attempt < 20; attempt += 1) {
if (fetchMock.mock.calls.length >= count) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
describe("makeRelayDeviceRegistrationRequest", () => {
beforeEach(() => {
vi.unstubAllGlobals();
vi.stubGlobal("__DEV__", false);
secureStore.clear();
Constants.expoConfig!.extra = {};
__resetAgentAwarenessRemoteRegistrationForTest();
});
it("preserves disabled Live Activity preferences in relay registrations", () => {
expect(
makeRelayDeviceRegistrationRequest({
deviceId: "device-1",
label: "Julius's iPhone",
iosMajorVersion: 18,
appVersion: "1.0.0",
pushToken: "apns-token",
pushToStartToken: "push-to-start-token",
notificationsEnabled: true,
preferences: {
liveActivitiesEnabled: false,
},
}),
).toEqual({
deviceId: "device-1",
label: "Julius's iPhone",
platform: "ios",
iosMajorVersion: 18,
appVersion: "1.0.0",
pushToken: "apns-token",
pushToStartToken: "push-to-start-token",
preferences: {
liveActivitiesEnabled: false,
notificationsEnabled: true,
notifyOnApproval: true,
notifyOnInput: true,
notifyOnCompletion: true,
notifyOnFailure: true,
},
});
});
it("marks notification delivery disabled when APNs permission is unavailable", () => {
expect(
makeRelayDeviceRegistrationRequest({
deviceId: "device-1",
label: "Julius's iPhone",
iosMajorVersion: 18,
appVersion: "1.0.0",
pushToStartToken: "push-to-start-token",
notificationsEnabled: false,
preferences: {
liveActivitiesEnabled: true,
},
}),
).toEqual({
deviceId: "device-1",
label: "Julius's iPhone",
platform: "ios",
iosMajorVersion: 18,
appVersion: "1.0.0",
pushToStartToken: "push-to-start-token",
preferences: {
liveActivitiesEnabled: true,
notificationsEnabled: false,
notifyOnApproval: true,
notifyOnInput: true,
notifyOnCompletion: true,
notifyOnFailure: true,
},
});
});
it("normalizes relay base URLs for APNs registration requests", () => {
expect(normalizeAgentAwarenessRelayBaseUrl(" https://relay.example.test/// ")).toBe(
"https://relay.example.test",
);
expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull();
});
it("registers at most one listener while a Live Activity push token is pending", async () => {
registerAgentAwarenessConnection(savedConnection());
const addPushTokenListener = vi.fn();
const activity = {
getPushToken: vi.fn(() => Promise.resolve(null)),
addPushTokenListener,
};
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
expect(activity.getPushToken).toHaveBeenCalledTimes(2);
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
});
it("reports Live Activity token registration as skipped when relay auth is unavailable", async () => {
registerAgentAwarenessConnection(savedConnection());
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
});
it("refreshes APNs registration for connected environments after settings changes", async () => {
registerAgentAwarenessConnection(savedConnection());
await new Promise((resolve) => setTimeout(resolve, 0));
vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
await runRegistrationEffect(refreshAgentAwarenessRegistration());
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
});
it.effect("registers the APNs device when cloud auth becomes available", () => {
const fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
return Promise.resolve(
Response.json(
url.endsWith("/v1/client/dpop-token")
? {
access_token: "relay-dpop-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 300,
scope: "mobile:registration",
}
: { ok: true },
),
);
});
vi.stubGlobal("fetch", fetchMock);
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2));
expect(fetchMock).toHaveBeenCalledTimes(2);
const [request, init] = fetchMock.mock.calls[1] as unknown as [
unknown,
RequestInit | undefined,
];
const url = request instanceof Request ? request.url : String(request);
const method = request instanceof Request ? request.method : init?.method;
const headers = request instanceof Request ? request.headers : new Headers(init?.headers);
const dpop = headers.get("dpop");
expect(url).toBe("https://relay.example.test/v1/mobile/devices");
expect(method).toBe("POST");
expect(headers.get("authorization")).toBe("DPoP relay-dpop-token");
expect(dpop).toEqual(expect.any(String));
if (!dpop) {
throw new Error("Missing DPoP header.");
}
expect(
verifyDpopProof({
proof: dpop,
method: "POST",
url: "https://relay.example.test/v1/mobile/devices",
expectedAccessToken: "relay-dpop-token",
nowEpochSeconds: proofIat(dpop),
}),
).toMatchObject({ ok: true });
});
});
it("only registers again when the authenticated identity changes", () => {
expect(shouldRegisterAgentAwarenessDeviceForProvider(null, "user-a")).toBe(true);
expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-a")).toBe(false);
expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-b")).toBe(true);
expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", undefined)).toBe(true);
});
it("registers rotated APNs tokens without rereading the native token", async () => {
const fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
return Promise.resolve(
Response.json(
url.endsWith("/v1/client/dpop-token")
? {
access_token: "relay-dpop-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 300,
scope: "mobile:registration",
}
: { ok: true },
),
);
});
vi.stubGlobal("fetch", fetchMock);
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
expect(tokenListener).toBeDefined();
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
});
it.effect(
"keeps the user-scoped relay APNs device when an environment connection is removed",
() => {
const fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
return Promise.resolve(
Response.json(
url.endsWith("/v1/client/dpop-token")
? {
access_token: "relay-dpop-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 300,
scope: "mobile:registration",
}
: { ok: true },
),
);
});
vi.stubGlobal("fetch", fetchMock);
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
registerAgentAwarenessConnection(savedConnection());
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2));
fetchMock.mockClear();
unregisterAgentAwarenessConnection(savedConnection().environmentId);
expect(fetchMock).not.toHaveBeenCalled();
});
},
);
});
@@ -0,0 +1,447 @@
import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Effect from "effect/Effect";
import { Platform } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import {
type RelayDeviceRegistrationRequest,
type RelayLiveActivityRegistrationRequest,
} from "@t3tools/contracts/relay";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import type { SavedRemoteConnection } from "../../lib/connection";
import { mobileRuntime } from "../../lib/runtime";
import {
loadAgentAwarenessDeviceId,
loadOrCreateAgentAwarenessDeviceId,
loadPreferences,
} from "../../lib/storage";
import type { AgentActivityProps } from "../../widgets/AgentActivity";
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
let pushToStartSubscription: { remove: () => void } | null = null;
let pushTokenSubscription: { remove: () => void } | null = null;
let relayTokenProvider: (() => Promise<string | null>) | null = null;
let relayTokenProviderIdentity: string | null = null;
export function normalizeAgentAwarenessRelayBaseUrl(
value: string | null | undefined,
): string | null {
const trimmed = value?.trim();
if (!trimmed) {
return null;
}
return trimmed.replace(/\/+$/g, "");
}
function readRelayConfig(): { readonly url: string } | null {
const relayUrl = resolveCloudPublicConfig().relayUrl;
if (!relayUrl) {
logRegistrationDebug("relay registration skipped; relay config missing");
return null;
}
return { url: relayUrl };
}
function canRegisterRemoteLiveActivities(): boolean {
return Platform.OS === "ios";
}
export function shouldRegisterAgentAwarenessDeviceForProvider(
previousIdentity: string | null,
identity: string | undefined,
): boolean {
return identity === undefined || identity !== previousIdentity;
}
export function setAgentAwarenessRelayTokenProvider(
provider: (() => Promise<string | null>) | null,
identity?: string,
): void {
const isExistingIdentity =
provider !== null &&
!shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);
relayTokenProvider = provider;
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
if (!provider) {
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
return;
}
ensurePushToStartListener();
ensurePushTokenListener();
if (isExistingIdentity) {
return;
}
runRegistrationInBackground(registerDevice(), "device registration after cloud sign-in failed");
}
function iosMajorVersion(): number {
const version = Platform.Version;
if (typeof version === "number") {
return Math.floor(version);
}
const major = Number.parseInt(version.split(".")[0] ?? "", 10);
return Number.isFinite(major) ? major : 18;
}
function nativePushTokenRegistration(observedPushToken?: string) {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities()) {
return { notificationsEnabled: false, pushToken: null };
}
if (observedPushToken) {
return { notificationsEnabled: true, pushToken: observedPushToken };
}
const permissions = yield* Effect.tryPromise({
try: () => Notifications.getPermissionsAsync(),
catch: (error) => error,
});
if (!permissions.granted) {
return { notificationsEnabled: false, pushToken: null };
}
const token = yield* Effect.tryPromise({
try: () => Notifications.getDevicePushTokenAsync(),
catch: (error) => error,
}).pipe(
Effect.tapError((error) =>
Effect.sync(() => {
logRegistrationError("native APNs token lookup failed", error);
}),
),
Effect.orElseSucceed(() => null),
);
const pushToken =
token?.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0
? token.data.trim()
: null;
return { notificationsEnabled: pushToken !== null, pushToken };
});
}
const relayToken = Effect.gen(function* () {
const provider = relayTokenProvider;
if (!provider) {
return null;
}
return yield* Effect.tryPromise({
try: provider,
catch: (error) => error,
});
});
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
): Effect.Effect<void, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (!readRelayConfig()) return;
const token = yield* relayToken;
if (!token) {
logRegistrationDebug("relay device registration skipped; user is not signed in");
return;
}
const client = yield* ManagedRelayClient;
yield* client.registerDevice({
clerkToken: token,
payload: body,
});
});
}
function unregisterDeviceWithRelay(input: {
readonly deviceId: string;
readonly tokenProvider: () => Promise<string | null>;
}): Effect.Effect<void, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (!readRelayConfig()) return;
const token = yield* Effect.tryPromise({
try: input.tokenProvider,
catch: (error) => error,
});
if (!token) {
logRegistrationDebug("relay device unregistration skipped; user is not signed in");
return;
}
const client = yield* ManagedRelayClient;
yield* client.unregisterDevice({
clerkToken: token,
deviceId: input.deviceId,
});
});
}
function registerLiveActivityWithRelay(
body: RelayLiveActivityRegistrationRequest,
): Effect.Effect<boolean, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (!readRelayConfig()) return false;
const token = yield* relayToken;
if (!token) {
logRegistrationDebug("relay live activity registration skipped; user is not signed in");
return false;
}
const client = yield* ManagedRelayClient;
yield* client.registerLiveActivity({
clerkToken: token,
payload: body,
});
return true;
});
}
function logRegistrationError(context: string, error: unknown): void {
if (!__DEV__) {
return;
}
console.warn(
`[agent-awareness] ${context}`,
error instanceof Error ? error.message : String(error),
);
}
function logRegistrationDebug(context: string, details?: unknown): void {
if (!__DEV__) {
return;
}
console.log(`[agent-awareness] ${context}`, details ?? "");
}
function runRegistrationInBackground(
operation: Effect.Effect<unknown, unknown, ManagedRelayClient>,
context: string,
): void {
void mobileRuntime.runPromise(operation).catch((error: unknown) => {
logRegistrationError(context, error);
});
}
function registerDevice(input?: {
readonly pushToStartToken?: string;
readonly observedPushToken?: string;
}): Effect.Effect<void, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities()) {
return;
}
const [deviceId, preferences] = yield* Effect.all([
Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (error) => error,
}),
Effect.tryPromise({
try: () => loadPreferences(),
catch: (error) => error,
}),
]);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
yield* registerDeviceWithRelay(
makeRelayDeviceRegistrationRequest({
deviceId,
label: Constants.deviceName?.trim() || "iOS device",
iosMajorVersion: iosMajorVersion(),
appVersion: Constants.expoConfig?.version,
...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
...(input?.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
preferences,
}),
);
});
}
function registerDeviceForCurrentUser(
pushToStartToken?: string,
): Effect.Effect<void, unknown, ManagedRelayClient> {
return registerDevice(pushToStartToken ? { pushToStartToken } : undefined);
}
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
runRegistrationInBackground(
registerDeviceForCurrentUser(pushToStartToken),
"push-to-start token registration failed",
);
}
function ensurePushToStartListener(): void {
if (pushToStartSubscription || !canRegisterRemoteLiveActivities()) {
return;
}
pushToStartSubscription = addPushToStartTokenListener((event) => {
const token = event.activityPushToStartToken;
if (token) {
registerPushToStartTokenForCurrentUser(token);
}
});
}
function ensurePushTokenListener(): void {
if (pushTokenSubscription || !canRegisterRemoteLiveActivities()) {
return;
}
pushTokenSubscription = Notifications.addPushTokenListener((token) => {
if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) {
runRegistrationInBackground(
registerDevice({ observedPushToken: token.data.trim() }),
"native APNs token rotation registration failed",
);
}
});
}
export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void {
if (!canRegisterRemoteLiveActivities()) {
return;
}
environmentConnections.set(connection.environmentId, connection);
ensurePushToStartListener();
ensurePushTokenListener();
runRegistrationInBackground(registerDevice(), "device registration failed");
}
function removeAgentAwarenessConnection(environmentId: EnvironmentId): void {
environmentConnections.delete(environmentId);
}
export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId): void {
removeAgentAwarenessConnection(environmentId);
}
export function unregisterAllAgentAwarenessConnections(): void {
environmentConnections.clear();
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
}
export function refreshAgentAwarenessRegistration(): Effect.Effect<
void,
never,
ManagedRelayClient
> {
return registerDeviceForCurrentUser().pipe(
Effect.catch((error) =>
Effect.sync(() => {
logRegistrationError("device registration refresh failed", error);
}),
),
);
}
export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
environmentConnections.clear();
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
relayTokenProvider = null;
relayTokenProviderIdentity = null;
}
export function unregisterAgentAwarenessDeviceForCurrentUser(
tokenProvider: () => Promise<string | null>,
): Effect.Effect<void, never, ManagedRelayClient> {
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadAgentAwarenessDeviceId(),
catch: (error) => error,
});
if (!deviceId) {
return;
}
yield* unregisterDeviceWithRelay({ deviceId, tokenProvider });
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
logRegistrationError("device unregistration failed", error);
}),
),
);
}
export function registerLiveActivityPushToken(input: {
readonly activity: LiveActivity<AgentActivityProps>;
}): Effect.Effect<boolean, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities()) {
return false;
}
const activityPushToken = yield* Effect.tryPromise({
try: () => input.activity.getPushToken(),
catch: (error) => error,
});
if (!activityPushToken) {
if (activityPushTokenListeners.has(input.activity)) {
logRegistrationDebug(
"live activity push token not available yet; token listener already registered",
{
connectionCount: environmentConnections.size,
},
);
return false;
}
logRegistrationDebug(
"live activity push token not available yet; listening for token event",
{
connectionCount: environmentConnections.size,
},
);
activityPushTokenListeners.add(input.activity);
input.activity.addPushTokenListener((event) => {
if (event.pushToken) {
logRegistrationDebug("live activity push token event received", {
tokenSuffix: event.pushToken.slice(-8),
});
runRegistrationInBackground(
registerLiveActivityPushTokenValue({
activityPushToken: event.pushToken,
}),
"live activity token listener registration failed",
);
}
});
return false;
}
return yield* registerLiveActivityPushTokenValue({
activityPushToken,
});
});
}
function registerLiveActivityPushTokenValue(input: {
readonly activityPushToken: string;
}): Effect.Effect<boolean, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (error) => error,
});
const registered = yield* registerLiveActivityWithRelay({
deviceId,
activityPushToken: input.activityPushToken,
});
if (registered) {
logRegistrationDebug("live activity push token registered", {
tokenSuffix: input.activityPushToken.slice(-8),
});
}
return registered;
});
}
@@ -0,0 +1,59 @@
import { shellSnapshotStateAtom } from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "../../lib/connection";
import { mobileRuntime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import {
endAllAgentLiveActivities,
endEnvironmentLiveActivities,
syncAgentLiveActivitiesForSnapshot,
} from "./liveActivityController";
import {
registerAgentAwarenessConnection,
unregisterAgentAwarenessConnection,
unregisterAllAgentAwarenessConnections,
} from "./remoteRegistration";
const environmentUnsubscribers = new Map<EnvironmentId, () => void>();
export function startAgentAwarenessForEnvironment(connection: SavedRemoteConnection): void {
const { environmentId } = connection;
if (environmentUnsubscribers.has(environmentId)) {
return;
}
registerAgentAwarenessConnection(connection);
const sync = () => {
const state = appAtomRegistry.get(shellSnapshotStateAtom(environmentId));
void mobileRuntime
.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId,
snapshot: state.data,
}),
)
.catch(() => undefined);
};
const unsubscribe = appAtomRegistry.subscribe(shellSnapshotStateAtom(environmentId), sync);
environmentUnsubscribers.set(environmentId, unsubscribe);
sync();
}
export function stopAgentAwarenessForEnvironment(environmentId: EnvironmentId): void {
environmentUnsubscribers.get(environmentId)?.();
environmentUnsubscribers.delete(environmentId);
unregisterAgentAwarenessConnection(environmentId);
void mobileRuntime.runPromise(endEnvironmentLiveActivities(environmentId)).catch(() => undefined);
}
export function stopAllAgentAwareness(): void {
for (const unsubscribe of environmentUnsubscribers.values()) {
unsubscribe();
}
environmentUnsubscribers.clear();
unregisterAllAgentAwarenessConnections();
void mobileRuntime.runPromise(endAllAgentLiveActivities()).catch(() => undefined);
}
@@ -0,0 +1,93 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime";
import { type ReactNode, useEffect, useRef } from "react";
import { mobileRuntime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { refreshActiveLiveActivityRemoteRegistration } from "../agent-awareness/liveActivityController";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function CloudAuthBridge(props: { readonly children: ReactNode }) {
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const previousTokenProviderRef = useRef<{
readonly userId: string;
readonly provider: () => Promise<string | null>;
} | null>(null);
useEffect(() => {
if (!isLoaded) {
return;
}
if (!isSignedIn || !userId) {
const previous = previousTokenProviderRef.current;
previousTokenProviderRef.current = null;
if (previous) {
void mobileRuntime
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
.catch(() => undefined);
}
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
return;
}
const previous = previousTokenProviderRef.current;
if (previous && previous.userId !== userId) {
void mobileRuntime
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
.catch(() => undefined);
}
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
previousTokenProviderRef.current = { userId, provider: tokenProvider };
setAgentAwarenessRelayTokenProvider(tokenProvider, userId);
setManagedRelaySession(
appAtomRegistry,
createManagedRelaySession({
accountId: userId,
readClerkToken: tokenProvider,
}),
);
if (!previous || previous.userId !== userId) {
void mobileRuntime
.runPromise(refreshActiveLiveActivityRemoteRegistration())
.catch(() => undefined);
}
}, [getToken, isLoaded, isSignedIn, userId]);
useEffect(
() => () => {
previousTokenProviderRef.current = null;
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
},
[],
);
return props.children;
}
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
useEffect(() => {
if (!publishableKey || !relayUrl) {
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
}
}, [publishableKey, relayUrl]);
if (!publishableKey || !relayUrl) {
return props.children;
}
return (
<ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
<CloudAuthBridge>{props.children}</CloudAuthBridge>
</ClerkProvider>
);
}
@@ -0,0 +1,208 @@
import { useWaitlist } from "@clerk/expo";
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { useState } from "react";
import { useThemeColor } from "../../lib/useThemeColor";
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
const { errors, fetchStatus, waitlist } = useWaitlist();
const colors = useCloudWaitlistColors();
const [emailAddress, setEmailAddress] = useState("");
const [requestError, setRequestError] = useState<string | null>(null);
const isSubmitting = fetchStatus === "fetching";
const fieldError = errors.fields.emailAddress?.longMessage;
const joinWaitlist = async () => {
const normalizedEmailAddress = emailAddress.trim();
if (!normalizedEmailAddress || isSubmitting) {
return;
}
setRequestError(null);
try {
const { error } = await waitlist.join({ emailAddress: normalizedEmailAddress });
if (error) {
setRequestError("Could not join the waitlist. Check your email address and try again.");
}
} catch {
setRequestError("Could not join the waitlist. Check your connection and try again.");
}
};
if (waitlist.id) {
return (
<View style={styles.content}>
<Text style={[styles.title, { color: colors.foreground }]}>You are on the waitlist</Text>
<Text style={[styles.body, styles.confirmationBody, { color: colors.secondaryForeground }]}>
We will email you when your T3 Cloud access is ready.
</Text>
<SignInAction onPress={props.onSignIn} />
</View>
);
}
return (
<View style={styles.content}>
<Text style={[styles.body, { color: colors.secondaryForeground }]}>
Enter your email and we will let you know when access is ready.
</Text>
<View style={styles.field}>
<Text style={[styles.label, { color: colors.secondaryForeground }]}>Email address</Text>
<TextInput
accessibilityLabel="Email address"
autoCapitalize="none"
autoComplete="email"
autoCorrect={false}
keyboardType="email-address"
onChangeText={(value) => {
setEmailAddress(value);
setRequestError(null);
}}
onSubmitEditing={() => void joinWaitlist()}
placeholder="Enter your email address"
placeholderTextColor={colors.placeholder}
returnKeyType="join"
style={[
styles.input,
{
backgroundColor: colors.input,
borderColor:
fieldError || requestError ? colors.dangerForeground : colors.inputBorder,
color: colors.foreground,
},
]}
textContentType="emailAddress"
value={emailAddress}
/>
{fieldError || requestError ? (
<Text
accessibilityLiveRegion="polite"
style={[styles.error, { color: colors.dangerForeground }]}
selectable
>
{fieldError ?? requestError}
</Text>
) : null}
</View>
<Pressable
accessibilityRole="button"
accessibilityState={{
busy: isSubmitting,
disabled: isSubmitting || emailAddress.trim().length === 0,
}}
disabled={isSubmitting || emailAddress.trim().length === 0}
onPress={() => void joinWaitlist()}
style={[
styles.primaryButton,
{
backgroundColor: colors.primary,
opacity: isSubmitting || emailAddress.trim().length === 0 ? 0.45 : 1,
},
]}
>
{isSubmitting ? <ActivityIndicator color={colors.primaryForeground} size="small" /> : null}
<Text style={[styles.buttonText, { color: colors.primaryForeground }]}>
{isSubmitting ? "Joining" : "Join the waitlist"}
</Text>
</Pressable>
<SignInAction onPress={props.onSignIn} />
</View>
);
}
function SignInAction(props: { readonly onPress: () => void }) {
const colors = useCloudWaitlistColors();
return (
<View style={styles.signInRow}>
<Text style={[styles.body, { color: colors.secondaryForeground }]}>Already have access?</Text>
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
<Text style={[styles.signInText, { color: colors.foreground }]}>Sign in</Text>
</Pressable>
</View>
);
}
function useCloudWaitlistColors() {
return {
dangerForeground: String(useThemeColor("--color-danger-foreground")),
foreground: String(useThemeColor("--color-foreground")),
input: String(useThemeColor("--color-input")),
inputBorder: String(useThemeColor("--color-input-border")),
placeholder: String(useThemeColor("--color-placeholder")),
primary: String(useThemeColor("--color-primary")),
primaryForeground: String(useThemeColor("--color-primary-foreground")),
secondaryForeground: String(useThemeColor("--color-foreground-secondary")),
};
}
const styles = StyleSheet.create({
body: {
fontFamily: "DMSans_400Regular",
fontSize: 15,
lineHeight: 21,
},
buttonText: {
fontFamily: "DMSans_700Bold",
fontSize: 16,
},
content: {
gap: 18,
},
confirmationBody: {
textAlign: "center",
},
error: {
fontFamily: "DMSans_400Regular",
fontSize: 13,
lineHeight: 18,
},
field: {
gap: 8,
},
input: {
borderCurve: "continuous",
borderRadius: 16,
borderWidth: 1,
fontFamily: "DMSans_400Regular",
fontSize: 17,
minHeight: 54,
paddingHorizontal: 16,
paddingVertical: 14,
},
label: {
fontFamily: "DMSans_700Bold",
fontSize: 13,
lineHeight: 18,
},
primaryButton: {
alignItems: "center",
borderRadius: 999,
flexDirection: "row",
gap: 8,
justifyContent: "center",
minHeight: 54,
paddingHorizontal: 20,
paddingVertical: 12,
},
signInRow: {
alignItems: "center",
flexDirection: "row",
gap: 4,
justifyContent: "center",
paddingTop: 4,
},
signInText: {
fontFamily: "DMSans_700Bold",
fontSize: 15,
lineHeight: 21,
},
title: {
fontFamily: "DMSans_700Bold",
fontSize: 20,
lineHeight: 26,
textAlign: "center",
},
});
+166
View File
@@ -0,0 +1,166 @@
/// <reference types="node" />
import * as NodeCrypto from "node:crypto";
import { vi } from "vitest";
import { describe, expect, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import { verifyDpopProof } from "@t3tools/shared/dpop";
import {
createDpopProof,
generateDpopProofKeyPair,
loadOrCreateDpopProofKeyPair,
mobileCryptoLayer,
} from "./dpop";
vi.mock("expo-crypto", () => ({
CryptoDigestAlgorithm: {
SHA1: "SHA-1",
SHA256: "SHA-256",
SHA384: "SHA-384",
SHA512: "SHA-512",
},
getRandomBytes: (byteCount: number) => new Uint8Array(NodeCrypto.randomBytes(byteCount)),
getRandomBytesAsync: (byteCount: number) =>
Promise.resolve(new Uint8Array(NodeCrypto.randomBytes(byteCount))),
digest: (algorithm: string, data: unknown) => {
if (!(data instanceof Uint8Array)) {
return Promise.reject(new TypeError("expo-crypto digest data must be a typed array."));
}
return Promise.resolve(
new Uint8Array(NodeCrypto.createHash(algorithm).update(data).digest()).buffer,
);
},
}));
const secureStore = new Map<string, string>();
vi.mock("expo-secure-store", () => ({
getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null),
setItemAsync: (key: string, value: string) => {
secureStore.set(key, value);
return Promise.resolve();
},
}));
function proofIat(proof: string): number {
const payload = proof.split(".")[1];
if (!payload) {
throw new Error("Missing DPoP payload.");
}
const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
readonly iat: number;
};
return decoded.iat;
}
function proofHtu(proof: string): string {
const payload = proof.split(".")[1];
if (!payload) {
throw new Error("Missing DPoP payload.");
}
const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
readonly htu: string;
};
return decoded.htu;
}
describe("mobile DPoP", () => {
it.effect("passes typed-array digest input through the Expo Crypto adapter", () =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode("typed-array"));
expect(Buffer.from(digest).toString("hex")).toBe(
NodeCrypto.createHash("sha256").update("typed-array").digest("hex"),
);
}).pipe(Effect.provide(mobileCryptoLayer)),
);
it.effect("persists and reuses the installation proof key", () =>
Effect.gen(function* () {
secureStore.clear();
const first = yield* loadOrCreateDpopProofKeyPair();
const second = yield* loadOrCreateDpopProofKeyPair();
expect(second.thumbprint).toBe(first.thumbprint);
expect(second.privateJwk).toEqual(first.privateJwk);
}).pipe(Effect.provide(mobileCryptoLayer)),
);
it.effect("rejects malformed persisted proof keys", () =>
Effect.gen(function* () {
secureStore.set("t3code.cloud.dpop-proof-key", `{"kty":"EC","crv":"P-256","d":42}`);
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
expect(error.message).toBe("Stored DPoP proof key is invalid.");
}).pipe(Effect.provide(mobileCryptoLayer)),
);
it.effect("signs connect and bootstrap proofs with the same ephemeral proof key", () =>
Effect.gen(function* () {
const proofKey = yield* generateDpopProofKeyPair();
const connect = yield* createDpopProof({
method: "POST",
url: "https://relay.example.test/v1/environments/env-1/connect",
accessToken: "clerk-token",
proofKey,
});
const bootstrap = yield* createDpopProof({
method: "POST",
url: "https://desktop.example.test/oauth/token",
proofKey,
});
expect(connect.thumbprint).toBe(proofKey.thumbprint);
expect(bootstrap.thumbprint).toBe(proofKey.thumbprint);
expect(
verifyDpopProof({
proof: connect.proof,
method: "POST",
url: "https://relay.example.test/v1/environments/env-1/connect",
expectedThumbprint: proofKey.thumbprint,
expectedAccessToken: "clerk-token",
nowEpochSeconds: proofIat(connect.proof),
}),
).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });
expect(
verifyDpopProof({
proof: bootstrap.proof,
method: "POST",
url: "https://desktop.example.test/oauth/token",
expectedThumbprint: proofKey.thumbprint,
nowEpochSeconds: proofIat(bootstrap.proof),
}),
).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });
}).pipe(Effect.provide(mobileCryptoLayer)),
);
it.effect("signs DPoP proofs with RFC 9449 htu normalization", () =>
Effect.gen(function* () {
const proofKey = yield* generateDpopProofKeyPair();
const proof = yield* createDpopProof({
method: "POST",
url: "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored",
accessToken: "clerk-token",
proofKey,
});
expect(proofHtu(proof.proof)).toBe(
"https://relay.example.test/v1/environments/env-1/connect",
);
expect(
verifyDpopProof({
proof: proof.proof,
method: "POST",
url: "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored",
expectedThumbprint: proofKey.thumbprint,
expectedAccessToken: "clerk-token",
nowEpochSeconds: proofIat(proof.proof),
}),
).toMatchObject({ ok: true });
}).pipe(Effect.provide(mobileCryptoLayer)),
);
});
+270
View File
@@ -0,0 +1,270 @@
import * as Clock from "effect/Clock";
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 Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as ExpoCrypto from "expo-crypto";
import * as SecureStore from "expo-secure-store";
import { p256 } from "@noble/curves/nist";
import {
computeDpopAccessTokenHash,
computeDpopJwkThumbprint,
DpopPublicJwk,
normalizeDpopHtu,
} from "@t3tools/shared/dpop";
import * as Layer from "effect/Layer";
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
function cloudDpopError(message: string) {
return (cause: unknown) => new CloudDpopError({ message, cause });
}
const DpopPrivateJwkSchema = Schema.Struct({
...DpopPublicJwk.fields,
d: Schema.String,
});
const DpopPrivateJwkJson = Schema.fromJsonString(DpopPrivateJwkSchema);
const decodeDpopPrivateJwkJson = Schema.decodeUnknownEffect(DpopPrivateJwkJson);
const encodeDpopPrivateJwkJson = Schema.encodeEffect(DpopPrivateJwkJson);
const DpopJwtHeaderJson = Schema.fromJsonString(
Schema.Struct({
typ: Schema.Literal("dpop+jwt"),
alg: Schema.Literal("ES256"),
jwk: DpopPublicJwk,
}),
);
const DpopJwtPayloadJson = Schema.fromJsonString(
Schema.Struct({
htm: Schema.String,
htu: Schema.String,
jti: Schema.String,
iat: Schema.Int,
ath: Schema.optionalKey(Schema.String),
}),
);
const encodeDpopJwtHeaderJson = Schema.encodeEffect(DpopJwtHeaderJson);
const encodeDpopJwtPayloadJson = Schema.encodeEffect(DpopJwtPayloadJson);
function toExpoDigestAlgorithm(
algorithm: Crypto.DigestAlgorithm,
): ExpoCrypto.CryptoDigestAlgorithm {
switch (algorithm) {
case "SHA-1":
return ExpoCrypto.CryptoDigestAlgorithm.SHA1;
case "SHA-256":
return ExpoCrypto.CryptoDigestAlgorithm.SHA256;
case "SHA-384":
return ExpoCrypto.CryptoDigestAlgorithm.SHA384;
case "SHA-512":
return ExpoCrypto.CryptoDigestAlgorithm.SHA512;
}
}
export const mobileCryptoLayer = Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: ExpoCrypto.getRandomBytes,
digest: (algorithm, data) =>
Effect.promise(async () => {
const input = new Uint8Array(data.length);
input.set(data);
return new Uint8Array(await ExpoCrypto.digest(toExpoDigestAlgorithm(algorithm), input));
}),
}),
);
type DpopPrivateJwk = typeof DpopPrivateJwkSchema.Type;
export interface DpopProofKeyPair {
readonly privateJwk: DpopPrivateJwk;
readonly publicJwk: DpopPublicJwk;
readonly thumbprint: string;
}
const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key";
function base64UrlToBytes(value: string): Uint8Array {
return Result.getOrThrow(Encoding.decodeBase64Url(value));
}
function sha256Digest(
data: Uint8Array,
message: string,
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
return Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),
Effect.mapError(cloudDpopError(message)),
);
}
function secureRandomBytes(
byteCount: number,
message: string,
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
return Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomBytes(byteCount)),
Effect.mapError(cloudDpopError(message)),
);
}
function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");
}
return {
kty: "EC",
crv: "P-256",
x: Encoding.encodeBase64Url(publicKey.slice(1, 33)),
y: Encoding.encodeBase64Url(publicKey.slice(33, 65)),
};
}
function privateJwkFromPrivateKey(
privateKey: Uint8Array,
publicJwk: DpopPublicJwk,
): DpopPrivateJwk {
return { ...publicJwk, d: Encoding.encodeBase64Url(privateKey) };
}
export function generateDpopProofKeyPair(): Effect.Effect<
DpopProofKeyPair,
CloudDpopError,
Crypto.Crypto
> {
return Effect.gen(function* () {
let privateKey: Uint8Array;
do {
privateKey = yield* secureRandomBytes(
p256.CURVE.nByteLength,
"Could not generate DPoP key pair randomness.",
);
} while (!p256.utils.isValidPrivateKey(privateKey));
const publicJwk = yield* Effect.try({
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
catch: cloudDpopError("Generated DPoP public key is invalid."),
});
const thumbprint = computeDpopJwkThumbprint(publicJwk);
return {
privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk),
publicJwk,
thumbprint,
};
});
}
export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
DpopProofKeyPair,
CloudDpopError,
Crypto.Crypto
> {
return Effect.gen(function* () {
const stored = yield* Effect.tryPromise({
try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
catch: cloudDpopError("Could not read the DPoP proof key."),
});
if (stored) {
const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
);
const restored = yield* Effect.try({
try: () => {
const privateKey = base64UrlToBytes(storedPrivateJwk.d);
const publicJwk = publicJwkFromUncompressedPublicKey(
p256.getPublicKey(privateKey, false),
);
if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
throw new Error("Stored DPoP key does not match its public key.");
}
return { privateJwk: storedPrivateJwk, publicJwk };
},
catch: cloudDpopError("Stored DPoP proof key is invalid."),
});
return {
...restored,
thumbprint: computeDpopJwkThumbprint(restored.publicJwk),
};
}
const generated = yield* generateDpopProofKeyPair();
const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),
);
yield* Effect.tryPromise({
try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),
catch: cloudDpopError("Could not store the DPoP proof key."),
});
return generated;
});
}
function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
const normalized = normalizeDpopHtu(url);
return normalized
? Effect.succeed(normalized)
: Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
}
export function createDpopProof(input: {
readonly method: string;
readonly url: string;
readonly accessToken?: string;
readonly proofKey?: DpopProofKeyPair;
}): Effect.Effect<
{ readonly proof: string; readonly thumbprint: string },
CloudDpopError,
Crypto.Crypto
> {
return Effect.gen(function* () {
const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
const privateKey = yield* Effect.try({
try: () => base64UrlToBytes(keyPair.privateJwk.d),
catch: cloudDpopError("Could not import DPoP private key."),
});
const nowMs = yield* Clock.currentTimeMillis;
const jti = yield* Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
);
const htu = yield* normalizeHtu(input.url);
const header = yield* encodeDpopJwtHeaderJson({
typ: "dpop+jwt",
alg: "ES256",
jwk: keyPair.publicJwk,
}).pipe(
Effect.map(Encoding.encodeBase64Url),
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
);
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
const payload = yield* encodeDpopJwtPayloadJson({
htm: input.method.toUpperCase(),
htu,
jti,
iat: Math.floor(nowMs / 1_000),
...(ath ? { ath } : {}),
}).pipe(
Effect.map(Encoding.encodeBase64Url),
Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
);
const signatureInputHash = yield* sha256Digest(
new TextEncoder().encode(`${header}.${payload}`),
"Could not hash DPoP signing input.",
);
const signature = yield* Effect.try({
try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
catch: cloudDpopError("Could not sign DPoP proof."),
});
return {
proof: `${header}.${payload}.${Encoding.encodeBase64Url(signature)}`,
thumbprint: keyPair.thumbprint,
};
});
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,582 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import {
EnvironmentCloudEndpointUnavailableError,
EnvironmentHttpBadRequestError,
EnvironmentHttpConflictError,
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
EnvironmentHttpUnauthorizedError,
} from "@t3tools/contracts";
import { stripPairingTokenFromUrl } from "@t3tools/shared/remote";
import {
type RelayEnvironmentConnectResponse as RelayEnvironmentConnectResponseType,
type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,
RelayEnvironmentConnectScope,
RelayEnvironmentStatusScope,
RelayProtectedError,
type RelayDpopAccessTokenScope,
type RelayProtectedError as RelayProtectedErrorType,
type RelayClientEnvironmentRecord,
type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
type RelayManagedEndpointProviderKind,
} from "@t3tools/contracts/relay";
import {
exchangeRemoteDpopAccessToken,
fetchRemoteEnvironmentDescriptor,
makeEnvironmentHttpApiClient,
ManagedRelayClient,
ManagedRelayDpopSigner,
} from "@t3tools/client-runtime";
import { mobileAuthClientMetadata } from "../../lib/authClientMetadata";
import type { SavedRemoteConnection } from "../../lib/connection";
import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
import { resolveCloudPublicConfig } from "./publicConfig";
const RELAY_STATUS_AND_CONNECT_SCOPES = [
RelayEnvironmentStatusScope,
RelayEnvironmentConnectScope,
] satisfies ReadonlyArray<RelayDpopAccessTokenScope>;
export function normalizeRelayBaseUrl(value: string | null | undefined): string | null {
const trimmed = value?.trim();
if (!trimmed) {
return null;
}
return trimmed.replace(/\/+$/g, "");
}
function readRelayUrl(): string | null {
return resolveCloudPublicConfig().relayUrl;
}
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export interface CloudEnvironmentRecordWithStatus {
readonly environment: RelayClientEnvironmentRecord;
readonly status: RelayEnvironmentStatusResponseType | null;
readonly statusError: string | null;
}
const isRelayProtectedError = Schema.is(RelayProtectedError);
const isEnvironmentCloudApiError = Schema.is(
Schema.Union([
EnvironmentHttpBadRequestError,
EnvironmentHttpUnauthorizedError,
EnvironmentHttpForbiddenError,
EnvironmentHttpConflictError,
EnvironmentHttpInternalServerError,
EnvironmentCloudEndpointUnavailableError,
]),
);
const MANAGED_ENDPOINT_PROVIDER_KIND =
"cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
function cloudEnvironmentLinkError(message: string) {
return (cause: unknown) => {
const environmentError = findEnvironmentCloudApiError(cause);
return new CloudEnvironmentLinkError({
message: environmentError
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
: withDevCause(message, cause),
cause,
});
};
}
function isDevRuntime(): boolean {
return typeof __DEV__ !== "undefined" && __DEV__;
}
function causeMessage(cause: unknown): string | null {
if (cause instanceof Error && cause.message) {
return cause.message;
}
if (typeof cause === "object" && cause !== null) {
const record = cause as { readonly message?: unknown; readonly cause?: unknown };
if (typeof record.message === "string" && record.message.length > 0) {
const nested = causeMessage(record.cause);
return nested ? `${record.message}: ${nested}` : record.message;
}
}
return null;
}
function withDevCause(message: string, cause: unknown): string {
if (!isDevRuntime()) {
return message;
}
const detail = causeMessage(cause);
return detail ? `${message} (${detail})` : message;
}
function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
switch (error._tag) {
case "RelayAuthInvalidError":
switch (error.reason) {
case "missing_bearer":
case "invalid_bearer":
return "Relay rejected the cloud session token.";
case "invalid_dpop":
return "Relay rejected the DPoP proof.";
case "not_authorized":
return "Relay rejected the authenticated request.";
}
case "RelayEnvironmentLinkProofExpiredError":
return "Relay rejected an expired environment link proof.";
case "RelayEnvironmentLinkProofInvalidError":
return `Relay rejected the environment link proof (${error.reason}).`;
case "RelayEnvironmentConnectNotAuthorizedError":
return "Relay rejected the environment connection request.";
case "RelayEnvironmentEndpointUnavailableError":
return `Relay could not reach the environment endpoint (${error.reason}).`;
case "RelayEnvironmentEndpointTimedOutError":
return "Relay timed out while contacting the environment endpoint.";
case "RelayEnvironmentLinkFailedError":
return `Relay could not link the environment (${error.reason}).`;
case "RelayEnvironmentLinkUnavailableError":
return `Relay cannot provision the managed endpoint (${error.reason}).`;
case "RelayAgentActivityPublishProofExpiredError":
return "Relay rejected an expired agent activity publish proof.";
case "RelayAgentActivityPublishProofInvalidError":
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`;
}
}
function decodedRelayClientError(message: string) {
return (cause: unknown) => {
const relayError = findRelayProtectedError(cause);
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
return new CloudEnvironmentLinkError({
message: detail ? `${message}: ${detail}` : message,
cause,
});
};
}
function findRelayProtectedError(cause: unknown): RelayProtectedErrorType | null {
if (isRelayProtectedError(cause)) {
return cause;
}
if (typeof cause !== "object" || cause === null) {
return null;
}
return "cause" in cause ? findRelayProtectedError(cause.cause) : null;
}
function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
if (isEnvironmentCloudApiError(cause)) {
return cause;
}
if (typeof cause !== "object" || cause === null) {
return null;
}
return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
}
function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
const relayUrl = readRelayUrl();
return relayUrl
? Effect.succeed(relayUrl)
: Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));
}
function endpointOrigin(httpBaseUrl: string) {
const url = new URL(httpBaseUrl);
return {
localHttpHost: "127.0.0.1",
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
};
}
function ensureLinkedEnvironmentMatches(input: {
readonly expectedEnvironmentId: string;
readonly expectedProviderKind: RelayManagedEndpointProviderKind;
readonly link: RelayEnvironmentLinkResponseType;
}): Effect.Effect<void, CloudEnvironmentLinkError> {
if (input.link.environmentId !== input.expectedEnvironmentId) {
return new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different environment.",
});
}
if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
return new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different endpoint provider.",
});
}
return Effect.void;
}
function endpointMatches(
left: RelayClientEnvironmentRecord["endpoint"],
right: RelayClientEnvironmentRecord["endpoint"],
): boolean {
return (
left.httpBaseUrl === right.httpBaseUrl &&
left.wsBaseUrl === right.wsBaseUrl &&
left.providerKind === right.providerKind
);
}
function ensureStatusMatchesEnvironment(input: {
readonly environment: RelayClientEnvironmentRecord;
readonly status: RelayEnvironmentStatusResponseType;
}): Effect.Effect<void, CloudEnvironmentLinkError> {
if (input.status.environmentId !== input.environment.environmentId) {
return new CloudEnvironmentLinkError({
message: "Relay returned status for a different environment.",
});
}
if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {
return new CloudEnvironmentLinkError({
message: "Relay returned status for a different endpoint.",
});
}
if (
input.status.descriptor &&
input.status.descriptor.environmentId !== input.environment.environmentId
) {
return new CloudEnvironmentLinkError({
message: "Relay returned status descriptor for a different environment.",
});
}
return Effect.void;
}
function ensureConnectEndpointMatchesEnvironment(input: {
readonly environment: RelayClientEnvironmentRecord;
readonly connect: RelayEnvironmentConnectResponseType;
}): Effect.Effect<void, CloudEnvironmentLinkError> {
if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {
return new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different endpoint.",
});
}
return Effect.void;
}
export function linkEnvironmentToCloud(input: {
readonly connection: SavedRemoteConnection;
readonly clerkToken: string;
}): Effect.Effect<void, CloudEnvironmentLinkError, HttpClient.HttpClient | ManagedRelayClient> {
return Effect.gen(function* () {
if (!input.connection.bearerToken) {
return yield* new CloudEnvironmentLinkError({
message: "Only a locally paired bearer connection can be linked to the cloud.",
});
}
const localBearerToken = input.connection.bearerToken;
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
const preferences = yield* Effect.tryPromise({
try: () => loadPreferences(),
catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
});
const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
const challenge = yield* relayClient
.createEnvironmentLinkChallenge({
clerkToken: input.clerkToken,
payload: {
notificationsEnabled: true,
liveActivitiesEnabled,
managedTunnelsEnabled: true,
},
})
.pipe(
Effect.mapError(
decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
),
);
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
const proof = yield* environmentClient.cloud
.linkProof({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: {
challenge: challenge.challenge,
relayIssuer: relayUrl,
endpoint: {
httpBaseUrl: input.connection.httpBaseUrl,
wsBaseUrl: input.connection.wsBaseUrl,
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
},
origin: endpointOrigin(input.connection.httpBaseUrl),
},
})
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
const link = yield* relayClient
.linkEnvironment({
clerkToken: input.clerkToken,
payload: {
deviceId,
proof,
notificationsEnabled: true,
liveActivitiesEnabled,
managedTunnelsEnabled: true,
},
})
.pipe(
Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
);
yield* ensureLinkedEnvironmentMatches({
expectedEnvironmentId: input.connection.environmentId,
expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
link,
});
yield* environmentClient.cloud
.relayConfig({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: {
relayUrl,
relayIssuer: link.relayIssuer,
cloudUserId: link.cloudUserId,
environmentCredential: link.environmentCredential,
cloudMintPublicKey: link.cloudMintPublicKey,
endpointRuntime: link.endpointRuntime,
},
})
.pipe(
Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
);
});
}
export function listCloudEnvironments(input: {
readonly clerkToken: string;
}): Effect.Effect<
ReadonlyArray<RelayClientEnvironmentRecord>,
CloudEnvironmentLinkError,
ManagedRelayClient
> {
return Effect.gen(function* () {
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
return yield* relayClient
.listEnvironments({
clerkToken: input.clerkToken,
})
.pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));
});
}
export function getCloudEnvironmentStatus(input: {
readonly clerkToken: string;
readonly environment: RelayClientEnvironmentRecord;
readonly relayScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;
}): Effect.Effect<
RelayEnvironmentStatusResponseType,
CloudEnvironmentLinkError,
ManagedRelayClient
> {
return Effect.gen(function* () {
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const status = yield* relayClient
.getEnvironmentStatus({
clerkToken: input.clerkToken,
scopes: input.relayScopes ?? [RelayEnvironmentStatusScope],
environmentId: input.environment.environmentId,
})
.pipe(
Effect.mapError(
decodedRelayClientError(
`${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,
),
),
);
yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });
return status;
});
}
export function cloudEnvironmentsPendingStatus(
environments: ReadonlyArray<RelayClientEnvironmentRecord>,
): ReadonlyArray<CloudEnvironmentRecordWithStatus> {
return environments.map((environment) => ({
environment,
status: null,
statusError: "Checking status...",
}));
}
export function loadCloudEnvironmentStatuses(input: {
readonly clerkToken: string;
readonly environments: ReadonlyArray<RelayClientEnvironmentRecord>;
}): Effect.Effect<
ReadonlyArray<CloudEnvironmentRecordWithStatus>,
CloudEnvironmentLinkError,
ManagedRelayClient
> {
return Effect.forEach(
input.environments,
(environment) =>
getCloudEnvironmentStatus({
clerkToken: input.clerkToken,
environment,
relayScopes: RELAY_STATUS_AND_CONNECT_SCOPES,
}).pipe(
Effect.match({
onFailure: (error) => ({
environment,
status: null,
statusError: error.message,
}),
onSuccess: (status) => ({
environment,
status,
statusError: null,
}),
}),
),
{ concurrency: "unbounded" },
);
}
export function listCloudEnvironmentsWithStatus(input: {
readonly clerkToken: string;
}): Effect.Effect<
ReadonlyArray<CloudEnvironmentRecordWithStatus>,
CloudEnvironmentLinkError,
ManagedRelayClient
> {
return Effect.gen(function* () {
const environments = yield* listCloudEnvironments(input);
return yield* loadCloudEnvironmentStatuses({
clerkToken: input.clerkToken,
environments,
});
});
}
function connectRelayManagedEnvironment(input: {
readonly clerkToken: string;
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
readonly expectedEnvironment?: RelayClientEnvironmentRecord;
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
> {
return Effect.gen(function* () {
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
const connect = yield* relayClient
.connectEnvironment({
clerkToken: input.clerkToken,
scopes: [RelayEnvironmentConnectScope],
environmentId: input.environmentId,
deviceId,
})
.pipe(
Effect.mapError(
decodedRelayClientError(
`${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
),
),
);
if (connect.environmentId !== input.environmentId) {
return yield* new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different environment.",
});
}
if (input.expectedEnvironment) {
yield* ensureConnectEndpointMatchesEnvironment({
environment: input.expectedEnvironment,
connect,
});
}
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: connect.endpoint.httpBaseUrl,
}).pipe(
Effect.mapError(
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
),
);
if (descriptor.environmentId !== connect.environmentId) {
return yield* new CloudEnvironmentLinkError({
message: "Connected endpoint descriptor does not match the selected environment.",
});
}
const signer = yield* ManagedRelayDpopSigner;
const bootstrapDpop = yield* signer
.createProof({
method: "POST",
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
})
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
const bootstrap = yield* exchangeRemoteDpopAccessToken({
httpBaseUrl: connect.endpoint.httpBaseUrl,
credential: connect.credential,
dpopProof: bootstrapDpop,
clientMetadata: mobileAuthClientMetadata(),
}).pipe(
Effect.mapError(
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
),
);
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
return {
environmentId: descriptor.environmentId,
environmentLabel: descriptor.label,
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
displayUrl: connect.endpoint.httpBaseUrl,
httpBaseUrl: connect.endpoint.httpBaseUrl,
wsBaseUrl: connect.endpoint.wsBaseUrl,
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: bootstrap.access_token,
relayManaged: true,
};
});
}
export function connectCloudEnvironment(input: {
readonly clerkToken: string;
readonly environment: RelayClientEnvironmentRecord;
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
environmentId: input.environment.environmentId,
expectedEnvironment: input.environment,
});
}
export function refreshCloudEnvironmentConnection(input: {
readonly clerkToken: string;
readonly connection: SavedRemoteConnection;
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
environmentId: input.connection.environmentId,
});
}
@@ -0,0 +1,42 @@
import {
managedRelayClientLayer,
ManagedRelayDpopSigner,
ManagedRelayDpopSignerError,
} from "@t3tools/client-runtime";
import { RelayMobileClientId } from "@t3tools/contracts/relay";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop";
const mobileRelayDpopSignerLayer = Layer.effect(
ManagedRelayDpopSigner,
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
return ManagedRelayDpopSigner.of({
thumbprint: Effect.suspend(() =>
loadOrCreateDpopProofKeyPair().pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.map((proofKey) => proofKey.thumbprint),
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
),
),
createProof: (input) =>
Effect.gen(function* () {
const proofKey = yield* loadOrCreateDpopProofKeyPair().pipe(
Effect.provideService(Crypto.Crypto, crypto),
);
return yield* createDpopProof({ ...input, proofKey }).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.map((proof) => proof.proof),
);
}).pipe(Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause }))),
});
}),
);
export const mobileManagedRelayClientLayer = (relayUrl: string) =>
managedRelayClientLayer({ relayUrl, clientId: RelayMobileClientId }).pipe(
Layer.provideMerge(mobileRelayDpopSignerLayer),
);
@@ -0,0 +1,88 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
ManagedRelayClient,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime";
import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
import { mobileRuntime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
const managedRelayAtomRuntime = Atom.runtime(
Layer.effect(
ManagedRelayClient,
mobileRuntime.contextEffect.pipe(
Effect.map((context) => Context.get(context, ManagedRelayClient)),
),
),
);
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null"));
const EMPTY_ENVIRONMENT_STATUS_ATOM = Atom.make(
AsyncResult.initial<RelayEnvironmentStatusResponse, never>(false),
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environment-status:null"));
export function useManagedRelayEnvironments() {
const session = useAtomValue(managedRelaySessionAtom);
const accountId = session?.accountId ?? null;
const atom = accountId
? managedRelayQueryManager.environmentsAtom(accountId)
: EMPTY_ENVIRONMENTS_ATOM;
const result = useAtomValue(atom);
const refresh = useCallback(() => {
if (accountId) {
managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
}
}, [accountId]);
return {
...readManagedRelaySnapshotState(result),
accountId,
refresh,
};
}
export function useManagedRelayEnvironmentStatus(environment: RelayClientEnvironmentRecord) {
const session = useAtomValue(managedRelaySessionAtom);
const accountId = session?.accountId ?? null;
const atom = accountId
? managedRelayQueryManager.environmentStatusAtom({ accountId, environment })
: EMPTY_ENVIRONMENT_STATUS_ATOM;
const result = useAtomValue(atom);
const refresh = useCallback(() => {
if (accountId) {
managedRelayQueryManager.refreshEnvironmentStatus(appAtomRegistry, {
accountId,
environment,
});
}
}, [accountId, environment]);
return {
...readManagedRelaySnapshotState(result),
accountId,
refresh,
};
}
export function refreshManagedRelayEnvironments(): void {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session) {
managedRelayQueryManager.refreshEnvironments(appAtomRegistry, session.accountId);
}
}
@@ -0,0 +1,47 @@
import { describe, expect, it, vi } from "vitest";
import { resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
extra: {},
},
},
}));
describe("resolveCloudPublicConfig", () => {
it("returns no cloud configuration for an unconfigured build", () => {
expect(resolveCloudPublicConfig({})).toEqual({
clerkPublishableKey: null,
clerkJwtTemplate: null,
relayUrl: null,
});
});
it("normalizes statically injected cloud configuration", () => {
expect(
resolveCloudPublicConfig({
clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " },
relay: { url: " https://relay.example.test/// " },
}),
).toEqual({
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: "https://relay.example.test",
});
});
it("rejects an insecure relay URL", () => {
expect(
resolveCloudPublicConfig({
clerk: { publishableKey: "pk_test_example", jwtTemplate: "t3-relay" },
relay: { url: "http://relay.example.test" },
}),
).toEqual({
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: null,
});
});
});
@@ -0,0 +1,41 @@
import Constants from "expo-constants";
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
export interface CloudPublicConfig {
readonly clerkPublishableKey: string | null;
readonly clerkJwtTemplate: string | null;
readonly relayUrl: string | null;
}
function trimNonEmpty(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
const clerk = extra?.clerk as
| { readonly publishableKey?: unknown; readonly jwtTemplate?: unknown }
| undefined;
const relay = extra?.relay as { readonly url?: unknown } | undefined;
return {
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
} satisfies CloudPublicConfig;
}
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
}
export function resolveRelayClerkTokenOptions() {
const { clerkJwtTemplate } = resolveCloudPublicConfig();
if (!clerkJwtTemplate) {
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
}
return relayClerkTokenOptions(clerkJwtTemplate);
}
@@ -0,0 +1,134 @@
import { getClerkInstance } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import * as Data from "effect/Data";
import { useCallback, useRef } from "react";
import type { TurboModule } from "react-native";
import { TurboModuleRegistry } from "react-native";
const CLERK_CLIENT_JWT_KEY = "__clerk_client_jwt";
interface NativeClerkModule extends TurboModule {
readonly getClientToken?: () => Promise<string | null>;
readonly presentAuth?: (options: {
readonly dismissable: boolean;
readonly mode: "signInOrUp";
}) => Promise<NativeAuthResult | null>;
}
interface NativeAuthResult {
readonly cancelled?: boolean;
readonly session?: {
readonly id?: string;
};
readonly sessionId?: string;
}
interface ClerkWithNativeSync {
readonly __internal_reloadInitialResources?: () => Promise<void>;
readonly setActive?: (params: { readonly session: string }) => Promise<void>;
}
const NativeClerk = TurboModuleRegistry.get<NativeClerkModule>("ClerkExpo");
class NativeClerkAuthError extends Data.TaggedError("NativeClerkAuthError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
async function syncNativeSession(sessionId: string): Promise<void> {
const getClientToken = NativeClerk?.getClientToken;
let nativeClientToken: string | null = null;
if (getClientToken) {
try {
nativeClientToken = await getClientToken();
} catch (cause) {
throw new NativeClerkAuthError({
message: "Could not read native Clerk client token.",
cause,
});
}
}
if (nativeClientToken) {
const saveToken = tokenCache?.saveToken;
if (saveToken) {
try {
await saveToken(CLERK_CLIENT_JWT_KEY, nativeClientToken);
} catch (cause) {
throw new NativeClerkAuthError({
message: "Could not save native Clerk client token.",
cause,
});
}
}
}
const clerk = getClerkInstance();
const clerkWithNativeSync = clerk as ClerkWithNativeSync;
const reloadInitialResources = clerkWithNativeSync.__internal_reloadInitialResources;
if (reloadInitialResources) {
try {
await reloadInitialResources();
} catch (cause) {
throw new NativeClerkAuthError({
message: "Could not reload Clerk resources after native auth.",
cause,
});
}
}
const setActive = clerkWithNativeSync.setActive;
if (setActive) {
try {
await setActive({ session: sessionId });
} catch (cause) {
throw new NativeClerkAuthError({
message: "Could not activate native Clerk session.",
cause,
});
}
}
}
export function useNativeClerkAuthModal() {
const presentingRef = useRef(false);
const presentAuth = useCallback(async (): Promise<void> => {
if (presentingRef.current || !NativeClerk?.presentAuth) {
return;
}
presentingRef.current = true;
const presentNativeAuth = NativeClerk.presentAuth;
try {
// Clerk's iOS AuthView is not inline. It presents this same native modal
// internally; call the presenter directly so Expo Router does not render
// an empty formSheet behind it.
let result: NativeAuthResult | null;
try {
result = await presentNativeAuth({
dismissable: true,
mode: "signInOrUp",
});
} catch (cause) {
throw new NativeClerkAuthError({
message: "Native Clerk auth presentation failed.",
cause,
});
}
const sessionId = result?.sessionId ?? result?.session?.id ?? null;
if (sessionId && !result?.cancelled) {
await syncNativeSession(sessionId);
}
} catch (error) {
if (__DEV__) {
console.error("[useNativeClerkAuthModal] presentAuth failed:", error);
}
} finally {
presentingRef.current = false;
}
}, []);
return {
isAvailable: !!NativeClerk?.presentAuth,
presentAuth,
};
}
@@ -113,56 +113,66 @@ export function ConnectionEnvironmentRow(props: {
exiting={FadeOut.duration(150)}
className="gap-3 px-4 pb-4"
>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Label
{props.environment.isRelayManaged ? (
<Text className="text-[13px] leading-[18px] text-foreground-muted">
Managed by T3 Cloud. Tunnel details update automatically.
</Text>
<TextInput
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook"
placeholderTextColor={placeholderColor}
value={label}
onChangeText={setLabel}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
) : (
<>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Label
</Text>
<TextInput
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook"
placeholderTextColor={placeholderColor}
value={label}
onChangeText={setLabel}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
URL
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={url}
onChangeText={setUrl}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
URL
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={url}
onChangeText={setUrl}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
</>
)}
<View className="flex-row gap-2">
<Pressable
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"
onPress={handleSave}
>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
<Text
className="text-[12px] font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.8 }}
<View className="flex-row justify-end gap-2">
{props.environment.isRelayManaged ? null : (
<Pressable
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"
onPress={handleSave}
>
Save
</Text>
</Pressable>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
<Text
className="text-[12px] font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.8 }}
>
Save
</Text>
</Pressable>
)}
<Pressable
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70"
@@ -41,7 +41,6 @@ import {
refreshSourceControlDiscoveryForEnvironment,
useSourceControlDiscovery,
} from "../../state/use-source-control-discovery";
import { NewTaskSheetHeader } from "../threads/NewTaskSheetHeader";
interface EnvironmentOption {
readonly environmentId: EnvironmentId;
@@ -105,25 +104,11 @@ function SectionTitle(props: { readonly children: string }) {
);
}
function AddProjectShell(props: {
readonly title: string;
readonly closeToNew?: boolean;
readonly children: ReactNode;
}) {
const router = useRouter();
function AddProjectShell(props: { readonly children: ReactNode }) {
const insets = useSafeAreaInsets();
return (
<View className="flex-1 bg-sheet">
<NewTaskSheetHeader
eyebrow="New project"
title={props.title}
control={{
icon: props.closeToNew ? "xmark" : "chevron.left",
onPress: () => router.back(),
}}
/>
<ScrollView
keyboardShouldPersistTaps="handled"
contentInsetAdjustmentBehavior="automatic"
@@ -179,9 +164,9 @@ function ListRow(props: {
{props.icon}
</View>
<View className="flex-1 gap-0.5">
<Text className="text-[15px] font-t3-bold">{props.title}</Text>
<Text className="text-[16px] leading-[21px] font-t3-bold">{props.title}</Text>
{props.subtitle ? (
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={2}>
<Text className="text-[13px] leading-[17px] text-foreground-muted" numberOfLines={2}>
{props.subtitle}
</Text>
) : null}
@@ -363,7 +348,7 @@ export function AddProjectSourceScreen() {
}, [selectedEnvironment]);
return (
<AddProjectShell title="Select source" closeToNew>
<AddProjectShell>
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
{environmentOptions.length > 1 ? (
@@ -561,7 +546,7 @@ export function AddProjectRepositoryScreen() {
}, [environment, isSubmitting, repositoryInput, router, source]);
return (
<AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
<AddProjectShell>
{error ? <ErrorBanner message={error} /> : null}
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-[15px] leading-[20px]"
@@ -711,7 +696,7 @@ export function AddProjectLocalFolderScreen() {
}, [createProject, environment, isSubmitting, pathInput]);
return (
<AddProjectShell title="Local folder">
<AddProjectShell>
{error ? <ErrorBanner message={error} /> : null}
{environment ? (
<>
@@ -790,7 +775,7 @@ export function AddProjectDestinationScreen() {
}, [createProject, environment, isSubmitting, pathInput, remoteUrl]);
return (
<AddProjectShell title="Clone destination">
<AddProjectShell>
{error ? <ErrorBanner message={error} /> : null}
{repositoryTitle ? (
<View className="rounded-[24px] bg-card px-4 py-3">
@@ -238,17 +238,18 @@ export function ReviewCommentComposerSheet() {
<View className="min-h-0 flex-1 gap-2">
<Text className="text-[13px] font-t3-bold text-foreground">Comment</Text>
<View className="min-h-[132px] flex-1 overflow-hidden rounded-[20px] border border-border bg-card">
<View className="flex-1 px-4 pt-3.5">
<TextInputWrapper onPaste={handleNativePaste} style={{ flex: 1 }}>
<View className="min-h-0 flex-1 px-4 pt-3.5">
<TextInputWrapper onPaste={handleNativePaste} style={{ flex: 1, minHeight: 0 }}>
<TextInput
autoFocus
multiline
scrollEnabled
placeholder="Leave a comment..."
textAlignVertical="top"
value={commentText}
onChangeText={setCommentText}
className="h-full flex-1 border-0 bg-transparent px-0 py-0 font-sans text-[15px]"
style={{ flex: 1 }}
style={{ flex: 1, minHeight: 0 }}
/>
</TextInputWrapper>
</View>
@@ -8,16 +8,7 @@ import type { KnownTerminalSession } from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Pressable,
ScrollView,
Text as RNText,
View,
useColorScheme,
type LayoutChangeEvent,
type NativeScrollEvent,
type NativeSyntheticEvent,
} from "react-native";
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
import {
KeyboardController,
KeyboardEvents,
@@ -25,6 +16,11 @@ import {
useKeyboardState,
} from "react-native-keyboard-controller";
import {
ComposerToolbarButton,
ComposerToolbarRow,
ComposerToolbarScroller,
} from "../../components/ComposerToolbarTrigger";
import { EmptyState } from "../../components/EmptyState";
import { GlassSurface } from "../../components/GlassSurface";
import { LoadingScreen } from "../../components/LoadingScreen";
@@ -79,7 +75,6 @@ import {
const DEFAULT_TERMINAL_COLS = 80;
const DEFAULT_TERMINAL_ROWS = 24;
const TERMINAL_ACCESSORY_HEIGHT = 52;
const TERMINAL_ACCESSORY_FADE_WIDTH = 18;
type PendingModifier = "ctrl" | "meta";
type HostPlatform = "mac" | "linux" | "windows" | "unknown";
@@ -94,47 +89,6 @@ type TerminalToolbarAction =
readonly modifier: PendingModifier;
};
function getTerminalStatusTone(input: {
readonly status: TerminalMenuSession["status"];
readonly hasRunningSubprocess?: boolean;
}): {
readonly tintColor: string;
readonly textColor: string;
} {
if (input.status === "running") {
if (input.hasRunningSubprocess) {
return {
tintColor: "#fbbf24",
textColor: "#a3a3a3",
};
}
return {
tintColor: "#34d399",
textColor: "#a3a3a3",
};
}
if (input.status === "starting") {
return {
tintColor: "#f59e0b",
textColor: "#a3a3a3",
};
}
if (input.status === "error") {
return {
tintColor: "#ef4444",
textColor: "#fca5a5",
};
}
return {
tintColor: "#ef4444",
textColor: "#a3a3a3",
};
}
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
return value[0] ?? null;
@@ -186,10 +140,6 @@ function applyCtrlModifier(input: string): string {
return input;
}
function withAlpha(hexColor: string, alpha: string): string {
return /^#[0-9a-f]{6}$/i.test(hexColor) ? `${hexColor}${alpha}` : hexColor;
}
function pickRunningTerminalSessionForBootstrap(
sessions: ReadonlyArray<KnownTerminalSession>,
): KnownTerminalSession | null {
@@ -248,15 +198,6 @@ export function ThreadTerminalRouteScreen() {
const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE);
const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
const toolbarScrollGeometryRef = useRef({
contentWidth: 0,
offsetX: 0,
viewportWidth: 0,
});
const [toolbarScrollEdges, setToolbarScrollEdges] = useState({
showLeftFade: false,
showRightFade: false,
});
const hasOpenedRef = useRef(false);
const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const attachStreamLogCountRef = useRef(0);
@@ -370,14 +311,6 @@ export function ThreadTerminalRouteScreen() {
activeKnownSummary: activeKnownSession?.state.summary ?? null,
};
const terminalStatusTone = useMemo(
() =>
getTerminalStatusTone({
status: terminal.status,
hasRunningSubprocess: terminal.hasRunningSubprocess,
}),
[terminal.hasRunningSubprocess, terminal.status],
);
const terminalTheme = getPierreTerminalTheme(appearanceScheme);
const pendingModifier =
pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
@@ -964,47 +897,6 @@ export function ThreadTerminalRouteScreen() {
[handleClearTerminal, pendingModifier, terminalId, writeInput],
);
const updateToolbarScrollEdges = useCallback(
(patch: Partial<(typeof toolbarScrollGeometryRef)["current"]>) => {
const nextGeometry = { ...toolbarScrollGeometryRef.current, ...patch };
toolbarScrollGeometryRef.current = nextGeometry;
const nextEdges = {
showLeftFade: nextGeometry.offsetX > 1,
showRightFade:
nextGeometry.offsetX + nextGeometry.viewportWidth < nextGeometry.contentWidth - 1,
};
setToolbarScrollEdges((current) =>
current.showLeftFade === nextEdges.showLeftFade &&
current.showRightFade === nextEdges.showRightFade
? current
: nextEdges,
);
},
[],
);
const handleToolbarLayout = useCallback(
(event: LayoutChangeEvent) => {
updateToolbarScrollEdges({ viewportWidth: event.nativeEvent.layout.width });
},
[updateToolbarScrollEdges],
);
const handleToolbarContentSizeChange = useCallback(
(contentWidth: number) => {
updateToolbarScrollEdges({ contentWidth });
},
[updateToolbarScrollEdges],
);
const handleToolbarScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
updateToolbarScrollEdges({ offsetX: event.nativeEvent.contentOffset.x });
},
[updateToolbarScrollEdges],
);
const handleDismissKeyboard = useCallback(() => {
setIsAccessoryDismissed(true);
void KeyboardController.dismiss();
@@ -1089,17 +981,7 @@ export function ThreadTerminalRouteScreen() {
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
icon="circle.fill"
style={{
color: terminalStatusTone.textColor,
fontFamily: "DMSans_700Bold",
fontSize: 12,
fontWeight: "700",
}}
tintColor={terminalStatusTone.tintColor}
title="Terminal options"
>
<Stack.Toolbar.Menu icon="terminal" title="Terminal options" separateBackground>
<Stack.Toolbar.Label>
{getTerminalStatusLabel({
status: terminal.status,
@@ -1170,127 +1052,43 @@ export function ThreadTerminalRouteScreen() {
borderTopColor: terminalTheme.border,
borderTopWidth: 1,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
paddingBottom: 4,
paddingHorizontal: 8,
paddingTop: 4,
}}
>
<View style={{ alignItems: "center", flexDirection: "row", gap: 6 }}>
<View style={{ flex: 1, position: "relative" }}>
<ScrollView
horizontal
contentContainerStyle={{ alignItems: "center", gap: 6, paddingRight: 2 }}
onContentSizeChange={handleToolbarContentSizeChange}
onLayout={handleToolbarLayout}
onScroll={handleToolbarScroll}
scrollEventThrottle={16}
showsHorizontalScrollIndicator={false}
>
{terminalToolbarActions.map((action) => {
const active =
action.kind === "modifier" && pendingModifier === action.modifier;
return (
<Pressable
key={action.key}
onPress={() => handleToolbarActionPress(action)}
style={({ pressed }) => ({
alignItems: "center",
backgroundColor: active
? withAlpha(
terminalTheme.palette[10] ?? terminalTheme.foreground,
"2e",
)
: pressed
? withAlpha(terminalTheme.foreground, "1f")
: withAlpha(terminalTheme.foreground, "12"),
borderColor: active
? withAlpha(
terminalTheme.palette[10] ?? terminalTheme.foreground,
"52",
)
: terminalTheme.border,
borderRadius: 12,
borderWidth: 1,
justifyContent: "center",
minWidth: action.label.length > 1 ? 46 : 38,
paddingHorizontal: 11,
paddingVertical: 8,
})}
>
<RNText
style={{
color: active
? (terminalTheme.palette[10] ?? terminalTheme.foreground)
: terminalTheme.foreground,
fontFamily: "DMSans_700Bold",
fontSize: 12,
fontWeight: "700",
textTransform:
action.kind === "modifier" || action.kind === "clear"
? "uppercase"
: "none",
}}
>
{action.label}
</RNText>
</Pressable>
);
})}
</ScrollView>
{toolbarScrollEdges.showLeftFade ? (
<View
pointerEvents="none"
style={{
bottom: 0,
experimental_backgroundImage: `linear-gradient(to right, ${terminalTheme.background} 0%, ${withAlpha(terminalTheme.background, "00")} 100%)`,
left: 0,
position: "absolute",
top: 0,
width: TERMINAL_ACCESSORY_FADE_WIDTH,
}}
/>
) : null}
{toolbarScrollEdges.showRightFade ? (
<View
pointerEvents="none"
style={{
bottom: 0,
experimental_backgroundImage: `linear-gradient(to right, ${withAlpha(terminalTheme.background, "00")} 0%, ${terminalTheme.background} 100%)`,
position: "absolute",
right: 0,
top: 0,
width: TERMINAL_ACCESSORY_FADE_WIDTH,
}}
/>
) : null}
</View>
<Pressable
accessibilityLabel="Dismiss keyboard"
accessibilityRole="button"
onPress={handleDismissKeyboard}
style={({ pressed }) => ({
alignItems: "center",
backgroundColor: pressed
? withAlpha(terminalTheme.foreground, "1f")
: withAlpha(terminalTheme.foreground, "12"),
borderColor: terminalTheme.border,
borderRadius: 12,
borderWidth: 1,
justifyContent: "center",
minWidth: 38,
paddingHorizontal: 11,
paddingVertical: 8,
})}
<ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
<ComposerToolbarScroller
contentPaddingRight={2}
fadeOpaque={terminalTheme.background}
fadeTransparent={`${terminalTheme.background}00`}
>
<SymbolView
name={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
size={14}
tintColor={terminalTheme.foreground}
type="monochrome"
/>
</Pressable>
</View>
{terminalToolbarActions.map((action) => {
const active =
action.kind === "modifier" && pendingModifier === action.modifier;
return (
<ComposerToolbarButton
key={action.key}
active={active}
label={action.label}
maxWidth={120}
minWidth={action.label.length > 1 ? 56 : 44}
onPress={() => handleToolbarActionPress(action)}
showChevron={false}
textTransform={
action.kind === "modifier" || action.kind === "clear"
? "uppercase"
: "none"
}
/>
);
})}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel="Dismiss keyboard"
icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
onPress={handleDismissKeyboard}
showChevron={false}
/>
</ComposerToolbarRow>
</View>
</KeyboardStickyView>
) : !keyboardState.isVisible ? (
@@ -1,16 +1,27 @@
import { useRouter } from "expo-router";
import { Stack, useRouter } from "expo-router";
import { TextInputWrapper } from "expo-paste-input";
import { useCallback, useEffect, useMemo } from "react";
import { View } from "react-native";
import { KeyboardStickyView, useKeyboardState } from "react-native-keyboard-controller";
import { useCallback, useEffect, useMemo, useRef } from "react";
import {
InteractionManager,
View,
useColorScheme,
type TextInput as RNTextInput,
} from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
import { AppTextInput as TextInput } from "../../components/AppText";
import {
ComposerToolbarButton,
ComposerToolbarRow,
ComposerToolbarScroller,
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
@@ -18,7 +29,6 @@ import { buildThreadRoutePath } from "../../lib/routes";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useNativePaste } from "../../lib/useNativePaste";
import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
import { NewTaskSheetHeader } from "./NewTaskSheetHeader";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useProjectActions } from "./use-project-actions";
@@ -34,6 +44,22 @@ function withModelSelectionOption(
};
}
function formatTitleCase(value: string): string {
return value.length === 0 ? value : `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
}
function formatWorkspaceLabel(input: {
readonly workspaceMode: string;
readonly currentBranchName: string | null;
readonly selectedBranchName: string | null;
}): string {
const branchName = input.selectedBranchName ?? input.currentBranchName;
if (input.workspaceMode === "worktree") {
return branchName ? `New worktree · ${branchName}` : "New worktree";
}
return branchName ? `Current · ${branchName}` : "Current checkout";
}
export function NewTaskDraftScreen(props: {
readonly initialProjectRef?: {
readonly environmentId?: string;
@@ -45,11 +71,15 @@ export function NewTaskDraftScreen(props: {
const flow = useNewTaskFlow();
const router = useRouter();
const insets = useSafeAreaInsets();
const colorScheme = useColorScheme();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const promptInputRef = useRef<RNTextInput>(null);
const borderColor = useThemeColor("--color-border");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
useEffect(() => {
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
@@ -93,6 +123,24 @@ export function NewTaskDraftScreen(props: {
void flow.loadBranches();
}, [flow, selectedProject]);
useEffect(() => {
if (!selectedProject) {
return;
}
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
const interaction = InteractionManager.runAfterInteractions(() => {
focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
});
return () => {
interaction.cancel();
if (focusFrame !== null) {
cancelAnimationFrame(focusFrame);
}
};
}, [selectedProject]);
const environmentMenuActions = useMemo(
() =>
flow.environments.map((environment) => ({
@@ -231,10 +279,10 @@ export function NewTaskDraftScreen(props: {
{
id: "workspace:mode",
title: "Mode",
subtitle: flow.workspaceMode === "local" ? "Local" : "Worktree",
subtitle: flow.workspaceMode === "local" ? "Current checkout" : "New worktree",
subactions: (["local", "worktree"] as const).map((value) => ({
id: `workspace:mode:${value}`,
title: value === "local" ? "Local" : "Worktree",
title: value === "local" ? "Current checkout" : "New worktree",
state: flow.workspaceMode === value ? ("on" as const) : undefined,
})),
},
@@ -253,6 +301,31 @@ export function NewTaskDraftScreen(props: {
flow.workspaceMode,
]);
const selectedEnvironmentLabel =
flow.environments.find(
(environment) => environment.environmentId === flow.selectedEnvironmentId,
)?.environmentLabel ?? "Environment";
const currentBranchName =
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const configurationLabel = useMemo(() => {
const parts = [
formatTitleCase(flow.effort),
flow.fastMode ? "Fast" : null,
flow.contextWindow !== "1M" ? flow.contextWindow : null,
].filter((part): part is string => Boolean(part));
return parts.length > 0 ? parts.join(" · ") : "Configuration";
}, [flow.contextWindow, flow.effort, flow.fastMode]);
const workspaceLabel = useMemo(
() =>
formatWorkspaceLabel({
currentBranchName,
selectedBranchName: flow.selectedBranchName,
workspaceMode: flow.workspaceMode,
}),
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
);
function handleModelMenuAction(event: string) {
if (!event.startsWith("model:")) {
return;
@@ -382,6 +455,8 @@ export function NewTaskDraftScreen(props: {
});
if (createdThread) {
flow.setPrompt("");
flow.clearAttachments();
router.replace(buildThreadRoutePath(createdThread));
}
} finally {
@@ -392,40 +467,36 @@ export function NewTaskDraftScreen(props: {
if (!selectedProject) {
return (
<View className="flex-1 bg-sheet">
<NewTaskSheetHeader title="Loading task" />
<Stack.Screen options={{ title: "Loading task" }} />
</View>
);
}
return (
<View className="flex-1 bg-sheet">
<NewTaskSheetHeader
title={selectedProject.title}
control={
flow.logicalProjects.length > 1
? { icon: "chevron.left", onPress: () => router.back() }
: undefined
}
/>
<Stack.Screen options={{ title: selectedProject.title }} />
<View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 8 }}>
<TextInputWrapper
onPaste={(payload) => void handleNativePaste(payload)}
style={{ flex: 1 }}
>
<TextInput
multiline
value={flow.prompt}
onChangeText={flow.setPrompt}
placeholder={`Describe a coding task in ${selectedProject.title}`}
textAlignVertical="top"
className="h-full flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
style={{ flex: 1 }}
/>
</TextInputWrapper>
</View>
<KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
<View style={{ flex: 1, minHeight: 0, paddingHorizontal: 20, paddingTop: 8 }}>
<TextInputWrapper
onPaste={(payload) => void handleNativePaste(payload)}
style={{ flex: 1, minHeight: 0 }}
>
<TextInput
ref={promptInputRef}
autoFocus
multiline
scrollEnabled
value={flow.prompt}
onChangeText={flow.setPrompt}
placeholder={`Describe a coding task in ${selectedProject.title}`}
textAlignVertical="top"
className="h-full flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
style={{ flex: 1, minHeight: 0 }}
/>
</TextInputWrapper>
</View>
<KeyboardStickyView>
<View
style={{
borderTopWidth: 1,
@@ -443,41 +514,65 @@ export function NewTaskDraftScreen(props: {
/>
</View>
) : null}
<View className="flex-row items-center justify-between gap-2 px-4 pt-2">
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
<ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
<ComposerToolbarScroller
fadeOpaque={sheetFadeOpaque}
fadeTransparent={sheetFadeTransparent}
>
<ControlPill
iconNode={
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
}
<ComposerToolbarButton
icon="plus"
onPress={() => void handlePickImages()}
showChevron={false}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ControlPill icon="slider.horizontal.3" />
</ControlPillMenu>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
>
<ControlPill icon="desktopcomputer" />
</ControlPillMenu>
<ControlPillMenu
actions={workspaceMenuActions}
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
>
<ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
</ControlPillMenu>
<ControlPill
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
}
label={flow.selectedModelOption?.label ?? "Model"}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Environment"
icon="desktopcomputer"
label={selectedEnvironmentLabel}
/>
</ControlPillMenu>
<ControlPillMenu
actions={workspaceMenuActions}
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Workspace"
icon="point.topleft.down.curvedto.point.bottomright.up"
label={workspaceLabel}
/>
</ControlPillMenu>
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={flow.submitting ? "Starting task" : "Start task"}
icon="arrow.up"
label={flow.submitting ? "Starting" : "Start"}
onPress={() => void handleStart()}
variant="primary"
showChevron={false}
disabled={
!flow.selectedProject ||
!flow.selectedModel ||
@@ -486,9 +581,9 @@ export function NewTaskDraftScreen(props: {
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
}
/>
</View>
</ComposerToolbarRow>
</View>
</KeyboardStickyView>
</KeyboardAvoidingView>
</View>
);
}
@@ -1,46 +0,0 @@
import { SymbolView } from "expo-symbols";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
export function NewTaskSheetHeader(props: {
readonly eyebrow?: string;
readonly title: string;
readonly control?: {
readonly icon: "chevron.left" | "xmark";
readonly onPress: () => void;
};
}) {
const iconColor = useThemeColor("--color-icon");
return (
<>
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
{props.control ? (
<Pressable
className="absolute left-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1 }}
onPress={props.control.onPress}
>
<SymbolView
name={props.control.icon}
size={16}
tintColor={iconColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
{props.eyebrow ?? "New task"}
</Text>
<Text className="text-[28px] font-t3-bold">{props.title}</Text>
</View>
</>
);
}
@@ -30,6 +30,12 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import {
ComposerToolbarButton,
ComposerToolbarRow,
ComposerToolbarScroller,
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
@@ -66,7 +72,7 @@ export const COMPOSER_EXPANDED_CHROME = 174;
* Used by the feed inset because KeyboardAvoidingLegendList only accounts for
* keyboard height; the floating toolbar remains an additional overlay.
*/
export const COMPOSER_EXPANDED_TOOLBAR_CHROME = 54;
export const COMPOSER_EXPANDED_TOOLBAR_CHROME = 60;
export interface ThreadComposerProps {
readonly draftMessage: string;
@@ -84,7 +90,6 @@ export interface ThreadComposerProps {
readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onRefresh: () => Promise<void>;
readonly onStopThread: () => Promise<void>;
readonly onSendMessage: () => void;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => Promise<void>;
@@ -144,6 +149,10 @@ function withModelSelectionOption(
};
}
function formatTitleCase(value: string): string {
return value.length === 0 ? value : `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
}
export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
const isDarkMode = useColorScheme() === "dark";
const themePlaceholderColor = useThemeColor("--color-placeholder");
@@ -183,10 +192,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
props.queueCount > 0;
const sendLabel = props.activeThreadBusy || props.queueCount > 0 ? "Queue" : "Send";
const modelProvider = props.selectedThread.modelSelection?.instanceId ?? null;
const currentModelSelection = props.selectedThread.modelSelection;
const currentRuntimeMode = props.selectedThread.runtimeMode;
const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
const toolbarFadeOpaque = isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)";
const toolbarFadeTransparent = isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)";
const selectedProviderStatus = useMemo(() => {
if (!props.serverConfig) return null;
return (
@@ -430,11 +440,25 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
);
// ── Model menu ───────────────────────────────────────────
const providerGroups = useMemo(() => {
const options = buildModelOptions(props.serverConfig, currentModelSelection);
return groupByProvider(options);
}, [props.serverConfig, currentModelSelection]);
const modelOptions = useMemo(
() => buildModelOptions(props.serverConfig, currentModelSelection),
[props.serverConfig, currentModelSelection],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
const currentModelOption =
modelOptions.find(
(option) =>
option.selection.instanceId === currentModelSelection.instanceId &&
option.selection.model === currentModelSelection.model,
) ?? null;
const configurationLabel = useMemo(() => {
const parts = [
formatTitleCase(currentEffort),
currentFastMode ? "Fast" : null,
currentContextWindow !== "1M" ? currentContextWindow : null,
].filter((part): part is string => Boolean(part));
return parts.length > 0 ? parts.join(" · ") : "Configuration";
}, [currentContextWindow, currentEffort, currentFastMode]);
const modelMenuActions = useMemo(
() =>
providerGroups.map((group) => ({
@@ -545,8 +569,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
return;
}
const modelKey = event.slice("model:".length);
const options = buildModelOptions(props.serverConfig, currentModelSelection);
const option = options.find((o) => o.key === modelKey);
const option = modelOptions.find((o) => o.key === modelKey);
if (option) {
void props.onUpdateModelSelection(option.selection);
}
@@ -752,44 +775,56 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
{/* Toolbar row — matches draft page layout (expanded only) */}
{isExpanded ? (
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingTop: 10,
gap: 8,
}}
>
<ControlPill icon="plus" onPress={() => void props.onPickDraftImages()} />
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
<ComposerToolbarScroller
fadeOpaque={toolbarFadeOpaque}
fadeTransparent={toolbarFadeTransparent}
>
<ControlPill iconNode={<ProviderIcon provider={modelProvider} size={16} />} />
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ControlPill icon="slider.horizontal.3" />
</ControlPillMenu>
<ControlPill icon="arrow.clockwise" onPress={() => void props.onRefresh()} />
{showStopAction ? (
<ControlPill
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
<ComposerToolbarButton
icon="plus"
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
) : null}
<ControlPill
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
showChevron={false}
/>
) : null}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={sendLabel}
icon="arrow.up"
label={sendLabel}
variant="primary"
disabled={!canSend}
onPress={handleSend}
showChevron={false}
/>
</View>
</ComposerToolbarRow>
) : null}
{/* Queue count */}
@@ -67,7 +67,6 @@ export interface ThreadDetailScreenProps {
readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onRefresh: () => Promise<void>;
readonly onStopThread: () => Promise<void>;
readonly onSendMessage: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise<void>;
@@ -198,18 +197,17 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
});
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const { onOpenDrawer, onRefresh } = props;
const { onOpenDrawer } = props;
const insets = useSafeAreaInsets();
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const composerBottomInset = Math.max(insets.bottom, 12);
const [composerExpanded, setComposerExpanded] = useState(false);
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
const [refreshing, setRefreshing] = useState(false);
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
@@ -223,19 +221,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onOpenDrawer();
}, [onOpenDrawer]);
const handleRefresh = useCallback(async (): Promise<void> => {
if (refreshing) {
return;
}
setRefreshing(true);
try {
await onRefresh();
} finally {
setRefreshing(false);
}
}, [onRefresh, refreshing]);
const drawerGestureThreshold = 80;
const headerDrawerGesture = useMemo(
() =>
@@ -273,8 +258,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
contentBottomInset={feedBottomInset}
layoutVariant={layoutVariant}
composerExpanded={composerExpanded}
refreshing={refreshing}
onRefresh={handleRefresh}
/>
) : (
<View style={{ flex: 1 }} />
@@ -330,7 +313,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onRefresh={props.onRefresh}
onStopThread={props.onStopThread}
onSendMessage={props.onSendMessage}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
@@ -55,8 +55,6 @@ export interface ThreadFeedProps {
readonly bearerToken: string | null;
readonly agentLabel: string;
readonly contentBottomInset?: number;
readonly refreshing?: boolean;
readonly onRefresh?: () => void;
readonly layoutVariant?: MobileLayoutVariant;
readonly composerExpanded?: boolean;
}
@@ -958,8 +956,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
on: { layout: true, itemLayout: true, dataChange: true },
}}
maintainScrollAtEndThreshold={0.1}
refreshing={props.refreshing ?? false}
onRefresh={props.onRefresh}
safeAreaInsetBottom={insets.bottom}
contentContainerStyle={{
paddingTop: 12,
@@ -7,7 +7,7 @@ import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { useVcsStatus, vcsStatusManager } from "../../state/use-vcs-status";
import { useVcsStatus } from "../../state/use-vcs-status";
import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
import { EmptyState } from "../../components/EmptyState";
@@ -53,6 +53,10 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
return value ?? null;
}
function OpeningThreadLoadingScreen() {
return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
}
export function ThreadRouteScreen() {
const { isLoadingSavedConnection, environmentStateById, pendingConnectionError } =
useRemoteEnvironmentState();
@@ -70,7 +74,6 @@ export function ThreadRouteScreen() {
const commands = useSelectedThreadCommands({
refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus,
});
const refreshSelectedThread = commands.onRefresh;
const router = useRouter();
const params = useLocalSearchParams<{
environmentId?: string | string[];
@@ -122,20 +125,6 @@ export function ThreadRouteScreen() {
);
const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
const handleRefreshGitStatus = useCallback(async () => {
if (!selectedThread) return;
await vcsStatusManager.refresh({
environmentId: selectedThread.environmentId,
cwd: selectedThreadCwd,
});
}, [selectedThread, selectedThreadCwd]);
/** Wraps thread refresh + git status refresh for pull-to-refresh */
const handleRefreshAll = useCallback(async () => {
await refreshSelectedThread();
await handleRefreshGitStatus();
}, [handleRefreshGitStatus, refreshSelectedThread]);
const handleOpenDrawer = useCallback(() => {
setDrawerVisible(true);
}, []);
@@ -245,7 +234,7 @@ export function ThreadRouteScreen() {
);
if (!environmentId || !threadId) {
return <LoadingScreen message="Opening thread…" />;
return <OpeningThreadLoadingScreen />;
}
if (!selectedThread) {
@@ -255,7 +244,7 @@ export function ThreadRouteScreen() {
routeConnectionState === "reconnecting";
if (stillHydrating) {
return <LoadingScreen message="Opening thread…" />;
return <OpeningThreadLoadingScreen />;
}
return (
@@ -278,7 +267,7 @@ export function ThreadRouteScreen() {
}
if (!selectedThreadDetail) {
return <LoadingScreen message="Opening thread…" />;
return <OpeningThreadLoadingScreen />;
}
const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
@@ -388,7 +377,6 @@ export function ThreadRouteScreen() {
onPickDraftImages={composer.onPickDraftImages}
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
onRefresh={handleRefreshAll}
serverConfig={serverConfig}
onStopThread={commands.onStopThread}
onSendMessage={composer.onSendMessage}
@@ -15,6 +15,13 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import {
appendComposerDraftAttachments,
removeComposerDraftAttachment,
replaceComposerDraftAttachments,
setComposerDraftText,
useComposerDraft,
} from "../../state/use-composer-drafts";
import { vcsRefManager, useVcsRefs } from "../../state/use-vcs-refs";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import {
@@ -153,8 +160,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
const branchLoadVersionRef = useRef(0);
const [prompt, setPrompt] = useState("");
const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
const [submitting, setSubmitting] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
@@ -166,28 +171,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [contextWindow, setContextWindow] = useState("1M");
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
const replaceAttachments = useCallback(
(nextAttachments: ReadonlyArray<DraftComposerImageAttachment>) => {
setAttachments(nextAttachments);
},
[],
);
const appendAttachments = useCallback(
(nextAttachments: ReadonlyArray<DraftComposerImageAttachment>) => {
setAttachments((current) => [...current, ...nextAttachments]);
},
[],
);
const removeAttachment = useCallback((imageId: string) => {
setAttachments((current) => current.filter((candidate) => candidate.id !== imageId));
}, []);
const clearAttachments = useCallback(() => {
setAttachments([]);
}, []);
const reset = useCallback(() => {
console.log("[new task flow] reset", {
defaultEnvironmentId: projects[0]?.environmentId ?? null,
@@ -199,8 +182,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setWorkspaceMode("local");
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setPrompt("");
clearAttachments();
setSubmitting(false);
setBranchQuery("");
setRuntimeMode(DEFAULT_RUNTIME_MODE);
@@ -209,7 +190,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setFastMode(false);
setContextWindow("1M");
setExpandedProvider(null);
}, [clearAttachments, projects]);
}, [projects]);
useEffect(() => {
if (selectedEnvironmentId !== null || projects.length === 0) {
@@ -271,6 +252,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
) ??
projectsForEnvironment[0] ??
null;
const selectedProjectDraftKey = selectedProject
? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`
: null;
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
const modelOptions = useMemo(
() =>
@@ -298,6 +285,48 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
) ?? null;
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
const setPrompt = useCallback(
(value: string) => {
if (!selectedProjectDraftKey) {
return;
}
setComposerDraftText(selectedProjectDraftKey, value);
},
[selectedProjectDraftKey],
);
const replaceAttachments = useCallback(
(nextAttachments: ReadonlyArray<DraftComposerImageAttachment>) => {
if (!selectedProjectDraftKey) {
return;
}
replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
},
[selectedProjectDraftKey],
);
const appendAttachments = useCallback(
(nextAttachments: ReadonlyArray<DraftComposerImageAttachment>) => {
if (!selectedProjectDraftKey) {
return;
}
appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
},
[selectedProjectDraftKey],
);
const removeAttachment = useCallback(
(imageId: string) => {
if (!selectedProjectDraftKey) {
return;
}
removeComposerDraftAttachment(selectedProjectDraftKey, imageId);
},
[selectedProjectDraftKey],
);
const clearAttachments = useCallback(() => {
if (!selectedProjectDraftKey) {
return;
}
replaceComposerDraftAttachments(selectedProjectDraftKey, []);
}, [selectedProjectDraftKey]);
const branchTarget = useMemo(
() => ({
environmentId: selectedProject?.environmentId ?? null,
+10
View File
@@ -0,0 +1,10 @@
import type { AuthClientPresentationMetadata } from "@t3tools/contracts";
import { Platform } from "react-native";
export function mobileAuthClientMetadata(): AuthClientPresentationMetadata {
return {
label: "T3 Code Mobile",
deviceType: "mobile",
...(Platform.OS === "ios" ? { os: "iOS" } : Platform.OS === "android" ? { os: "Android" } : {}),
};
}
+34 -2
View File
@@ -1,9 +1,15 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { EnvironmentId } from "@t3tools/contracts";
import { mobileAuthClientMetadata, redactPairingCredential } from "./connection";
import {
isRelayManagedConnection,
mobileAuthClientMetadata,
redactPairingCredential,
toStableSavedRemoteConnection,
} from "./connection";
vi.mock("./runtime", () => ({
mobileRemoteHttpRuntime: {
mobileRuntime: {
runPromise: vi.fn(),
},
}));
@@ -39,4 +45,30 @@ describe("mobile remote connection records", () => {
),
).toBe("https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.example&label=Desktop");
});
it("recognizes explicitly managed relay connections", () => {
expect(isRelayManagedConnection({ relayManaged: true })).toBe(true);
});
it("keeps existing DPoP tunnel records read-only after upgrading", () => {
expect(isRelayManagedConnection({ authenticationMethod: "dpop" })).toBe(true);
expect(isRelayManagedConnection({ authenticationMethod: "bearer" })).toBe(false);
});
it("drops short-lived managed environment credentials from stable records", () => {
const connection = {
environmentId: EnvironmentId.make("environment-1"),
environmentLabel: "Desktop",
pairingUrl: "https://desktop.example/",
displayUrl: "https://desktop.example/",
httpBaseUrl: "https://desktop.example/",
wsBaseUrl: "wss://desktop.example/",
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: "short-lived-token",
relayManaged: true,
} as const;
expect(toStableSavedRemoteConnection(connection)).not.toHaveProperty("dpopAccessToken");
});
});
+40 -22
View File
@@ -1,11 +1,14 @@
import { type AuthClientPresentationMetadata, EnvironmentId } from "@t3tools/contracts";
import { EnvironmentId } from "@t3tools/contracts";
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
} from "@t3tools/client-runtime";
import { resolveRemotePairingTarget, stripPairingTokenFromUrl } from "@t3tools/shared/remote";
import { Platform } from "react-native";
import { mobileRemoteHttpRuntime } from "./runtime";
import * as Effect from "effect/Effect";
import { mobileAuthClientMetadata } from "./authClientMetadata";
import { mobileRuntime } from "./runtime";
export { mobileAuthClientMetadata } from "./authClientMetadata";
export interface RemoteConnectionInput {
readonly pairingUrl: string;
@@ -18,7 +21,10 @@ export interface SavedRemoteConnection {
readonly displayUrl: string;
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly bearerToken: string;
readonly bearerToken: string | null;
readonly authenticationMethod?: "bearer" | "dpop";
readonly dpopAccessToken?: string;
readonly relayManaged?: true;
}
export type RemoteClientConnectionState =
@@ -37,12 +43,21 @@ export function redactPairingCredential(pairingUrl: string): string {
}
}
export function mobileAuthClientMetadata(): AuthClientPresentationMetadata {
return {
label: "T3 Code Mobile",
deviceType: "mobile",
...(Platform.OS === "ios" ? { os: "iOS" } : Platform.OS === "android" ? { os: "Android" } : {}),
};
export function isRelayManagedConnection(
connection: Pick<SavedRemoteConnection, "authenticationMethod" | "relayManaged">,
): boolean {
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
}
export function toStableSavedRemoteConnection(
connection: SavedRemoteConnection,
): SavedRemoteConnection {
if (!isRelayManagedConnection(connection) || !connection.dpopAccessToken) {
return connection;
}
const { dpopAccessToken: _, ...stableConnection } = connection;
return stableConnection;
}
export async function bootstrapRemoteConnection(
@@ -52,18 +67,20 @@ export async function bootstrapRemoteConnection(
pairingUrl: input.pairingUrl,
});
const descriptor = await mobileRemoteHttpRuntime.runPromise(
fetchRemoteEnvironmentDescriptor({
httpBaseUrl: target.httpBaseUrl,
}),
);
const bootstrap = await mobileRemoteHttpRuntime.runPromise(
bootstrapRemoteBearerSession({
httpBaseUrl: target.httpBaseUrl,
credential: target.credential,
clientMetadata: mobileAuthClientMetadata(),
}),
const { descriptor, bootstrap } = await mobileRuntime.runPromise(
Effect.all(
{
descriptor: fetchRemoteEnvironmentDescriptor({
httpBaseUrl: target.httpBaseUrl,
}),
bootstrap: bootstrapRemoteBearerSession({
httpBaseUrl: target.httpBaseUrl,
credential: target.credential,
clientMetadata: mobileAuthClientMetadata(),
}),
},
{ concurrency: "unbounded" },
),
);
return {
@@ -74,5 +91,6 @@ export async function bootstrapRemoteConnection(
httpBaseUrl: target.httpBaseUrl,
wsBaseUrl: target.wsBaseUrl,
bearerToken: bootstrap.access_token,
authenticationMethod: "bearer",
};
}
+20 -1
View File
@@ -1,5 +1,24 @@
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
export const mobileRemoteHttpRuntime = ManagedRuntime.make(remoteHttpClientLayer(fetch));
import { mobileCryptoLayer } from "../features/cloud/dpop";
import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer";
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
function configuredRelayUrl(): string {
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
}
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
export const mobileRuntime = ManagedRuntime.make(
Layer.mergeAll(
mobileHttpClientLayer,
mobileCryptoLayer,
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
),
),
);
+72
View File
@@ -0,0 +1,72 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => {
const values = new Map<string, string>();
return {
clear: () => values.clear(),
getItemAsync: vi.fn((key: string) => Promise.resolve(values.get(key) ?? null)),
setItemAsync: vi.fn((key: string, value: string) => {
values.set(key, value);
return Promise.resolve();
}),
};
});
vi.mock("expo-secure-store", () => ({
getItemAsync: mocks.getItemAsync,
setItemAsync: mocks.setItemAsync,
}));
vi.mock("react-native", () => ({
Platform: {
OS: "ios",
},
}));
vi.mock("./runtime", () => ({
mobileRuntime: {
runPromise: vi.fn(),
},
}));
import { loadSavedConnections, saveConnection } from "./storage";
import { toStableSavedRemoteConnection } from "./connection";
const managedConnection = {
environmentId: EnvironmentId.make("environment-1"),
environmentLabel: "Desktop",
pairingUrl: "https://desktop.example/",
displayUrl: "https://desktop.example/",
httpBaseUrl: "https://desktop.example/",
wsBaseUrl: "wss://desktop.example/",
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: "short-lived-token",
relayManaged: true,
} as const;
describe("mobile connection storage", () => {
beforeEach(() => {
mocks.clear();
vi.clearAllMocks();
});
it("persists relay-managed connections without their ephemeral access token", async () => {
await saveConnection(managedConnection);
const savedValue = mocks.setItemAsync.mock.calls[0]?.[1];
expect(savedValue).toBeDefined();
expect(JSON.parse(savedValue ?? "")).toEqual({
connections: [toStableSavedRemoteConnection(managedConnection)],
});
});
it("loads relay-managed connection metadata without a cached access token", async () => {
await saveConnection(managedConnection);
await expect(loadSavedConnections()).resolves.toEqual([
toStableSavedRemoteConnection(managedConnection),
]);
});
});
+42 -6
View File
@@ -5,10 +5,15 @@ import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "./connection";
import {
isRelayManagedConnection,
type SavedRemoteConnection,
toStableSavedRemoteConnection,
} from "./connection";
const CONNECTIONS_KEY = "t3code.connections";
const PREFERENCES_KEY = "t3code.preferences";
const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
@@ -20,6 +25,7 @@ export interface CachedShellSnapshot {
}
export interface MobilePreferences {
readonly liveActivitiesEnabled?: boolean;
readonly terminalFontSize?: number;
}
@@ -133,18 +139,23 @@ export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteC
return pipe(
parsed.connections ?? [],
Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()),
Arr.filter(
(c) => !!c.environmentId && (!!c.bearerToken?.trim() || isRelayManagedConnection(c)),
),
);
}
export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
const current = await loadSavedConnections();
const stableConnection = toStableSavedRemoteConnection(connection);
const next = current.some((entry) => entry.environmentId === connection.environmentId)
? pipe(
current,
Arr.map((entry) => (entry.environmentId === connection.environmentId ? connection : entry)),
Arr.map((entry) =>
entry.environmentId === connection.environmentId ? stableConnection : entry,
),
)
: pipe(current, Arr.append(connection));
: pipe(current, Arr.append(stableConnection));
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
}
@@ -164,11 +175,19 @@ export async function loadPreferences(): Promise<MobilePreferences> {
return {};
}
const preferences: {
liveActivitiesEnabled?: boolean;
terminalFontSize?: number;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
}
if (typeof parsed.terminalFontSize === "number") {
return { terminalFontSize: parsed.terminalFontSize };
preferences.terminalFontSize = parsed.terminalFontSize;
}
return {};
return preferences;
}
export async function savePreferencesPatch(
@@ -182,3 +201,20 @@ export async function savePreferencesPatch(
await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next));
return next;
}
export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
if (existing?.trim()) {
return existing;
}
const { uuidv4 } = await import("./uuid");
const deviceId = uuidv4();
await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
return deviceId;
}
export async function loadAgentAwarenessDeviceId(): Promise<string | null> {
const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
return existing?.trim() ? existing : null;
}
@@ -11,6 +11,7 @@ export interface ConnectedEnvironmentSummary {
readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
readonly displayUrl: string;
readonly isRelayManaged: boolean;
readonly connectionState: EnvironmentConnectionState;
readonly connectionError: string | null;
}
@@ -0,0 +1,243 @@
import { useAtomValue } from "@effect/atom-react";
import { useEffect } from "react";
import { Atom } from "effect/unstable/reactivity";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { appAtomRegistry } from "./atom-registry";
const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
const COMPOSER_DRAFTS_FILE = "drafts.json";
const PERSIST_DEBOUNCE_MS = 200;
export interface ComposerDraft {
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
}
interface PersistedComposerDrafts {
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
readonly drafts: Record<string, ComposerDraft>;
}
const EMPTY_DRAFT: ComposerDraft = {
text: "",
attachments: [],
};
export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:composer-drafts"),
);
let loadStarted = false;
let persistTimer: ReturnType<typeof setTimeout> | null = null;
function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
if (!draft) {
return EMPTY_DRAFT;
}
return {
text: draft.text,
attachments: draft.attachments,
};
}
function isEmptyDraft(draft: ComposerDraft): boolean {
return draft.text.length === 0 && draft.attachments.length === 0;
}
async function getComposerDraftsFile() {
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, COMPOSER_DRAFTS_DIRECTORY);
directory.create({ idempotent: true, intermediates: true });
return new File(directory, COMPOSER_DRAFTS_FILE);
}
async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDraft>> {
try {
const file = await getComposerDraftsFile();
if (!file.exists) {
return {};
}
const parsed = JSON.parse(await file.text()) as Partial<PersistedComposerDrafts>;
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
return {};
}
return Object.fromEntries(
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
const draft = entry[1];
return (
typeof draft?.text === "string" &&
Array.isArray(draft.attachments) &&
!isEmptyDraft(draft)
);
}),
);
} catch {
return {};
}
}
async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
try {
const file = await getComposerDraftsFile();
const nonEmptyDrafts = Object.fromEntries(
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
const document: PersistedComposerDrafts = {
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
drafts: nonEmptyDrafts,
};
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(document));
} catch {
// Draft persistence is best-effort; in-memory drafts still keep working.
}
}
function schedulePersistComposerDrafts(drafts: Record<string, ComposerDraft>): void {
if (persistTimer !== null) {
clearTimeout(persistTimer);
}
persistTimer = setTimeout(() => {
persistTimer = null;
void savePersistedComposerDrafts(drafts);
}, PERSIST_DEBOUNCE_MS);
}
export function ensureComposerDraftsLoaded(): void {
if (loadStarted) {
return;
}
loadStarted = true;
void loadPersistedComposerDrafts().then((persistedDrafts) => {
if (Object.keys(persistedDrafts).length === 0) {
return;
}
const current = appAtomRegistry.get(composerDraftsAtom);
appAtomRegistry.set(composerDraftsAtom, {
...persistedDrafts,
...current,
});
});
}
function updateComposerDrafts(
update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
): void {
const next = update(appAtomRegistry.get(composerDraftsAtom));
appAtomRegistry.set(composerDraftsAtom, next);
schedulePersistComposerDrafts(next);
}
export function setComposerDraftText(draftKey: string, value: string): void {
updateComposerDrafts((current) => {
const draft = {
...normalizeDraft(current[draftKey]),
text: value,
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
});
}
export function appendComposerDraftText(draftKey: string, value: string): void {
updateComposerDrafts((current) => {
const existing = normalizeDraft(current[draftKey]);
return {
...current,
[draftKey]: {
...existing,
text: `${existing.text}${value}`,
},
};
});
}
export function appendComposerDraftAttachments(
draftKey: string,
attachments: ReadonlyArray<DraftComposerImageAttachment>,
): void {
if (attachments.length === 0) {
return;
}
updateComposerDrafts((current) => {
const existing = normalizeDraft(current[draftKey]);
return {
...current,
[draftKey]: {
...existing,
attachments: [...existing.attachments, ...attachments],
},
};
});
}
export function replaceComposerDraftAttachments(
draftKey: string,
attachments: ReadonlyArray<DraftComposerImageAttachment>,
): void {
updateComposerDrafts((current) => {
const draft = {
...normalizeDraft(current[draftKey]),
attachments,
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
});
}
export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
updateComposerDrafts((current) => {
const existing = normalizeDraft(current[draftKey]);
const draft = {
...existing,
attachments: existing.attachments.filter((image) => image.id !== imageId),
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
});
}
export function clearComposerDraft(draftKey: string): void {
updateComposerDrafts((current) => {
if (!current[draftKey]) {
return current;
}
const next = { ...current };
delete next[draftKey];
return next;
});
}
export function useComposerDraft(draftKey: string | null): ComposerDraft {
const drafts = useAtomValue(composerDraftsAtom);
useEffect(() => {
ensureComposerDraftsLoaded();
}, []);
return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;
}
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more