Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 48c43ca5f2 Fix sidebar pill hook import
Co-authored-by: Julius Marminge <[email protected]>
2026-07-09 16:18:00 +00:00
Cursor AgentandJulius Marminge f9f8ecfd38 Remove sidebar pill timestamp effect
Co-authored-by: Julius Marminge <[email protected]>
2026-07-09 16:16:29 +00:00
Cursor AgentandJulius Marminge 3abec1aee7 Optimize sidebar provider update pill renders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-09 16:14:44 +00:00
Julius Marmingeandcodex f61fa9499d Expose mobile PR indicator labels to accessibility (#3828)
Co-authored-by: codex <[email protected]>
2026-07-09 14:00:51 +00:00
Julius Marmingeandcodex 8619ef22e9 Show compact PR number badges in mobile thread rows (#3827)
Co-authored-by: codex <[email protected]>
2026-07-09 15:29:55 +02:00
Julius Marmingeandcodex 843cf176ea fix(mobile): embed fonts and render project favicons reliably (#3823)
Co-authored-by: codex <[email protected]>
2026-07-09 13:49:16 +02:00
Julius Marmingeandcodex ca1e08b5a0 [codex] Label max and ultra reasoning (#3824)
Co-authored-by: codex <[email protected]>
2026-07-09 10:20:32 +00:00
2250e3ee7a feat(client): persist offline environment data and mobile preferences (#3795)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-09 11:23:51 +02:00
Julius Marmingeandcodex 3201e00ad4 [codex] Preserve worktree metadata during branch sync (#3822)
Co-authored-by: codex <[email protected]>
2026-07-09 09:01:23 +02:00
Julius Marmingeandcodex e9127658a6 [codex] Upgrade Clerk stack (#3821)
Co-authored-by: codex <[email protected]>
2026-07-09 07:54:28 +02:00
Patricio Gómez Meneses 18a41388eb Fix desktop native optional dependency packaging (#3816) 2026-07-09 03:55:33 +00:00
Rowan 0c66565854 fix(release): bump electron-builder so pnpm 11 deduped deps land in the asar (#3790) 2026-07-08 04:38:45 -07:00
Julius Marminge e775bc6228 Upgrade Clerk toolchain to latest versions (#3785) 2026-07-08 04:30:07 -07:00
Julius MarmingeandCursor Agent 03ac1f0cd9 fix(release): stage pnpm 11 allowBuilds for desktop installs (#3781)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 15:55:18 -07:00
Julius MarmingeandCursor Agent 7778a1cea7 Use rounded depth logo for production splash screen (#3780)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 22:49:50 +00:00
Julius MarmingeandClaude Fable 5 dad0889766 Revert "Revert "Add T3 Connect onboarding for mobile and web"" (#3777)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 14:17:18 -07:00
b9cc8d6ef1 Set up Cursor Cloud dev environment (web + Android toolchain) (#3755)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-07-07 13:18:58 -07:00
Julius MarmingeandClaude Fable 5 0e0040832c Expose Clerk Google sign-in env vars to Expo (#3772)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 12:45:40 -07:00
Julius Marminge cd8b9fc8b3 Revert "Add T3 Connect onboarding for mobile and web" (#3776) 2026-07-07 12:40:12 -07:00
Julius Marminge fa6073e2e1 Add T3 Connect onboarding for mobile and web (#3765) 2026-07-07 12:39:56 -07:00
Julius Marminge 4eb1b57933 Lead with the outcome when no agents are active in the Live Activity (#3768) 2026-07-07 09:12:52 -07:00
Julius Marminge 4414f922fe Clear VCS presentation state on finish (#3764) 2026-07-07 08:54:27 -07:00
Julius Marminge 6e42231cb1 Extend Done display to 15 minutes and show up to 5 Live Activity banner rows (#3761) 2026-07-07 02:00:36 -07:00
Julius Marminge bdf5aed665 Fix Expo widget asset wiring order (#3763) 2026-07-07 02:00:10 -07:00
Julius Marminge 0b62e2eb11 Use variant-specific splash icons in mobile app (#3762) 2026-07-07 01:59:13 -07:00
Julius Marminge f9727d0853 Prevent Add Project sheet from collapsing on relayout (#3759) 2026-07-07 01:58:29 -07:00
Julius MarmingeandClaude Opus 4.8 d8e0ba3ea0 Improve live activity routing and diagnostics (#3685)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-07 00:56:20 -07:00
Julius MarmingeandClaude Fable 5 32e7844837 Fix mobile legend anchor under automatic iOS insets (#3684)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-05 22:50:33 -07:00
Julius MarmingeandClaude Opus 4.8 482d56233d Load thread snapshots over HTTP before live sync (#3719)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-05 22:00:13 -07:00
Theo BrowneandClaude Fable 5 6009720844 Add repo-root favicon.svg so t3 code shows its own icon (#3683)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-04 15:05:45 -07:00
Theo BrowneandClaude Opus 4.8 e26e55f389 fix(mobile): combined test branch — scroll, back-swipe, thread lists, computer switching (#3687)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-04 14:28:51 -07:00
Julius Marminge 4ac094fef6 Surface pending tasks in mobile home and draft flow (#3670) 2026-07-03 13:32:14 -07:00
Julius Marminge a7e43b2281 Upgrade Vite Plus and enable bundled dev opt-in (#3679) 2026-07-03 11:21:47 -07:00
Julius MarmingeandClaude Fable 5 cabc93bad3 Make the thread composer read as elevated liquid glass (#3668)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-03 07:05:38 +00:00
Julius MarmingeandClaude Fable 5 5cda815626 fix(mobile): compile patched native pods from source on EAS (#3667)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-03 06:52:01 +00:00
32d17d3db5 Add adaptive split-view layout for iPad/mobile workspace (#3514)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-02 22:42:14 -07:00
Theo Browne 6d35a87c5d fix(dev): Fix electron dev launch and add test (#3662) 2026-07-02 18:57:59 -07:00
390 changed files with 34111 additions and 8515 deletions

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
---
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
alwaysApply: true
---
# Cursor Cloud specific instructions
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
## Toolchain
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
`vp check --fix` before committing.
## Running the web app
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
Without one installed the UI loads but no agent can run. Claude Code
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
server to pick up a newly installed provider CLI immediately.
## Android native builds (apps/mobile)
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
Gradle auto-downloads any additional pinned SDK packages on demand.
- Generate the native project first: from `apps/mobile`,
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
Android Studio bundles is what is installed.
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
scope for environment setup.
## Known flaky tests (unrelated to setup)
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
+4 -1
View File
@@ -57,7 +57,10 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
+113
View File
@@ -0,0 +1,113 @@
name: Mobile EAS Production
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
# Under the fingerprint runtime-version policy the fingerprint must be computed
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
on:
workflow_dispatch:
inputs:
mode:
description: "build (+ auto-submit to TestFlight) or update (OTA)"
required: true
type: choice
default: build
options:
- build
- update
platform:
description: "Target platform"
required: true
type: choice
default: ios
options:
- ios
- android
- all
message:
description: "OTA update message (mode=update only)"
required: false
type: string
jobs:
production:
name: EAS Production ${{ inputs.mode }}
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
env:
APP_VARIANT: production
NODE_OPTIONS: --max-old-space-size=8192
steps:
- id: expo-token
name: Check for EXPO_TOKEN
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
if [ -n "$EXPO_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup EAS
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull production environment variables
if: steps.expo-token.outputs.present == 'true'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Build and submit
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
- name: Publish OTA update
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
eas update \
--channel production \
--environment production \
--platform ${{ inputs.platform }} \
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
--non-interactive
@@ -43,6 +43,15 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Dependency acquisition and runtime boundaries
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
+1
View File
@@ -0,0 +1 @@
vp staged
+1 -1
View File
@@ -31,7 +31,7 @@
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"electron-builder": "26.15.6",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
+13 -6
View File
@@ -358,10 +358,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
}
export function resolveElectronPath() {
ensureElectronRuntime();
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
if (hostPlatform !== "darwin") {
return electronBinaryPath;
@@ -378,13 +375,23 @@ export function resolveElectronLaunchCommand(args = []) {
};
}
export function resolveElectronBinaryPath({
ensureRuntime = ensureElectronRuntime,
createRequire = NodeModule.createRequire,
moduleUrl = import.meta.url,
} = {}) {
ensureRuntime();
const require = createRequire(moduleUrl);
return require("electron");
}
export function resolveDevProtocolClient() {
if (hostPlatform !== "darwin" || !isDevelopment) {
return null;
}
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
@@ -1,6 +1,6 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
@@ -25,4 +25,24 @@ describe("electron development launcher", () => {
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
it("repairs Electron before loading the package entrypoint", () => {
const calls = [];
const electronPath = resolveElectronBinaryPath({
ensureRuntime: () => {
calls.push("ensure");
},
createRequire: () => (specifier) => {
calls.push(`require:${specifier}`);
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
},
moduleUrl: import.meta.url,
});
assert.equal(
electronPath,
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
);
assert.deepEqual(calls, ["ensure", "require:electron"]);
});
});
+1
View File
@@ -1,6 +1,7 @@
included:
- ios/T3Code
- modules/t3-composer-editor/ios
- modules/t3-native-controls/ios
- modules/t3-terminal/ios
- modules/t3-review-diff/ios
+78 -5
View File
@@ -15,30 +15,38 @@ const VARIANT_CONFIG: Record<
readonly appName: string;
readonly scheme: string;
readonly iosIcon: string;
readonly splashIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
readonly relyingParty?: string;
}
> = {
development: {
appName: "T3 Code Dev",
scheme: "t3code-dev",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
relyingParty: "clerk.t3.codes",
},
preview: {
appName: "T3 Code Preview",
scheme: "t3code-preview",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
},
production: {
appName: "T3 Code",
scheme: "t3code",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
relyingParty: "clerk.t3.codes",
},
};
@@ -55,6 +63,16 @@ function resolveAppVariant(value: string | undefined): AppVariant {
const variant = VARIANT_CONFIG[APP_VARIANT];
const dmSansFonts = {
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
medium: "@expo-google-fonts/dm-sans/500Medium/DMSans_500Medium.ttf",
bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf",
} as const;
// These aliases match the fonts' PostScript names on iOS. Register the same
// names on Android so React Native and the native composer use one set of
// family names without waiting for runtime font loading.
const config: ExpoConfig = {
name: variant.appName,
slug: "t3-code",
@@ -62,7 +80,11 @@ const config: ExpoConfig = {
scheme: variant.scheme,
version: "0.1.0",
runtimeVersion: {
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
// With appVersion, every 0.1.0 build shares a runtime version, so a JS update
// could land on a binary missing the native changes it needs and crash.
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
},
orientation: "portrait",
icon: "./assets/icon.png",
@@ -77,6 +99,14 @@ const config: ExpoConfig = {
icon: variant.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
// Sign in with Apple, or push notification entitlements).
appleTeamId: "ARK85ZXQ4Z",
associatedDomains: [
`applinks:${variant.relyingParty}`,
`webcredentials:${variant.relyingParty}`,
],
infoPlist: {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
@@ -101,9 +131,32 @@ const config: ExpoConfig = {
favicon: "./assets/favicon.png",
},
plugins: [
"expo-router",
"expo-font",
[
"expo-font",
{
ios: {
fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold],
},
android: {
fonts: [
{
fontFamily: "DMSans-Regular",
fontDefinitions: [{ path: dmSansFonts.regular, weight: 400 }],
},
{
fontFamily: "DMSans-Medium",
fontDefinitions: [{ path: dmSansFonts.medium, weight: 500 }],
},
{
fontFamily: "DMSans-Bold",
fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }],
},
],
},
},
],
"expo-secure-store",
"expo-sqlite",
["@clerk/expo", { theme: "./clerk-theme.json" }],
"expo-web-browser",
[
@@ -116,12 +169,12 @@ const config: ExpoConfig = {
[
"expo-splash-screen",
{
image: "./assets/splash-icon.png",
image: variant.splashIcon,
resizeMode: "contain",
backgroundColor: "#ffffff",
imageWidth: 220,
dark: {
image: "./assets/splash-icon.png",
image: variant.splashIcon,
backgroundColor: "#0a0a0a",
},
},
@@ -139,12 +192,22 @@ const config: ExpoConfig = {
},
},
],
"./plugins/withIosCocoaPodsUuidCache.cjs",
// Must be listed BEFORE expo-widgets: same-type mods run last-registered-
// first, so registering earlier makes this plugin's mods run AFTER
// expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
// would delete the asset catalog) and its xcodeproj mod creates the widget
// target (which must exist before the compile phase can be attached).
"./plugins/withWidgetLogoAsset.cjs",
[
"expo-widgets",
{
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
enablePushNotifications: true,
// Agent activity can update many times an hour; without the
// frequent-updates entitlement iOS throttles the update budget sooner.
frequentUpdates: true,
widgets: [
{
name: "AgentActivity",
@@ -155,6 +218,7 @@ const config: ExpoConfig = {
],
},
],
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
],
extra: {
@@ -166,6 +230,15 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
// Native Google sign-in credentials. @clerk/expo reads these from `extra`
// under their exact env-var names (not nested), and its config plugin reads
// the iOS URL scheme at prebuild to register it in Info.plist.
// Unset values must be omitted (not null): the public manifest serializes
// null to {}, which is truthy and would defeat Clerk's fallback checks.
EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.0 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

+3
View File
@@ -0,0 +1,3 @@
<svg width="111" height="74" viewBox="7 29 111 74" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 887 B

+16 -5
View File
@@ -6,25 +6,31 @@
},
"build": {
"development": {
"corepack": true,
"env": {
"APP_VARIANT": "development"
"APP_VARIANT": "development",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "development",
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"corepack": true,
"env": {
"APP_VARIANT": "preview"
"APP_VARIANT": "preview",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "preview",
"environment": "preview",
"distribution": "internal"
},
"preview:dev": {
"corepack": true,
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint"
"MOBILE_VERSION_POLICY": "fingerprint",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "preview",
"environment": "preview",
@@ -35,8 +41,10 @@
}
},
"production": {
"corepack": true,
"env": {
"APP_VARIANT": "production"
"APP_VARIANT": "production",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "production",
"environment": "production",
@@ -46,7 +54,10 @@
"submit": {
"production": {
"ios": {
"ascAppId": "6761315631"
"ascAppId": "6787819824"
},
"android": {
"track": "internal"
}
}
}
+27 -24
View File
@@ -51,6 +51,7 @@
/* Inputs */
--color-input: #ffffff;
--color-input-border: rgba(0, 0, 0, 0.1);
--color-sidebar-search: rgba(118, 118, 128, 0.12);
--color-placeholder: #a3a3a3;
/* Icons */
@@ -144,6 +145,7 @@
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-sidebar-search: rgba(118, 118, 128, 0.24);
--color-placeholder: #8e8e93;
/* Icons */
@@ -194,41 +196,42 @@
/* ─── Typography ────────────────────────────────────────────────────── */
@theme {
--font-sans: "DMSans_400Regular";
--font-medium: "DMSans_500Medium";
--font-bold: "DMSans_700Bold";
/* Keep these native family names aligned with app.config.ts. */
--font-sans: "DMSans-Regular";
--font-medium: "DMSans-Medium";
--font-bold: "DMSans-Bold";
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
--text-3xs: 10px;
--text-3xs--line-height: 13px;
--text-2xs: 11px;
--text-2xs--line-height: 15px;
--text-xs: 12px;
--text-xs--line-height: 16px;
--text-sm: 13px;
--text-sm--line-height: 18px;
--text-base: 15px;
--text-base--line-height: 22px;
--text-lg: 17px;
--text-lg--line-height: 22px;
--text-xl: 20px;
--text-xl--line-height: 26px;
--text-2xl: 24px;
--text-2xl--line-height: 30px;
--text-3xl: 28px;
--text-3xl--line-height: 34px;
--text-3xs: 11px;
--text-3xs--line-height: 14px;
--text-2xs: 12px;
--text-2xs--line-height: 16px;
--text-xs: 13px;
--text-xs--line-height: 17px;
--text-sm: 14px;
--text-sm--line-height: 19px;
--text-base: 16px;
--text-base--line-height: 23px;
--text-lg: 18px;
--text-lg--line-height: 23px;
--text-xl: 21px;
--text-xl--line-height: 28px;
--text-2xl: 26px;
--text-2xl--line-height: 32px;
--text-3xl: 30px;
--text-3xl--line-height: 36px;
}
/* ─── Custom utilities ──────────────────────────────────────────────── */
@utility font-t3-medium {
font-family: "DMSans_500Medium";
font-family: var(--font-medium);
}
@utility font-t3-bold {
font-family: "DMSans_700Bold";
font-family: var(--font-bold);
}
@utility font-t3-extrabold {
font-family: "DMSans_700Bold";
font-family: var(--font-bold);
font-weight: 800;
}
+10 -1
View File
@@ -1,2 +1,11 @@
import { registerRootComponent } from "expo";
import "react-native-gesture-handler";
import "expo-router/entry";
import { featureFlags } from "react-native-screens";
import App from "./src/App";
// Required for react-native-screens' iOS FormSheet sizing fix when a nested
// native stack is rendered inside a non-fitToContents formSheet.
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
registerRootComponent(App);
@@ -47,6 +47,7 @@ public class T3ComposerEditorModule: Module {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange"
)
@@ -63,6 +63,24 @@ private final class ComposerTextView: UITextView {
var onPasteImages: (([String]) -> Void)?
var onAttributedMutation: (() -> Void)?
var onSubmit: (() -> Void)?
override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
let submit = UIKeyCommand(
input: "\r",
modifierFlags: .command,
action: #selector(submitMessage(_:))
)
submit.discoverabilityTitle = "Send Message"
submit.wantsPriorityOverSystemBehavior = true
commands.append(submit)
return commands
}
@objc private func submitMessage(_ sender: UIKeyCommand) {
onSubmit?()
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(paste(_:)) {
@@ -282,7 +300,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
skillText: "#a21caf",
fileTint: "#737373"
)
private var fontFamily = "DMSans_400Regular"
private var fontFamily = "DMSans-Regular"
private var fontSize: CGFloat = 14
private var lineHeight: CGFloat = 20
private var contentInsetVertical: CGFloat = 0
@@ -299,6 +317,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
let onComposerSelectionChange = EventDispatcher()
let onComposerFocus = EventDispatcher()
let onComposerBlur = EventDispatcher()
let onComposerSubmit = EventDispatcher()
let onComposerPasteImages = EventDispatcher()
let onComposerContentSizeChange = EventDispatcher()
@@ -320,6 +339,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
textView.onAttributedMutation = { [weak self] in
self?.emitTextChange()
}
textView.onSubmit = { [weak self] in
self?.onComposerSubmit([:])
}
addSubview(textView)
placeholderLabel.numberOfLines = 0
@@ -586,7 +608,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
iconImage: UIImage?,
style: ComposerChipStyle
) -> UIImage {
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
let font = UIFont(name: "DMSans-Medium", size: max(12, fontSize - 2))
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
let fallbackIcon = UIImage(
systemName: iconName,
@@ -26,6 +26,15 @@ function nodeKey(node: MarkdownNode, index: number): string {
return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
}
/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
return Math.max(10, Math.round(textStyle.fontSize * 0.8));
}
function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
return codeBlockFontSize(textStyle) + 6;
}
function nodeText(node: MarkdownNode): string {
if (node.content !== undefined) {
return node.content;
@@ -161,8 +170,8 @@ function HighlightedCodeText(props: {
style={{
color: props.textStyle.codeColor,
fontFamily: "ui-monospace",
fontSize: 12,
lineHeight: 18,
fontSize: codeBlockFontSize(props.textStyle),
lineHeight: codeBlockLineHeight(props.textStyle),
}}
>
{props.content}
@@ -196,8 +205,8 @@ function HighlightedCodeText(props: {
style={{
color: props.textStyle.codeColor,
fontFamily: "ui-monospace",
fontSize: 12,
lineHeight: 18,
fontSize: codeBlockFontSize(props.textStyle),
lineHeight: codeBlockLineHeight(props.textStyle),
}}
>
{keyedLines.map((line, lineIndex) => (
@@ -264,7 +273,7 @@ function NativeCodeBlock(props: {
flex: 1,
color: props.textStyle.mutedColor,
fontFamily: "ui-monospace",
fontSize: 12,
fontSize: codeBlockFontSize(props.textStyle),
}}
>
{languageLabel}
@@ -32,11 +32,25 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
].join(":");
}
const DEFAULT_BODY_FONT_SIZE = 15;
const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
const index = Math.max(0, Math.min(5, headingLevel - 1));
const configured = textStyle.headingFontSizes?.[index];
if (typeof configured === "number" && Number.isFinite(configured)) {
return configured;
}
const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
}
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
const isFile = run.fileIcon != null;
const isSkill = run.skillName != null;
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
const isHeading = run.role === "heading";
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
const hasParagraphStyle = run.headIndent !== undefined;
@@ -88,7 +102,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
: isHeading
? headingFontSize
: run.role === "code-language"
? 11
? Math.max(10, Math.round(textStyle.fontSize * 0.73))
: run.code || isCodeBlock
? Math.max(12, textStyle.fontSize - 2)
: textStyle.fontSize,
@@ -98,9 +112,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
: run.role === "list-break"
? textStyle.lineHeight + (run.spacing ?? 0)
: isHeading
? Math.max(headingFontSize + 6, 20)
? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
: isCodeBlock
? 18
? Math.max(16, textStyle.lineHeight - 2)
: textStyle.lineHeight,
fontStyle: run.italic ? "italic" : "normal",
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
@@ -148,6 +162,9 @@ export function NativeMarkdownSelectableText(props: {
// color-only child update can otherwise leave the previous appearance cached.
const appearanceKey = [
colorScheme ?? "unspecified",
props.textStyle.fontSize,
props.textStyle.lineHeight,
props.textStyle.headingFontSizes?.join(","),
props.textStyle.color,
props.textStyle.strongColor,
props.textStyle.mutedColor,
@@ -16,6 +16,7 @@ export interface NativeMarkdownTextStyle {
readonly fontFamily: string;
readonly headingFontFamily: string;
readonly boldFontFamily: string;
readonly headingFontSizes?: ReadonlyArray<number>;
}
export interface MarkdownHighlightedToken {
@@ -0,0 +1,6 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
}
}
@@ -0,0 +1,62 @@
import ExpoModulesCore
import UIKit
public final class T3HeaderButtonView: ExpoView {
private static let size: CGFloat = 44
private static let symbolSize: CGFloat = 18
private let button = UIButton(type: .system)
private var systemImage = "circle"
let onTriggered = EventDispatcher()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
isAccessibilityElement = false
button.frame = bounds
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
addSubview(button)
applyConfiguration()
}
public override var intrinsicContentSize: CGSize {
CGSize(width: Self.size, height: Self.size)
}
public func setLabel(_ label: String) {
button.accessibilityLabel = label
}
public func setSystemImage(_ systemImage: String) {
guard self.systemImage != systemImage else {
return
}
self.systemImage = systemImage
applyConfiguration()
}
private func applyConfiguration() {
var configuration: UIButton.Configuration
if #available(iOS 26.0, *) {
configuration = .glass()
configuration.cornerStyle = .capsule
} else {
configuration = .plain()
}
configuration.baseForegroundColor = .label
configuration.contentInsets = .zero
configuration.image = UIImage(systemName: systemImage)
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
pointSize: Self.symbolSize,
weight: .regular
)
button.configuration = configuration
}
@objc private func handlePress() {
onTriggered()
}
}
@@ -0,0 +1,131 @@
import ExpoModulesCore
import UIKit
public final class T3KeyboardCommandsModule: Module {
public func definition() -> ModuleDefinition {
Name("T3KeyboardCommands")
View(T3KeyboardCommandsView.self) {
Prop("enabledCommands") { (view: T3KeyboardCommandsView, commands: [String]) in
view.setEnabledCommands(commands)
}
Events("onCommand")
}
}
}
public final class T3KeyboardCommandsView: ExpoView {
let onCommand = EventDispatcher()
private var enabledCommands = Set<String>()
public override var canBecomeFirstResponder: Bool { true }
public override var keyCommands: [UIKeyCommand]? {
[
enabledCommand("newTask", input: "n", modifiers: .command, action: #selector(newTask), title: "New Task"),
enabledCommand("focusSearch", input: "f", modifiers: .command, action: #selector(focusSearch), title: "Find"),
enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"),
enabledCommand("back", input: "[", modifiers: .command, action: #selector(goBack), title: "Back"),
enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"),
enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"),
enabledCommand("review", input: "r", modifiers: [.command, .shift], action: #selector(openReview), title: "Open Review"),
enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"),
].compactMap { $0 }
}
func setEnabledCommands(_ commands: [String]) {
enabledCommands = Set(commands)
if isFirstResponder {
resignFirstResponder()
}
reclaimFirstResponderIfAvailable()
}
private func enabledCommand(
_ identifier: String,
input: String,
modifiers: UIKeyModifierFlags,
action: Selector,
title: String
) -> UIKeyCommand? {
guard enabledCommands.contains(identifier) else { return nil }
return command(input, modifiers: modifiers, action: action, title: title)
}
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UITextView.textDidEndEditingNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UITextField.textDidEndEditingNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public override func didMoveToWindow() {
super.didMoveToWindow()
reclaimFirstResponderIfAvailable()
}
public override func layoutSubviews() {
super.layoutSubviews()
reclaimFirstResponderIfAvailable()
}
private func command(
_ input: String,
modifiers: UIKeyModifierFlags,
action: Selector,
title: String
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
command.discoverabilityTitle = title
command.wantsPriorityOverSystemBehavior = true
return command
}
@objc private func newTask() { emit("newTask") }
@objc private func focusSearch() { emit("focusSearch") }
@objc private func goBack() { emit("back") }
@objc private func openFiles() { emit("files") }
@objc private func openTerminal() { emit("terminal") }
@objc private func openReview() { emit("review") }
@objc private func handleToggleSidebar() { emit("toggleSidebar") }
private func emit(_ command: String) {
onCommand(["command": command])
}
@objc private func reclaimFirstResponderIfAvailable() {
DispatchQueue.main.async { [weak self] in
guard let self, self.window?.t3FirstResponder == nil else { return }
self.becomeFirstResponder()
}
}
}
private extension UIView {
var t3FirstResponder: UIResponder? {
if isFirstResponder { return self }
for subview in subviews {
if let responder = subview.t3FirstResponder { return responder }
}
return nil
}
}
@@ -0,0 +1,19 @@
Pod::Spec.new do |s|
s.name = 'T3NativeControls'
s.version = '1.0.0'
s.summary = 'Native UIKit controls for T3 Code mobile.'
s.description = 'UIKit-backed controls that match native iOS navigation chrome.'
s.author = 'T3 Tools'
s.homepage = 'https://t3tools.com'
s.platforms = {
:ios => '18.0',
}
s.source = { :path => '.' }
s.static_framework = true
s.dependency 'ExpoModulesCore'
s.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES',
}
s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
end
@@ -0,0 +1,18 @@
import ExpoModulesCore
public final class T3NativeControlsModule: Module {
public func definition() -> ModuleDefinition {
Name("T3NativeControls")
View(T3HeaderButtonView.self) {
Prop("label") { (view: T3HeaderButtonView, label: String) in
view.setLabel(label)
}
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
view.setSystemImage(systemImage)
}
Events("onTriggered")
}
}
}
@@ -5,22 +5,14 @@ public class T3ReviewDiffModule: Module {
Name("T3ReviewDiffSurface")
View(T3ReviewDiffView.self) {
Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
view.setRowsJson(rowsJson)
}
Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
view.setTokensPatchJson(tokensPatchJson)
}
Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
view.setTokensResetKey(tokensResetKey)
}
Prop("contentResetKey") { (view: T3ReviewDiffView, contentResetKey: String) in
view.setContentResetKey(contentResetKey)
}
Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
}
@@ -61,7 +53,42 @@ public class T3ReviewDiffModule: Module {
view.setInitialRowIndex(initialRowIndex)
}
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
Prop("refreshing") { (view: T3ReviewDiffView, refreshing: Bool) in
view.setRefreshing(refreshing)
}
Events(
"onDebug",
"onVisibleFileChange",
"onToggleFile",
"onToggleViewedFile",
"onPressLine",
"onToggleComment",
"onPullToRefresh"
)
AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in
view.scrollToFile(fileId, animated: animated)
}
AsyncFunction("scrollToTop") { (view: T3ReviewDiffView, animated: Bool) in
view.scrollToTop(animated: animated)
}
// Large, frequently changing JSON values cannot be regular Fabric props. Expo's
// prop adapter compares strings on the main thread before invoking a setter, which
// makes a syntax-token patch capable of blocking a frame by itself.
AsyncFunction("setRowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
view.setRowsJson(rowsJson)
}
AsyncFunction("setTokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
view.setTokensPatchJson(tokensPatchJson)
}
}
}
}
@@ -1,7 +1,7 @@
import ExpoModulesCore
import UIKit
private struct ReviewDiffNativeRow: Decodable {
private struct ReviewDiffNativeRow: Decodable, Sendable {
let kind: String
let id: String
let fileId: String?
@@ -21,18 +21,18 @@ private struct ReviewDiffNativeRow: Decodable {
let commentSectionTitle: String?
}
private struct ReviewDiffNativeWordDiffRange: Decodable {
private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
let start: Int
let end: Int
}
private struct ReviewDiffNativeToken: Decodable {
private struct ReviewDiffNativeToken: Decodable, Sendable {
let content: String
let color: String?
let fontStyle: Int?
}
private struct ReviewDiffNativeTokenPatch: Decodable {
private struct ReviewDiffNativeTokenPatch: Decodable, Sendable {
let resetKey: String?
let chunkIndex: Int?
let tokensByRowId: [String: [ReviewDiffNativeToken]]?
@@ -312,6 +312,10 @@ private struct ReviewDiffNativeStyle {
}
public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private let payloadDecodeQueue = DispatchQueue(
label: "com.t3tools.review-diff.payload-decode",
qos: .userInitiated
)
private let scrollView = UIScrollView()
private let contentView = ReviewDiffContentView()
private var rows: [ReviewDiffNativeRow] = []
@@ -323,14 +327,25 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private var lastMetricsDebugKey = ""
private var lastVisibleRangeDebugKey = ""
private var tokensResetKey = ""
private var contentResetKey = ""
private var initialRowIndex: Int?
private var hasAppliedInitialRowIndex = false
private var lastVisibleFileId: String?
private var pendingScrollFileId: String?
private var pendingScrollAnimated = false
private var isProgrammaticScrollActive = false
private var rowsDecodeGeneration = 0
private var tokensDecodeGeneration = 0
let onDebug = EventDispatcher()
let onVisibleFileChange = EventDispatcher()
let onToggleFile = EventDispatcher()
let onToggleViewedFile = EventDispatcher()
let onPressLine = EventDispatcher()
let onToggleComment = EventDispatcher()
let onPullToRefresh = EventDispatcher()
private let pullRefreshControl = UIRefreshControl()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
@@ -345,6 +360,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
scrollView.showsVerticalScrollIndicator = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.backgroundColor = contentView.theme.background
pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
scrollView.refreshControl = pullRefreshControl
addSubview(scrollView)
contentView.backgroundColor = contentView.theme.background
@@ -379,6 +396,13 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
updateViewportFrame()
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// A direct gesture takes ownership from any interrupted programmatic jump.
// Resume visible-file events immediately so the inspector follows the finger.
isProgrammaticScrollActive = false
contentView.isVerticalScrollActive = true
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard !decelerate else {
return
@@ -396,77 +420,125 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
}
func setRowsJson(_ rowsJson: String) {
guard let data = rowsJson.data(using: .utf8) else {
return
}
rowsDecodeGeneration += 1
let generation = rowsDecodeGeneration
do {
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
contentView.rows = rows
hasAppliedInitialRowIndex = false
emitDebug("rows-decoded", [
"rows": rows.count,
"firstKind": rows.first?.kind ?? "none",
])
updateContentMetrics()
} catch {
rows = []
contentView.rows = []
hasAppliedInitialRowIndex = false
updateContentMetrics()
emitDebug("rows-decode-failed", [
"error": error.localizedDescription,
])
payloadDecodeQueue.async { [weak self] in
guard let data = rowsJson.data(using: .utf8) else {
return
}
do {
let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.rowsDecodeGeneration else {
return
}
self.rows = decodedRows
self.contentView.rows = decodedRows
self.hasAppliedInitialRowIndex = false
self.lastVisibleFileId = nil
self.emitDebug("rows-decoded", [
"rows": decodedRows.count,
"firstKind": decodedRows.first?.kind ?? "none",
])
self.updateContentMetrics()
self.applyPendingScrollIfNeeded()
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.rowsDecodeGeneration else {
return
}
self.rows = []
self.contentView.rows = []
self.hasAppliedInitialRowIndex = false
self.lastVisibleFileId = nil
self.pendingScrollFileId = nil
self.updateContentMetrics()
self.emitDebug("rows-decode-failed", ["error": message])
}
}
}
}
func setTokensJson(_ tokensJson: String) {
guard let data = tokensJson.data(using: .utf8) else {
return
}
tokensDecodeGeneration += 1
let generation = tokensDecodeGeneration
do {
contentView.tokensByRowId = try JSONDecoder().decode(
[String: [ReviewDiffNativeToken]].self,
from: data
)
} catch {
contentView.tokensByRowId = [:]
emitDebug("tokens-decode-failed", [
"error": error.localizedDescription,
])
payloadDecodeQueue.async { [weak self] in
guard let data = tokensJson.data(using: .utf8) else {
return
}
do {
let decodedTokens = try JSONDecoder().decode(
[String: [ReviewDiffNativeToken]].self,
from: data
)
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.tokensDecodeGeneration else {
return
}
self.contentView.tokensByRowId = decodedTokens
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.tokensDecodeGeneration else {
return
}
self.contentView.tokensByRowId = [:]
self.emitDebug("tokens-decode-failed", ["error": message])
}
}
}
}
func setTokensPatchJson(_ tokensPatchJson: String) {
guard let data = tokensPatchJson.data(using: .utf8) else {
return
}
let contentResetKey = self.contentResetKey
do {
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
if let resetKey = patch.resetKey, resetKey != tokensResetKey {
tokensResetKey = resetKey
contentView.tokensByRowId = [:]
}
let tokensByRowId = patch.tokensByRowId ?? [:]
if tokensByRowId.isEmpty {
payloadDecodeQueue.async { [weak self] in
guard let data = tokensPatchJson.data(using: .utf8) else {
return
}
contentView.mergeTokensByRowId(tokensByRowId)
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
emitDebug("tokens-patch-decoded", [
"chunkIndex": chunkIndex,
"rows": tokensByRowId.count,
"totalRows": contentView.tokensByRowId.count,
])
do {
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
DispatchQueue.main.async { [weak self] in
guard let self else {
return
}
guard contentResetKey == self.contentResetKey else {
return
}
// A highlighter request from the previous file can finish after the view has
// already reset. Never let that stale patch roll the native token state back.
if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {
return
}
let tokensByRowId = patch.tokensByRowId ?? [:]
if tokensByRowId.isEmpty {
return
}
self.contentView.mergeTokensByRowId(tokensByRowId)
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
self.emitDebug("tokens-patch-decoded", [
"chunkIndex": chunkIndex,
"rows": tokensByRowId.count,
"totalRows": self.contentView.tokensByRowId.count,
])
}
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
self?.emitDebug("tokens-patch-decode-failed", ["error": message])
}
}
} catch {
emitDebug("tokens-patch-decode-failed", [
"error": error.localizedDescription,
])
}
}
@@ -482,6 +554,27 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
])
}
func setContentResetKey(_ contentResetKey: String) {
guard contentResetKey != self.contentResetKey else {
return
}
self.contentResetKey = contentResetKey
rowsDecodeGeneration += 1
tokensDecodeGeneration += 1
contentView.tokensByRowId = [:]
rows = []
contentView.rows = []
hasAppliedInitialRowIndex = false
pendingScrollFileId = nil
isProgrammaticScrollActive = false
scrollView.setContentOffset(.zero, animated: false)
updateContentMetrics()
updateViewportFrame()
lastVisibleFileId = nil
applyInitialRowIndexIfNeeded()
}
func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) {
let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson)
let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds)
@@ -573,6 +666,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.invalidateVisibleViewport()
contentView.setNeedsDisplay()
applyInitialRowIndexIfNeeded()
applyPendingScrollIfNeeded()
emitVisibleFileIfNeeded()
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
if debugKey != lastMetricsDebugKey {
@@ -596,11 +691,41 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
}
private func finishVerticalScroll() {
isProgrammaticScrollActive = false
contentView.isVerticalScrollActive = false
updateViewportFrame()
emitVisibleRange(reason: "scroll-end")
}
private func emitVisibleFileIfNeeded() {
// Keep the explicit destination selected while UIKit animates through the files
// between the old and new offsets. Emitting every intermediate header forces a
// React render per crossing and makes the navigator visibly flash.
guard !isProgrammaticScrollActive else {
return
}
// The top of the combined diff is the explicit "All files" destination.
// Treat it as a first-class selection instead of immediately resolving the
// first file header and undoing the navigator's optimistic selection.
if scrollView.contentOffset.y <= 0.5 {
guard lastVisibleFileId != nil else {
return
}
lastVisibleFileId = nil
onVisibleFileChange(["fileId": NSNull()])
return
}
guard let fileId = contentView.visibleFileId(atVerticalOffset: scrollView.contentOffset.y),
fileId != lastVisibleFileId else {
return
}
lastVisibleFileId = fileId
onVisibleFileChange(["fileId": fileId])
}
private func emitVisibleRange(reason: String) {
guard let range = contentView.currentVisibleRowRange() else {
return
@@ -670,6 +795,33 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
applyInitialRowIndexIfNeeded()
}
func scrollToFile(_ fileId: String, animated: Bool) {
pendingScrollFileId = fileId
pendingScrollAnimated = animated
applyPendingScrollIfNeeded()
}
func scrollToTop(animated: Bool) {
pendingScrollFileId = nil
pendingScrollAnimated = false
setVerticalContentOffset(0, animated: animated)
}
@objc private func handlePullToRefresh() {
onPullToRefresh([:])
}
/// Driven from JS: set to false once the reload completes to dismiss the spinner.
func setRefreshing(_ refreshing: Bool) {
if refreshing {
if !pullRefreshControl.isRefreshing {
pullRefreshControl.beginRefreshing()
}
} else if pullRefreshControl.isRefreshing {
pullRefreshControl.endRefreshing()
}
}
private func applyStyle() {
contentView.style = ReviewDiffNativeStyle
.resolve(stylePayload)
@@ -686,6 +838,38 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
)
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
emitVisibleFileIfNeeded()
}
private func applyPendingScrollIfNeeded() {
guard let fileId = pendingScrollFileId,
bounds.height > 0 else {
return
}
guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else {
if !rows.isEmpty {
pendingScrollFileId = nil
}
return
}
let animated = pendingScrollAnimated
pendingScrollFileId = nil
pendingScrollAnimated = false
setVerticalContentOffset(headerOffset, animated: animated)
}
private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) {
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
let clampedOffset = min(max(targetOffset, 0), maxOffset)
let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5
isProgrammaticScrollActive = shouldAnimate
contentView.isVerticalScrollActive = shouldAnimate
scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)
if !shouldAnimate {
updateViewportFrame()
}
}
private func applyInitialRowIndexIfNeeded() {
@@ -1255,6 +1439,32 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
return rowOffsets[rowIndex]
}
func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? {
guard let firstHeaderRowIndex = fileHeaderRowIndices.first else {
return nil
}
var lowerBound = 0
var upperBound = fileHeaderRowIndices.count
while lowerBound < upperBound {
let midpoint = (lowerBound + upperBound) / 2
let rowIndex = fileHeaderRowIndices[midpoint]
if rowOffsets[rowIndex] <= verticalOffset + 0.5 {
lowerBound = midpoint + 1
} else {
upperBound = midpoint
}
}
let rowIndex = lowerBound > 0
? fileHeaderRowIndices[lowerBound - 1]
: firstHeaderRowIndex
guard rows.indices.contains(rowIndex) else {
return nil
}
return resolvedFileId(for: rows[rowIndex])
}
private func fileHeaderRowIndex(forFileId fileId: String) -> Int? {
fileHeaderRowIndices.first { rowIndex in
rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId
@@ -7,6 +7,12 @@ class T3TerminalModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3TerminalSurface")
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
// logs so a stale native binary is distinguishable from a broken key pipeline.
Constants(
"hardwareKeyRevision" to 2,
)
View(T3TerminalView::class) {
Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->
view.terminalKey = terminalKey
@@ -20,6 +26,10 @@ class T3TerminalModule : Module() {
view.fontSize = fontSize.toFloat()
}
Prop("focusRequest") { view: T3TerminalView, focusRequest: Double ->
view.focusRequest = focusRequest
}
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
view.appearanceScheme = appearanceScheme
}
@@ -62,6 +62,15 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
var themeConfig: String = ""
var focusRequest: Double = 0.0
set(value) {
val previous = field
field = value
if (value != previous && value > 0) {
requestKeyboardFocus()
}
}
var backgroundColorHex: String = "#24292E"
set(value) {
field = value
@@ -113,11 +122,19 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
}
inputView.setOnKeyListener { _, keyCode, event ->
if (event.action != android.view.KeyEvent.ACTION_DOWN) return@setOnKeyListener false
when (keyCode) {
android.view.KeyEvent.KEYCODE_DEL -> {
when {
keyCode == android.view.KeyEvent.KEYCODE_DEL -> {
onInput(mapOf("data" to "\u007F"))
true
}
// Hardware keyboard Ctrl+A..Z -> control bytes 0x01..0x1A (Ctrl+C, Ctrl+Z, ...).
event.isCtrlPressed &&
keyCode in android.view.KeyEvent.KEYCODE_A..android.view.KeyEvent.KEYCODE_Z -> {
onInput(
mapOf("data" to (keyCode - android.view.KeyEvent.KEYCODE_A + 1).toChar().toString()),
)
true
}
else -> false
}
}
@@ -4,6 +4,12 @@ public class T3TerminalModule: Module {
public func definition() -> ModuleDefinition {
Name("T3TerminalSurface")
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
// logs so a stale native binary is distinguishable from a broken key pipeline.
Constants([
"hardwareKeyRevision": 2,
])
View(T3TerminalView.self) {
Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in
view.terminalKey = terminalKey
@@ -17,6 +23,10 @@ public class T3TerminalModule: Module {
view.fontSize = CGFloat(fontSize)
}
Prop("focusRequest") { (view: T3TerminalView, focusRequest: Double) in
view.focusRequest = focusRequest
}
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
view.appearanceScheme = appearanceScheme
}
@@ -22,13 +22,129 @@ private enum GhosttyRuntime {
}
}
/// Encodes hardware-keyboard combos that UITextField never surfaces through its
/// text-editing delegate (control combos, Escape, Tab, arrow keys) into the byte
/// sequences a terminal expects.
///
/// Capture uses UIKeyCommand with `wantsPriorityOverSystemBehavior` rather than
/// `pressesBegan`: while a text field is first responder, iPadOS routes hardware key
/// events through the text-input system, which can consume presses before they reach
/// responder press callbacks. Registered key commands are matched deterministically
/// before that happens.
private enum TerminalHardwareKeyEncoder {
/// Characters that produce a control byte when combined with Ctrl.
private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? "
static func makeKeyCommands(action: Selector) -> [UIKeyCommand] {
var commands: [UIKeyCommand] = []
let specialInputs = [
UIKeyCommand.inputEscape,
UIKeyCommand.inputUpArrow,
UIKeyCommand.inputDownArrow,
UIKeyCommand.inputLeftArrow,
UIKeyCommand.inputRightArrow,
"\t",
]
for input in specialInputs {
commands.append(makeCommand(input: input, modifierFlags: [], action: action))
}
commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action))
for character in controlInputs {
commands.append(makeCommand(input: String(character), modifierFlags: .control, action: action))
commands.append(
makeCommand(input: String(character), modifierFlags: [.control, .shift], action: action)
)
}
return commands
}
private static func makeCommand(
input: String,
modifierFlags: UIKeyModifierFlags,
action: Selector
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action)
command.wantsPriorityOverSystemBehavior = true
return command
}
static func sequence(input: String, modifiers: UIKeyModifierFlags) -> String? {
switch input {
case UIKeyCommand.inputEscape:
return "\u{1B}"
case UIKeyCommand.inputUpArrow:
return "\u{1B}[A"
case UIKeyCommand.inputDownArrow:
return "\u{1B}[B"
case UIKeyCommand.inputRightArrow:
return "\u{1B}[C"
case UIKeyCommand.inputLeftArrow:
return "\u{1B}[D"
case "\t":
return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t"
default:
break
}
guard modifiers.contains(.control) else { return nil }
guard let scalar = input.lowercased().unicodeScalars.first else { return nil }
return controlSequence(for: scalar)
}
private static func controlSequence(for scalar: Unicode.Scalar) -> String? {
switch scalar {
case "a"..."z":
// Ctrl+A..Z -> 0x01..0x1A (Ctrl+C = ETX, Ctrl+Z = SUB, ...).
return UnicodeScalar(scalar.value - 96).map(String.init)
case " ", "@":
return "\u{00}"
case "[":
return "\u{1B}"
case "\\":
return "\u{1C}"
case "]":
return "\u{1D}"
case "^":
return "\u{1E}"
case "_", "-":
return "\u{1F}"
case "?":
return "\u{7F}"
default:
return nil
}
}
}
private final class TerminalInputField: UITextField {
var onDeleteBackward: (() -> Void)?
var onInsert: ((String) -> Void)?
private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands(
action: #selector(handleHardwareKeyCommand(_:))
)
override var keyCommands: [UIKeyCommand]? {
Self.hardwareKeyCommands
}
override func deleteBackward() {
onDeleteBackward?()
super.deleteBackward()
}
@objc
private func handleHardwareKeyCommand(_ command: UIKeyCommand) {
guard let input = command.input else { return }
guard let sequence = TerminalHardwareKeyEncoder.sequence(
input: input,
modifiers: command.modifierFlags
) else { return }
onInsert?(sequence)
}
}
private enum TerminalAppearanceScheme: String {
@@ -108,6 +224,15 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
}
}
var focusRequest: Double = 0 {
didSet {
guard oldValue != focusRequest else { return }
DispatchQueue.main.async { [weak self] in
self?.requestKeyboardFocus()
}
}
}
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
didSet {
guard oldValue != appearanceScheme else { return }
@@ -167,6 +292,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
inputField.onDeleteBackward = { [weak self] in
self?.emitInput("\u{7F}")
}
inputField.onInsert = { [weak self] data in
self?.emitInput(data)
}
focusTapGesture.addTarget(self, action: #selector(handleViewportTap))
terminalViewport.addGestureRecognizer(focusTapGesture)
+34 -20
View File
@@ -5,7 +5,8 @@
"main": "index.ts",
"scripts": {
"dev": "expo start --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear",
"dev:client:preview": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=preview expo start --dev-client --scheme t3code-preview --clear --lan'",
"start": "expo start",
"start:dev": "APP_VARIANT=development expo start",
"start:preview": "APP_VARIANT=preview expo start",
@@ -43,12 +44,16 @@
"@clerk/expo": "catalog:",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/ui": "~56.0.8",
"@expo/metro-runtime": "~56.0.15",
"@expo/ui": "~56.0.18",
"@legendapp/list": "3.2.0",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
"@react-native-menu/menu": "^2.0.0",
"@react-navigation/elements": "2.9.26",
"@react-navigation/native": "7.3.4",
"@react-navigation/native-stack": "7.17.6",
"@shikijs/core": "4.2.0",
"@shikijs/engine-javascript": "4.2.0",
"@shikijs/langs": "4.2.0",
@@ -62,38 +67,39 @@
"clsx": "^2.1.1",
"diff": "8.0.3",
"effect": "catalog:",
"expo": "^56.0.0",
"expo-asset": "~56.0.15",
"expo-auth-session": "~56.0.12",
"expo-build-properties": "~56.0.15",
"expo-camera": "~56.0.7",
"expo-clipboard": "~56.0.3",
"expo-constants": "~56.0.16",
"expo": "~56.0.12",
"expo-asset": "~56.0.17",
"expo-auth-session": "~56.0.14",
"expo-build-properties": "~56.0.19",
"expo-camera": "~56.0.8",
"expo-clipboard": "~56.0.4",
"expo-constants": "~56.0.18",
"expo-crypto": "~56.0.4",
"expo-dev-client": "~56.0.16",
"expo-file-system": "~56.0.7",
"expo-font": "~56.0.5",
"expo-dev-client": "~56.0.20",
"expo-file-system": "~56.0.8",
"expo-font": "~56.0.7",
"expo-glass-effect": "~56.0.4",
"expo-haptics": "~56.0.3",
"expo-image-picker": "~56.0.14",
"expo-linking": "~56.0.12",
"expo-image": "~56.0.11",
"expo-image-picker": "~56.0.18",
"expo-linking": "~56.0.14",
"expo-network": "~56.0.5",
"expo-notifications": "~56.0.14",
"expo-notifications": "~56.0.18",
"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-sqlite": "~56.0.5",
"expo-symbols": "~56.0.6",
"expo-updates": "~56.0.19",
"expo-web-browser": "~56.0.5",
"expo-widgets": "~56.0.15",
"expo-widgets": "~56.0.19",
"punycode": "^2.3.1",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.85.3",
"react-native-gesture-handler": "~2.31.1",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.21.7",
"react-native-keyboard-controller": "1.21.13",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "0.35.9",
"react-native-reanimated": "4.3.1",
@@ -117,5 +123,13 @@
},
"overrides": {
"react-native-nitro-markdown": "file:deps/react-native-nitro-markdown-0.5.0.tgz"
},
"expo": {
"autolinking": {
"buildFromSource": [
"react-native-screens",
"@react-native-menu/menu"
]
}
}
}
@@ -0,0 +1,81 @@
"use strict";
// Bundle the widget asset catalog into an app-extension (widget) target.
//
// expo-widgets generates the widget target without a Resources build phase, and
// hand-adding a PBXResourcesBuildPhase does NOT get picked up — xcodebuild's
// planner never schedules `actool` for it (verified: even a full re-plan skips
// it). So instead we add a shell-script phase that runs `actool` directly and
// drops the compiled Assets.car into the extension bundle. Marked
// alwaysOutOfDate so the build system always runs it.
//
// Idempotent across re-runs. Returns true when it added the phase, false when
// it was already present. Throws when the target does not exist — that means
// this ran before expo-widgets created the target (plugin ordering bug) and
// silently skipping would ship a widget without its assets.
const PHASE_NAME = "Compile Widget Assets";
// Compiles ExpoWidgetsTarget/Assets.xcassets into the extension's resources dir.
// Uses only Xcode-provided build settings so it works for device + simulator.
const ACTOOL_SCRIPT = [
"set -e",
'CATALOG="${SRCROOT}/ExpoWidgetsTarget/Assets.xcassets"',
'if [ ! -d "$CATALOG" ]; then',
' echo "error: widget asset catalog not found at $CATALOG (expo-widgets wiped it? check plugin ordering in app.config.ts)"',
" exit 1",
"fi",
'DEST="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"',
'mkdir -p "$DEST"',
'xcrun actool "$CATALOG" --compile "$DEST" --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET:-16.0}" --output-format human-readable-text',
].join("\n");
function stripComments(map) {
const out = {};
for (const key of Object.keys(map || {})) {
if (key.endsWith("_comment")) continue;
out[key] = map[key];
}
return out;
}
function findByName(map, name) {
for (const [uuid, value] of Object.entries(stripComments(map))) {
if (value && value.name === name) return { uuid, value };
}
return null;
}
/**
* @param {import('xcode').XcodeProject} proj
* @param {{ targetName: string }} opts
*/
function addWidgetAssetCatalog(proj, opts) {
const objects = proj.hash.project.objects;
const target = findByName(objects.PBXNativeTarget, opts.targetName);
if (!target) {
throw new Error(
`addWidgetAssetCatalog: target "${opts.targetName}" not found — ` +
"withWidgetLogoAsset must be registered before expo-widgets so its " +
"xcodeproj mod runs after the widget target is created.",
);
}
const phases = target.value.buildPhases || [];
const existing = objects.PBXShellScriptBuildPhase || {};
const already = Object.entries(stripComments(existing)).some(
([uuid, value]) =>
value && value.name === `"${PHASE_NAME}"` && phases.some((p) => p.value === uuid),
);
if (already) return false;
const { uuid } = proj.addBuildPhase([], "PBXShellScriptBuildPhase", PHASE_NAME, target.uuid, {
shellPath: "/bin/sh",
shellScript: ACTOOL_SCRIPT,
});
// Always run: input-analysis is exactly what skipped the Resources phase.
objects.PBXShellScriptBuildPhase[uuid].alwaysOutOfDate = 1;
return true;
}
module.exports = { addWidgetAssetCatalog };
@@ -0,0 +1,52 @@
const fs = require("node:fs");
const path = require("node:path");
const { withDangerousMod } = require("expo/config-plugins");
const MARKER = "# t3code: repair cached CocoaPods UUID allocation before SPM integration";
const UUID_REPAIR = `${MARKER}
pods_project = installer.pods_project
existing_uuids = pods_project.objects.map(&:uuid)
uuid_prefix = pods_project.instance_variable_get(:@uuid_prefix)[0, 6]
sequential_uuid = /\\A#{Regexp.escape(uuid_prefix)}([0-9A-F]{7})0\\z/
highest_index = existing_uuids.filter_map do |uuid|
match = sequential_uuid.match(uuid)
match && match[1].to_i(16)
end.max || -1
# Pod::Project generates sequential UUIDs without collision checks because CocoaPods
# normally creates the project in this process. EAS can restore Pods.xcodeproj from
# cache, leaving the allocator behind the loaded objects. React Native's SPM support
# then reuses an existing UUID and silently corrupts the project graph.
next_index = highest_index + 1
pods_project.instance_variable_set(:@generated_uuids, Array.new(next_index))
pods_project.instance_variable_set(:@available_uuids, [])
pods_project.generate_available_uuid_list(1_000)
Pod::UI.puts "T3Code: reset CocoaPods UUID allocator at #{next_index} (#{existing_uuids.length} existing objects)"
`;
module.exports = function withIosCocoaPodsUuidCache(config) {
return withDangerousMod(config, [
"ios",
(nextConfig) => {
const podfilePath = path.join(nextConfig.modRequest.platformProjectRoot, "Podfile");
const podfile = fs.readFileSync(podfilePath, "utf8");
if (podfile.includes(MARKER)) {
return nextConfig;
}
const postInstallStart = "post_install do |installer|\n";
if (!podfile.includes(postInstallStart)) {
throw new Error("Unable to repair CocoaPods UUID allocation: post_install is missing.");
}
fs.writeFileSync(
podfilePath,
podfile.replace(postInstallStart, `${postInstallStart}${UUID_REPAIR}`),
"utf8",
);
return nextConfig;
},
]);
};
@@ -0,0 +1,99 @@
const { withAppDelegate, withInfoPlist } = require("expo/config-plugins");
const SCENE_DELEGATE = `
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(
_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions
) {
guard
let windowScene = scene as? UIWindowScene,
let appDelegate = UIApplication.shared.delegate as? AppDelegate
else {
return
}
let appWindow: UIWindow
if let existingWindow = appDelegate.window {
appWindow = existingWindow
} else {
appWindow = UIWindow(windowScene: windowScene)
appDelegate.window = appWindow
appDelegate.reactNativeFactory?.startReactNative(
withModuleName: "main",
in: appWindow,
launchOptions: nil)
}
window = appWindow
appWindow.windowScene = windowScene
appWindow.makeKeyAndVisible()
if let url = connectionOptions.urlContexts.first?.url {
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
}
if let userActivity = connectionOptions.userActivities.first {
_ = appDelegate.application(
UIApplication.shared,
continue: userActivity,
restorationHandler: { _ in })
}
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard
let url = URLContexts.first?.url,
let appDelegate = UIApplication.shared.delegate as? AppDelegate
else {
return
}
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
_ = appDelegate.application(
UIApplication.shared,
continue: userActivity,
restorationHandler: { _ in })
}
}`;
module.exports = function withIosSceneLifecycle(config) {
config = withInfoPlist(config, (nextConfig) => {
nextConfig.modResults.UIApplicationSceneManifest = {
UIApplicationSupportsMultipleScenes: false,
UISceneConfigurations: {
UIWindowSceneSessionRoleApplication: [
{
UISceneConfigurationName: "Default Configuration",
UISceneDelegateClassName: "$(PRODUCT_MODULE_NAME).SceneDelegate",
},
],
},
};
return nextConfig;
});
return withAppDelegate(config, (nextConfig) => {
if (nextConfig.modResults.language !== "swift") {
throw new Error("The iOS scene lifecycle plugin requires a Swift AppDelegate.");
}
if (!nextConfig.modResults.contents.includes("class SceneDelegate:")) {
nextConfig.modResults.contents += SCENE_DELEGATE;
}
return nextConfig;
});
};
@@ -0,0 +1,68 @@
"use strict";
// Ships the branded T3 mark to the Live Activity / widget extension.
//
// expo-widgets generates ExpoWidgetsTarget without a Resources build phase and
// has no asset support, so this plugin (a) writes an SVG template image set into
// the generated widget asset catalog and (b) wires that catalog into the widget
// target with an actool build phase.
//
// ORDERING: must be listed BEFORE "expo-widgets" in the plugins array. Expo
// chains same-type mods so the last-registered runs FIRST; registering this
// plugin earlier makes its mods run AFTER expo-widgets' mods. That matters
// twice: expo-widgets' dangerous mod rmSync's ios/ExpoWidgetsTarget/ (deleting
// any catalog written before it), and its xcodeproj mod is what creates the
// widget target. Listed after expo-widgets, both steps silently no-op on a
// fresh prebuild — which is how prod build 8 shipped without the logo.
const path = require("path");
const fs = require("fs");
const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");
const { addWidgetAssetCatalog } = require("./lib/addWidgetAssetCatalog.cjs");
const TARGET_NAME = "ExpoWidgetsTarget";
const CATALOG_NAME = "Assets.xcassets";
const IMAGE_SET = "T3Mark.imageset";
const SVG_NAME = "T3Mark.svg";
const CATALOG_CONTENTS = JSON.stringify({ info: { author: "expo", version: 1 } }, null, 2) + "\n";
const IMAGE_SET_CONTENTS =
JSON.stringify(
{
images: [{ idiom: "universal", filename: SVG_NAME }],
info: { author: "expo", version: 1 },
properties: {
"preserves-vector-representation": true,
"template-rendering-intent": "template",
},
},
null,
2,
) + "\n";
function withAssetFiles(config) {
return withDangerousMod(config, [
"ios",
(cfg) => {
const source = path.join(cfg.modRequest.projectRoot, "assets", "widget", SVG_NAME);
const catalogDir = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, CATALOG_NAME);
const imageSetDir = path.join(catalogDir, IMAGE_SET);
fs.mkdirSync(imageSetDir, { recursive: true });
fs.writeFileSync(path.join(catalogDir, "Contents.json"), CATALOG_CONTENTS);
fs.writeFileSync(path.join(imageSetDir, "Contents.json"), IMAGE_SET_CONTENTS);
fs.copyFileSync(source, path.join(imageSetDir, SVG_NAME));
return cfg;
},
]);
}
function withAssetWiring(config) {
return withXcodeProject(config, (cfg) => {
addWidgetAssetCatalog(cfg.modResults, { targetName: TARGET_NAME });
return cfg;
});
}
module.exports = function withWidgetLogoAsset(config) {
return withAssetWiring(withAssetFiles(config));
};
@@ -0,0 +1,30 @@
"use strict";
// One-off: apply the widget asset-catalog wiring to the already-generated
// ios/ project so the current build compiles ExpoWidgetsTarget/Assets.xcassets
// without a full `expo prebuild`. The durable equivalent lives in
// plugins/withWidgetLogoAsset.cjs and runs on prebuild.
const path = require("path");
const fs = require("fs");
const xcodePath = require.resolve("xcode", {
paths: [
require.resolve("@expo/config-plugins", { paths: [require.resolve("expo/package.json")] }),
],
});
const xcode = require(xcodePath);
const { addWidgetAssetCatalog } = require("../plugins/lib/addWidgetAssetCatalog.cjs");
const pbxprojPath = path.join(__dirname, "..", "ios", "T3CodeDev.xcodeproj", "project.pbxproj");
const proj = xcode.project(pbxprojPath);
proj.parseSync();
const added = addWidgetAssetCatalog(proj, { targetName: "ExpoWidgetsTarget" });
if (added) {
fs.writeFileSync(pbxprojPath, proj.writeSync());
console.log("Added widget asset-compile phase to ExpoWidgetsTarget.");
} else {
console.log("No change: phase already present.");
}
+61
View File
@@ -0,0 +1,61 @@
import * as Linking from "expo-linking";
import * as SplashScreen from "expo-splash-screen";
import { useEffect } from "react";
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 { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native";
import { RegistryContext } from "@effect/atom-react";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
import { useThemeColor } from "./lib/useThemeColor";
import "../global.css";
const appLinking = {
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
};
const Navigation = createStaticNavigation(RootStack);
export default function App() {
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
useEffect(() => {
SplashScreen.hide();
}, []);
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<AppearancePreferencesProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={statusBarBg}
translucent
/>
{/* The navigation theme drives the NATIVE header appearance: native-stack
forwards `dark` as the nav bar's overrideUserInterfaceStyle. Without
this, React Navigation defaults to its light theme and every native
header (glass buttons, title, materials) is forced light even when
the system is in dark mode. */}
<Navigation
linking={appLinking}
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
/>
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</AppearancePreferencesProvider>
</CloudAuthProvider>
</RegistryContext.Provider>
);
}
+490
View File
@@ -0,0 +1,490 @@
import {
createPathConfigForStaticNavigation,
getPathFromState,
NavigationState,
StackActions,
useNavigation,
} from "@react-navigation/native";
import {
createNativeStackNavigator,
createNativeStackScreen,
type NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "./components/AppText";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";
import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet";
import { ReviewSheet } from "./features/review/ReviewSheet";
import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen";
import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet";
import { GitCommitSheet } from "./features/threads/git/GitCommitSheet";
import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet";
import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet";
import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen";
import { ConnectionsRouteScreen } from "./features/connection/ConnectionsRouteScreen";
import { ConnectionsNewRouteScreen } from "./features/connection/ConnectionsNewRouteScreen";
import { HomeRouteScreen } from "./features/home/HomeRouteScreen";
import { AddProjectDestinationRoute } from "./features/projects/AddProjectDestinationRoute";
import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen";
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header
// background stay STATIC config while still adapting to appearance changes.
const SHEET_BACKGROUND_COLOR =
Platform.OS === "ios"
? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })
: undefined;
type AppScreenOptions = NativeStackNavigationOptions & {
readonly unstable_navigationItemStyle?: "editor";
};
// Shared header presets. Screens only override genuinely dynamic values (titles,
// subtitles, toolbar items, search callbacks) via NativeStackScreenOptions.
//
// GLASS: transparent header over the screen's primary scroll view, with the iOS 26
// scroll-edge blur sampling the content (Home, Thread, Files tree, settings sheet).
const GLASS_HEADER_OPTIONS: AppScreenOptions = {
headerBackButtonDisplayMode: "minimal",
headerBackTitle: "",
headerLargeTitle: false,
headerShadowVisible: false,
headerShown: true,
headerStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
headerTransparent: Platform.OS === "ios",
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
};
// SOLID: opaque sheet-colored header for surfaces whose content scrolls internally
// (file viewer, terminal, review) — there is nothing for glass to sample there.
const SOLID_HEADER_OPTIONS: AppScreenOptions = {
headerBackButtonDisplayMode: "minimal",
headerBackTitle: "",
headerLargeTitle: false,
headerShadowVisible: false,
headerShown: true,
headerStyle:
SHEET_BACKGROUND_COLOR !== undefined
? // native-stack types this as `string`, but the native side accepts any
// ColorValue including DynamicColorIOS.
{ backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
: undefined,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
headerTransparent: false,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
};
// Solid header variant for screens inside sheets (centered title, no editor style).
const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
...SOLID_HEADER_OPTIONS,
unstable_navigationItemStyle: undefined,
};
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "Settings",
screenOptions: {
...GLASS_HEADER_OPTIONS,
// Sheets read better with the iOS-default centered title (no editor style).
unstable_navigationItemStyle: undefined,
},
screens: {
Settings: createNativeStackScreen({
screen: SettingsRouteScreen,
linking: "",
options: {
title: "Settings",
},
}),
SettingsEnvironments: createNativeStackScreen({
screen: SettingsEnvironmentsRouteScreen,
linking: "environments",
options: {
title: "Environments",
},
}),
SettingsEnvironmentNew: createNativeStackScreen({
screen: ConnectionsNewRouteScreen,
linking: "environment-new",
options: {
title: "Add Environment",
},
}),
SettingsArchive: createNativeStackScreen({
screen: ArchivedThreadsRouteScreen,
linking: "archive",
options: {
title: "Archived Threads",
},
}),
SettingsAppearance: createNativeStackScreen({
screen: SettingsAppearanceRouteScreen,
linking: "appearance",
options: {
title: "Appearance",
},
}),
SettingsClientStorage: createNativeStackScreen({
screen: SettingsClientStorageRouteScreen,
linking: "client-storage",
options: {
title: "Client Storage",
},
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
options: {
title: "Sign in",
},
}),
SettingsWaitlist: createNativeStackScreen({
screen: SettingsWaitlistRouteScreen,
linking: "waitlist",
options: {
title: "Join the waitlist",
},
}),
},
});
// Thread routes live FLAT in the root stack (not in a nested navigator). A nested
// stack means a second UINavigationController with its own UINavigationBar, which
// breaks iOS 26's shared-header morphing between Home and Thread (each pair inside
// one bar morphs; across two bars the whole screen slides). Flat linking paths keep
// the same deep-link URLs the nested config produced.
const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
// New-task / add-project flow: nested navigator inside the formSheet (Settings-sheet
// pattern — a plain formSheet screen cannot render a stack header; the header and
// in-sheet pushes come from this nested stack).
const NewTaskSheetStack = createNativeStackNavigator({
initialRouteName: "NewTask",
screenOptions: {
...GLASS_HEADER_OPTIONS,
// Sheets read better with the iOS-default centered title (no editor style).
unstable_navigationItemStyle: undefined,
},
screens: {
NewTask: createNativeStackScreen({
screen: NewTaskRouteScreen,
linking: "",
options: {
title: "Choose project",
},
}),
NewTaskDraft: createNativeStackScreen({
screen: NewTaskDraftRouteScreen,
linking: "draft",
// The draft composer has no scroll view for glass to sample; a solid
// header also lays the content out below the bar (no manual inset).
options: SHEET_SOLID_HEADER_OPTIONS,
}),
AddProject: createNativeStackScreen({
screen: AddProjectSourceRoute,
linking: "add-project",
options: {
title: "Add Project",
},
}),
AddProjectRepository: createNativeStackScreen({
screen: AddProjectRepositoryRoute,
linking: "add-project/repository",
}),
AddProjectDestination: createNativeStackScreen({
screen: AddProjectDestinationRoute,
linking: "add-project/destination",
}),
AddProjectLocal: createNativeStackScreen({
screen: AddProjectLocalRoute,
linking: "add-project/local",
}),
},
});
// Routes presented as sheets/overlays ON TOP of the workspace. They must not
// influence the adaptive workspace layout: opening Settings over Home should
// not flip the sidebar in or change the active thread.
const WORKSPACE_OVERLAY_ROUTES = new Set([
"ConnectOnboarding",
"Connections",
"ConnectionsNew",
"GitBranches",
"GitCommit",
"GitConfirm",
"GitOverview",
"NewTaskSheet",
"SettingsSheet",
"ThreadReviewComment",
]);
/**
* Pathname of the topmost NON-overlay route — the screen the workspace is
* actually "on", regardless of any sheets floating above it.
*/
function workspacePathFromState(state: NavigationState): string {
const routes = state.routes.filter((route) => !WORKSPACE_OVERLAY_ROUTES.has(route.name));
const effectiveState =
routes.length > 0 && routes.length !== state.routes.length
? ({ ...state, routes, index: routes.length - 1 } as NavigationState)
: state;
const path = getPathFromState(effectiveState, navigationPathConfig);
return path.startsWith("/") ? path : `/${path}`;
}
function RootStackLayout(props: {
readonly children: React.ReactNode;
readonly state: NavigationState;
}) {
useAgentNotificationNavigation();
useThreadOutboxDrain();
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
useConnectOnboardingNavigation();
// Full pathname (sheets included) for keyboard-command scoping; the
// workspace layout only reacts to the underlying non-overlay route.
const path = getPathFromState(props.state, navigationPathConfig);
const pathname = path.startsWith("/") ? path : `/${path}`;
const workspacePathname = workspacePathFromState(props.state);
return (
<HardwareKeyboardCommandProvider pathname={pathname}>
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</ClerkSettingsSheetDetentProvider>
</HardwareKeyboardCommandProvider>
);
}
function NotFoundScreen() {
const navigation = useNavigation();
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
const returnHomeButtonStyle = StyleSheet.flatten([
{
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
},
primaryBgStyle,
]);
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
gap: 16,
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={[{ flex: 1 }, screenBgStyle]}
>
<Text className="text-3xl font-t3-bold text-foreground" selectable>
Route not found
</Text>
<Pressable
style={returnHomeButtonStyle}
onPress={() => navigation.dispatch(StackActions.replace("Home"))}
>
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
</Pressable>
</ScrollView>
);
}
export const RootStack = createNativeStackNavigator({
initialRouteName: "Home",
layout: RootStackLayout,
screenOptions: {
headerShown: false,
},
screens: {
Home: createNativeStackScreen({
screen: HomeRouteScreen,
linking: "",
options: {
...GLASS_HEADER_OPTIONS,
contentStyle: { backgroundColor: "transparent" },
headerBackVisible: false,
title: "Threads",
},
}),
Thread: createNativeStackScreen({
screen: ThreadRouteScreen,
linking: THREAD_LINKING_PREFIX,
options: GLASS_HEADER_OPTIONS,
}),
ThreadTerminal: createNativeStackScreen({
screen: ThreadTerminalRouteScreen,
linking: `${THREAD_LINKING_PREFIX}/terminal`,
options: SOLID_HEADER_OPTIONS,
}),
ThreadReview: createNativeStackScreen({
screen: ReviewSheet,
linking: `${THREAD_LINKING_PREFIX}/review`,
options: SOLID_HEADER_OPTIONS,
}),
ThreadReviewComment: createNativeStackScreen({
screen: ReviewCommentComposerSheet,
linking: `${THREAD_LINKING_PREFIX}/review-comment`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
ThreadFiles: createNativeStackScreen({
screen: ThreadFilesTreeScreen,
linking: `${THREAD_LINKING_PREFIX}/files`,
options: {
...GLASS_HEADER_OPTIONS,
contentStyle:
SHEET_BACKGROUND_COLOR !== undefined
? { backgroundColor: SHEET_BACKGROUND_COLOR }
: undefined,
title: "Files",
},
}),
ThreadFile: createNativeStackScreen({
screen: ThreadFileScreen,
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
options: SOLID_HEADER_OPTIONS,
}),
GitOverview: createNativeStackScreen({
screen: GitOverviewSheet,
linking: `${THREAD_LINKING_PREFIX}/git`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitCommit: createNativeStackScreen({
screen: GitCommitSheet,
linking: `${THREAD_LINKING_PREFIX}/git/commit`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitBranches: createNativeStackScreen({
screen: GitBranchesSheet,
linking: `${THREAD_LINKING_PREFIX}/git/branches`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitConfirm: createNativeStackScreen({
screen: GitConfirmSheet,
linking: `${THREAD_LINKING_PREFIX}/git-confirm`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.45, 0.7],
sheetGrabberVisible: true,
},
}),
SettingsSheet: createNativeStackScreen({
screen: SettingsSheetStack,
linking: "settings",
options: {
gestureEnabled: true,
headerShown: false,
presentation: "formSheet",
sheetAllowedDetents: [0.7, 0.92],
sheetGrabberVisible: true,
},
}),
ConnectOnboarding: createNativeStackScreen({
screen: ConnectOnboardingRouteScreen,
linking: "connect-onboarding",
options: {
// Root screenOptions hide headers; formSheets that want the native
// title bar opt back in with the sheet header preset.
...SHEET_SOLID_HEADER_OPTIONS,
title: "Set up T3 Connect",
gestureEnabled: true,
presentation: "formSheet",
sheetAllowedDetents: [0.6, 0.95],
sheetGrabberVisible: true,
},
}),
Connections: createNativeStackScreen({
screen: ConnectionsRouteScreen,
linking: "connections",
options: {
title: "Environments",
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
},
}),
ConnectionsNew: createNativeStackScreen({
screen: ConnectionsNewRouteScreen,
linking: "connections/new",
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
},
}),
NewTaskSheet: createNativeStackScreen({
screen: NewTaskSheetStack,
linking: "new",
// The whole new-task flow (choose project → draft → add project) shares
// draft state via NewTaskFlowProvider. The expo-router era mounted it in
// app/new/_layout.tsx; this layout wrapper is the native-stack equivalent.
layout: ({ children }) => <NewTaskFlowProvider>{children}</NewTaskFlowProvider>,
options: {
gestureEnabled: true,
headerShown: false,
presentation: "formSheet",
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
},
}),
NotFound: createNativeStackScreen({
screen: NotFoundScreen,
linking: "*",
}),
},
});
type RootStackType = typeof RootStack;
const navigationPathConfig = {
screens: createPathConfigForStaticNavigation(RootStack) ?? {},
};
declare module "@react-navigation/native" {
interface RootNavigator extends RootStackType {}
}
-43
View File
@@ -1,43 +0,0 @@
import { Link } from "expo-router";
import { Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "../components/AppText";
export default function NotFoundRoute() {
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
gap: 16,
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={[{ flex: 1 }, screenBgStyle]}
>
<Text className="text-3xl font-t3-bold text-foreground" selectable>
Route not found
</Text>
<Link href="/" asChild>
<Pressable
style={[
{
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
},
primaryBgStyle,
]}
>
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
</Pressable>
</Link>
</ScrollView>
);
}
-149
View File
@@ -1,149 +0,0 @@
import "../../global.css";
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import { usePathname } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback } from "react";
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 { useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
import { useWorkspaceState } from "../state/workspace";
import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry";
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
import {
ClerkSettingsSheetDetentProvider,
useClerkSettingsSheetDetent,
} from "../features/cloud/ClerkSettingsSheetDetent";
import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation";
import { useThemeColor } from "../lib/useThemeColor";
function AppNavigator() {
const pathname = usePathname();
const expandedSettingsRouteIsActive =
pathname === "/settings/archive" || pathname === "/settings/auth";
return (
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
<AppNavigatorContent />
</ClerkSettingsSheetDetentProvider>
);
}
function AppNavigatorContent() {
const { state } = useWorkspaceState();
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
useAgentNotificationNavigation();
useThreadOutboxDrain();
const handleSettingsTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
}
},
[collapse],
);
const newTaskScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
};
const connectionSheetScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
};
const settingsSheetScreenOptions = {
...connectionSheetScreenOptions,
sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
};
if (state.isLoadingConnections) {
return <LoadingScreen message="Loading remote workspace…" />;
}
return (
<>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={String(statusBarBg)}
translucent
/>
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen
name="settings"
listeners={{ transitionEnd: handleSettingsTransitionEnd }}
options={settingsSheetScreenOptions}
/>
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
<Stack.Screen name="new" options={newTaskScreenOptions} />
<Stack.Screen
name="threads/[environmentId]/[threadId]"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: "transparent" },
gestureEnabled: true,
headerShown: false,
}}
/>
</Stack>
</>
);
}
export default function RootLayout() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
return (
<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>
);
}
@@ -1,29 +0,0 @@
import Stack from "expo-router/stack";
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 = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
return (
<Stack
screenOptions={{
contentStyle,
headerStyle: { backgroundColor: connSheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
headerShadowVisible: false,
headerBackButtonDisplayMode: "minimal",
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="new" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
-120
View File
@@ -1,120 +0,0 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import { useProjects, useThreadShells } from "../state/entities";
import { useWorkspaceState } from "../state/workspace";
import { buildThreadRoutePath } from "../lib/routes";
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import { HomeHeader } from "../features/home/HomeHeader";
import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
import { useThreadListActions } from "../features/home/useThreadListActions";
interface HomeListOptions {
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const [listOptions, setListOptions] = useState<HomeListOptions>({
selectedEnvironmentId: null,
projectSortOrder:
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
});
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const environments = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(
Order.String,
(environment: { readonly label: string }) => environment.label,
),
),
[savedConnectionsById],
);
const selectedEnvironmentId = environments.some(
(environment) => environment.environmentId === listOptions.selectedEnvironmentId,
)
? listOptions.selectedEnvironmentId
: null;
const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
}, []);
const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
setListOptions((current) => ({ ...current, projectSortOrder }));
}, []);
const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
setListOptions((current) => ({ ...current, threadSortOrder }));
}, []);
const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
setListOptions((current) => ({ ...current, projectGroupingMode }));
}, []);
return (
<>
<HomeHeader
environments={environments}
selectedEnvironmentId={selectedEnvironmentId}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
projectGroupingMode={listOptions.projectGroupingMode}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenSettings={() => router.push("/settings")}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => router.push("/new")}
onThreadSortOrderChange={setThreadSortOrder}
/>
<HomeScreen
catalogState={catalogState}
onAddConnection={() => router.push("/connections/new")}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onOpenEnvironments={() => router.push("/settings/environments")}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
</>
);
}
-50
View File
@@ -1,50 +0,0 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function NewTaskLayout() {
const sheetStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
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", title: "Choose project" }} />
<Stack.Screen
name="add-project/index"
options={{ animation: "slide_from_right", title: "New project" }}
/>
<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,5 +0,0 @@
import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectDestinationRoute() {
return <AddProjectDestinationScreen />;
}
@@ -1,5 +0,0 @@
import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRoute() {
return <AddProjectSourceScreen />;
}
@@ -1,5 +0,0 @@
import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectLocalRoute() {
return <AddProjectLocalFolderScreen />;
}
@@ -1,23 +0,0 @@
import { Stack, useLocalSearchParams } from "expo-router";
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects";
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={{ title }} />
<AddProjectRepositoryScreen />
</>
);
}
-29
View File
@@ -1,29 +0,0 @@
import { Stack, useLocalSearchParams } from "expo-router";
import { NewTaskDraftScreen } from "../../features/threads/NewTaskDraftScreen";
export default function NewTaskDraftRoute() {
const params = useLocalSearchParams<{
environmentId?: string | string[];
projectId?: string | string[];
title?: string | string[];
}>();
return (
<>
<Stack.Screen
options={{
title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
}}
/>
<NewTaskDraftScreen
initialProjectRef={{
environmentId: Array.isArray(params.environmentId)
? params.environmentId[0]
: params.environmentId,
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
}}
/>
</>
);
}
-62
View File
@@ -1,62 +0,0 @@
import Stack from "expo-router/stack";
import { useCallback } from "react";
import { useResolveClassNames } from "uniwind";
import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function SettingsLayout() {
const { collapse } = useClerkSettingsSheetDetent();
const contentStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
const handleExpandedRouteTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
}
},
[collapse],
);
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.Screen
name="archive"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Archived Threads" }}
/>
<Stack.Screen
name="auth"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Sign in" }}
/>
</Stack>
);
}
-3
View File
@@ -1,3 +0,0 @@
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
export default ArchivedThreadsRouteScreen;
-33
View File
@@ -1,33 +0,0 @@
import { useAuth } from "@clerk/expo";
import { AuthView, UserProfileView } from "@clerk/expo/native";
import { Redirect, Stack } from "expo-router";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
export default function SettingsAuthRouteScreen() {
return hasCloudPublicConfig() ? (
<ConfiguredSettingsAuthRouteScreen />
) : (
<Redirect href="/settings" />
);
}
function ConfiguredSettingsAuthRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
return (
<>
<Stack.Screen options={{ title: isSignedIn ? "Account" : "Sign in" }} />
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} />
) : (
<AuthView isDismissible={false} />
)
) : null}
</View>
</>
);
}
@@ -1 +0,0 @@
export { default } from "../connections/new";
@@ -1,107 +0,0 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export default function ThreadLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
headerTitle: "",
}}
/>
<Stack.Screen
name="git"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.85],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="git-confirm"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.4],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="review"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files changed",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/index"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/[...path]"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "File",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review-comment"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.72, 0.92],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="terminal"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: "#050505" },
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerShadowVisible: false,
}}
/>
</Stack>
);
}
@@ -1,5 +0,0 @@
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFileRoute() {
return <ThreadFileScreen />;
}
@@ -1,5 +0,0 @@
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFilesIndexRoute() {
return <ThreadFilesTreeScreen />;
}
@@ -1,5 +0,0 @@
import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
export default function GitConfirmRoute() {
return <GitConfirmSheet />;
}
@@ -1,58 +0,0 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export const unstable_settings = {
anchor: "index",
};
export default function GitSheetLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerShown: false,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen
name="commit"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Commit changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="branches"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Branches & worktrees",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Review changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
</Stack>
);
}
@@ -1,5 +0,0 @@
import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
export default function GitBranchesRoute() {
return <GitBranchesSheet />;
}
@@ -1,5 +0,0 @@
import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
export default function GitCommitRoute() {
return <GitCommitSheet />;
}
@@ -1,5 +0,0 @@
import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
export default function GitRoute() {
return <GitOverviewSheet />;
}
@@ -1,18 +0,0 @@
import { Redirect, useLocalSearchParams } from "expo-router";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
export default function ReviewRoute() {
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
return (
<Redirect
href={{
pathname: "/threads/[environmentId]/[threadId]/review",
params: { environmentId, threadId },
}}
/>
);
}
@@ -1,5 +0,0 @@
import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
export default function ThreadRoute() {
return <ThreadRouteScreen />;
}
@@ -1,5 +0,0 @@
import { ReviewCommentComposerSheet } from "../../../../features/review/ReviewCommentComposerSheet";
export default function ReviewCommentRoute() {
return <ReviewCommentComposerSheet />;
}
@@ -1,10 +0,0 @@
import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
export default function ReviewRoute() {
return (
<ReviewHighlighterProvider>
<ReviewSheet />
</ReviewHighlighterProvider>
);
}
@@ -1,5 +0,0 @@
import { ThreadTerminalRouteScreen } from "../../../../features/terminal/ThreadTerminalRouteScreen";
export default function ThreadTerminalRoute() {
return <ThreadTerminalRouteScreen />;
}
+5 -14
View File
@@ -1,11 +1,9 @@
import type { Ref } from "react";
import {
Text as RNText,
TextInput as RNTextInput,
type TextInputProps as RNTextInputProps,
type TextProps as RNTextProps,
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
@@ -19,31 +17,24 @@ export function AppText({ className, ...props }: AppTextProps) {
return <RNText className={cn("font-sans text-foreground", className)} {...props} />;
}
export type AppTextInputProps = RNTextInputProps & {
export type AppTextInputProps = Omit<RNTextInputProps, "placeholderTextColor"> & {
readonly className?: string;
readonly ref?: Ref<RNTextInput>;
readonly ref?: React.Ref<RNTextInput>;
};
/**
* Thin wrapper around RN TextInput with default input styling.
* Uses Uniwind className — no manual style parsing.
*/
export function AppTextInput({
className,
placeholderTextColor,
ref,
...props
}: AppTextInputProps) {
const placeholderColor = useThemeColor("--color-placeholder");
export function AppTextInput({ className, ref, ...props }: AppTextInputProps) {
return (
<RNTextInput
ref={ref}
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
"min-h-13.5 rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
className,
)}
placeholderTextColor={placeholderTextColor ?? placeholderColor}
placeholderTextColorClassName="accent-placeholder"
{...props}
/>
);
+2 -7
View File
@@ -22,14 +22,9 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
/>
<View className="gap-1">
<View className="flex-row items-center gap-2">
<Text className="text-lg font-t3-bold text-foreground" style={{ letterSpacing: -0.4 }}>
T3 Code
</Text>
<Text className="text-lg font-t3-bold tracking-[-0.4px] text-foreground">T3 Code</Text>
<View className="rounded-full bg-subtle px-2 py-1">
<Text
className="text-3xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1.1 }}
>
<Text className="text-3xs font-t3-bold tracking-[1.1px] uppercase text-foreground-muted">
{stageLabel}
</Text>
</View>
@@ -39,14 +39,14 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
horizontal
showsHorizontalScrollIndicator={false}
keyboardShouldPersistTaps="always"
style={{ flexGrow: 0 }}
className="grow-0"
>
<View style={{ flexDirection: "row", gap: 10 }}>
<View className="flex-row gap-2.5">
{props.attachments.map((image) => (
<View
key={image.id}
className="relative"
style={{
position: "relative",
paddingTop: removeButtonGutter,
paddingRight: removeButtonGutter,
}}
@@ -66,16 +66,10 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
/>
</Pressable>
<Pressable
className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"
style={{
position: "absolute",
top: removeButtonPlacement === "gutter" ? 0 : 4,
right: removeButtonPlacement === "gutter" ? 0 : 4,
width: 22,
height: 22,
borderRadius: 11,
backgroundColor: "rgba(0,0,0,0.55)",
alignItems: "center",
justifyContent: "center",
}}
hitSlop={6}
onPress={() => props.onRemove(image.id)}
@@ -31,11 +31,9 @@ export function ComposerToolbarRow(props: {
}) {
return (
<View
className="flex-row items-center gap-1.5"
style={[
{
alignItems: "center",
flexDirection: "row",
gap: 6,
paddingBottom: props.paddingBottom ?? 8,
paddingHorizontal: props.paddingHorizontal ?? 6,
paddingTop: props.paddingTop ?? 8,
@@ -89,7 +87,7 @@ export function ComposerToolbarScroller(props: {
}, []);
return (
<View className="min-w-0 flex-1" style={{ position: "relative" }}>
<View className="relative min-w-0 flex-1">
<ScrollView
horizontal
keyboardShouldPersistTaps="always"
+1 -1
View File
@@ -75,7 +75,7 @@ export function ControlPill(props: {
}
export function ControlPillMenu(
props: Omit<ComponentProps<typeof MenuView>, "children" | "style" | "themeVariant"> & {
props: Omit<ComponentProps<typeof MenuView>, "children" | "themeVariant"> & {
readonly children: ReactNode;
},
) {
+23 -1
View File
@@ -7,11 +7,33 @@ export function EmptyState(props: {
readonly detail: string;
readonly actionLabel?: string;
readonly onAction?: () => void;
readonly variant?: "card" | "plain";
}) {
if (props.variant === "plain") {
return (
<View className="items-center px-8 py-8">
<Text className="text-center text-xl font-t3-bold text-foreground">{props.title}</Text>
<Text className="mt-2 text-center font-sans text-base leading-normal text-foreground-muted">
{props.detail}
</Text>
{props.actionLabel && props.onAction ? (
<Pressable
className="mt-5 rounded-full bg-primary px-5 py-3 active:opacity-70"
onPress={props.onAction}
>
<Text className="text-sm font-t3-bold text-primary-foreground">
{props.actionLabel}
</Text>
</Pressable>
) : null}
</View>
);
}
return (
<View className="rounded-[22px] border border-border bg-card p-5">
<Text className="font-t3-bold text-lg text-foreground">{props.title}</Text>
<Text className="mt-2 font-sans text-sm leading-[21px] text-foreground-muted">
<Text className="mt-2 font-sans text-sm leading-relaxed text-foreground-muted">
{props.detail}
</Text>
{props.actionLabel && props.onAction ? (
+1 -1
View File
@@ -4,7 +4,7 @@ import { AppText as Text } from "./AppText";
export function ErrorBanner(props: { readonly message: string }) {
return (
<View className="rounded-2xl border border-rose-300/70 bg-rose-100/80 px-3.5 py-3 dark:border-rose-400/28 dark:bg-rose-500/12">
<Text className="font-t3-medium text-sm leading-[18px] text-rose-700 dark:text-rose-300">
<Text className="font-t3-medium text-sm text-rose-700 dark:text-rose-300">
{props.message}
</Text>
</View>
@@ -39,22 +39,12 @@ export function GlassSafeAreaView({
style={{ borderRadius: 0, backgroundColor: "transparent" }}
>
<View
style={{
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 20,
paddingTop: headerPaddingTop,
paddingBottom: 16,
gap: 10,
}}
className="flex-row items-center gap-2.5 px-5 pb-4"
style={{ paddingTop: headerPaddingTop }}
>
<View style={{ alignItems: "flex-start", justifyContent: "center" }}>{leftSlot}</View>
<View
style={{ flex: 1, alignItems: "center", justifyContent: "center", overflow: "hidden" }}
>
{centerSlot}
</View>
<View style={{ alignItems: "flex-end", justifyContent: "center" }}>{rightSlot}</View>
<View className="items-start justify-center">{leftSlot}</View>
<View className="flex-1 items-center justify-center overflow-hidden">{centerSlot}</View>
<View className="items-end justify-center">{rightSlot}</View>
</View>
</GlassSurface>
</View>
+1 -1
View File
@@ -10,7 +10,7 @@ import {
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
export interface GlassSurfaceProps extends ViewProps {
export interface GlassSurfaceProps extends Omit<ViewProps, "className"> {
readonly children: ReactNode;
readonly glassEffectStyle?: "clear" | "regular" | "none";
readonly tintColor?: ColorValue;
@@ -1,6 +1,7 @@
import { SymbolView } from "expo-symbols";
import { Image } from "expo-image";
import { useState } from "react";
import { Image, View } from "react-native";
import { View } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import { useThemeColor } from "../lib/useThemeColor";
import { useAssetUrl } from "../state/assets";
@@ -78,7 +79,7 @@ function ProjectFaviconImage(props: {
borderRadius: props.size * 0.16,
...(showImage ? {} : { position: "absolute" as const, opacity: 0 }),
}}
resizeMode="contain"
contentFit="contain"
onLoad={() => {
if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
setStatus("loaded");
+25 -26
View File
@@ -10,6 +10,7 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as MobileSecureStorage from "../persistence/mobile-secure-storage";
import { migrateLegacyConnectionCatalog } from "./migration";
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
@@ -22,23 +23,22 @@ function catalogError(operation: string, cause: unknown) {
});
}
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
const decodeConnectionCatalogDocument = Schema.decodeEffect(ConnectionCatalogDocumentJson);
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => catalogError("decode", cause),
});
return yield* Effect.fromResult(
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
return yield* decodeConnectionCatalogDocument(raw).pipe(
Effect.mapError((cause) => catalogError("decode", cause)),
);
});
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
catalog: ConnectionCatalogDocumentType,
) {
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
return JSON.stringify(encoded);
return yield* encodeConnectionCatalogDocument(catalog).pipe(
Effect.mapError((cause) => catalogError("encode", cause)),
);
});
interface CatalogStore {
@@ -48,20 +48,19 @@ interface CatalogStore {
) => Effect.Effect<void, ConnectionTransientError>;
}
export interface SecureCatalogStorage {
readonly getItem: (key: string) => Effect.Effect<string | null, ConnectionTransientError>;
readonly setItem: (key: string, value: string) => Effect.Effect<void, ConnectionTransientError>;
readonly deleteItem: (key: string) => Effect.Effect<void, ConnectionTransientError>;
}
export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* (
storage: SecureCatalogStorage,
) {
export const make = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* () {
const storage = yield* MobileSecureStorage.MobileSecureStorage;
const getItem = (key: string) =>
storage.getItem(key).pipe(Effect.mapError((cause) => catalogError("load", cause)));
const setItem = (key: string, value: string) =>
storage.setItem(key, value).pipe(Effect.mapError((cause) => catalogError("save", cause)));
const deleteItem = (key: string) =>
storage.removeItem(key).pipe(Effect.mapError((cause) => catalogError("delete", cause)));
const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
const lock = yield* Semaphore.make(1);
const loadLegacyCatalog = Effect.fn("mobile.connectionStorage.loadLegacyCatalog")(function* () {
const legacyRaw = yield* storage.getItem(LEGACY_CONNECTIONS_KEY);
const legacyRaw = yield* getItem(LEGACY_CONNECTIONS_KEY);
const catalog =
legacyRaw === null || legacyRaw.trim() === ""
? EMPTY_CONNECTION_CATALOG_DOCUMENT
@@ -75,8 +74,8 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
);
if (legacyRaw !== null && legacyRaw.trim() !== "") {
const encoded = yield* encodeCatalog(catalog);
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
yield* storage.deleteItem(LEGACY_CONNECTIONS_KEY);
yield* setItem(CONNECTION_CATALOG_KEY, encoded);
yield* deleteItem(LEGACY_CONNECTIONS_KEY);
}
return catalog;
});
@@ -86,13 +85,13 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
if (Option.isSome(cached)) {
return cached.value;
}
const raw = yield* storage.getItem(CONNECTION_CATALOG_KEY);
const raw = yield* getItem(CONNECTION_CATALOG_KEY);
let catalog: ConnectionCatalogDocumentType;
if (raw !== null && raw.trim() !== "") {
catalog = yield* decodeCatalog(raw).pipe(
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(loadLegacyCatalog()),
),
),
@@ -111,7 +110,7 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
Effect.gen(function* () {
const next = transform(yield* loadUnlocked());
const encoded = yield* encodeCatalog(next);
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
yield* setItem(CONNECTION_CATALOG_KEY, encoded);
yield* Ref.set(state, Option.some(next));
}),
);
@@ -0,0 +1,97 @@
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-database";
import { make } from "./environment-cache-store";
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
const REFS: VcsListRefsResult = {
refs: [
{
name: "main",
current: true,
isDefault: true,
worktreePath: "/repo",
},
],
isRepo: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 1,
};
function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey: string) {
return `${environmentId}:${kind}:${cacheKey}`;
}
function makeDatabase() {
const values = new Map<string, string>();
const removed: Array<string> = [];
const database = MobileDatabase.of({
loadCache: (environmentId, kind, cacheKey) =>
Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) =>
Effect.sync(() => {
values.set(cacheId(environmentId, kind, cacheKey), payload);
}),
removeCache: (environmentId, kind, cacheKey) =>
Effect.sync(() => {
const id = cacheId(environmentId, kind, cacheKey);
removed.push(id);
values.delete(id);
}),
clearEnvironmentCache: (environmentId) =>
Effect.sync(() => {
for (const key of values.keys()) {
if (key.startsWith(`${environmentId}:`)) values.delete(key);
}
}),
clearAllCaches: Effect.sync(() => values.clear()),
inspectCaches: Effect.succeed([]),
loadPreferencesJson: Effect.succeed(Option.none()),
savePreferencesJson: () => Effect.void,
});
return { database, removed, values };
}
describe("mobile SQLite environment cache store", () => {
it.effect("round-trips schema-validated VCS refs", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.some(REFS));
}),
);
it.effect("deletes a corrupt cache record and treats it as a miss", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
const id = cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo");
memory.values.set(id, "{not-json");
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
expect(memory.removed).toEqual([id]);
}),
);
it.effect("clears one environment without touching another", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
const otherEnvironmentId = EnvironmentId.make("environment-2");
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
yield* store.clear(ENVIRONMENT_ID);
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
}),
);
});
@@ -0,0 +1,234 @@
import {
ConnectionPersistenceError,
EnvironmentCacheStore,
} from "@t3tools/client-runtime/platform";
import {
type EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
ServerConfig,
VcsListRefsResult,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as MobileDatabase from "../persistence/mobile-database";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
threadId: Schema.String,
snapshot: OrchestrationThreadDetailSnapshot,
});
const StoredServerConfig = Schema.Struct({
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
config: ServerConfig,
});
const StoredVcsRefs = Schema.Struct({
schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
cwd: Schema.String,
refs: VcsListRefsResult,
});
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredShellSnapshot),
);
const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredThreadSnapshot),
);
const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
const decodeStoredServerConfig = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredServerConfig),
);
const encodeStoredServerConfig = Schema.encodeEffect(Schema.fromJsonString(StoredServerConfig));
const decodeStoredVcsRefs = Schema.decodeUnknownEffect(Schema.fromJsonString(StoredVcsRefs));
const encodeStoredVcsRefs = Schema.encodeEffect(Schema.fromJsonString(StoredVcsRefs));
type CacheOperation = ConnectionPersistenceError["operation"];
function persistenceError(operation: CacheOperation, cause: unknown) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
function mapDatabaseError(operation: CacheOperation) {
return (error: MobileDatabase.MobileDatabaseError) => persistenceError(operation, error);
}
function loadDecodedCache<A, B>(input: {
readonly database: MobileDatabase.MobileDatabase["Service"];
readonly environmentId: EnvironmentId;
readonly kind: MobileDatabase.ClientCacheKind;
readonly cacheKey: string;
readonly operation: CacheOperation;
readonly decode: (raw: string) => Effect.Effect<A, unknown>;
readonly select: (value: A) => Option.Option<B>;
}): Effect.Effect<Option.Option<B>, ConnectionPersistenceError> {
return input.database.loadCache(input.environmentId, input.kind, input.cacheKey).pipe(
Effect.mapError(mapDatabaseError(input.operation)),
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<B>()),
onSome: (raw) =>
input.decode(raw).pipe(
Effect.map(input.select),
Effect.catch((cause) =>
Effect.logWarning("Discarding corrupt mobile client cache record.", {
environmentId: input.environmentId,
kind: input.kind,
cacheKey: input.cacheKey,
cause: String(cause),
}).pipe(
Effect.andThen(
input.database
.removeCache(input.environmentId, input.kind, input.cacheKey)
.pipe(Effect.catch(() => Effect.void)),
),
Effect.as(Option.none<B>()),
),
),
),
}),
),
);
}
export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
const database = yield* MobileDatabase.MobileDatabase;
return EnvironmentCacheStore.of({
loadShell: Effect.fn("MobileEnvironmentCache.loadShell")((environmentId) =>
loadDecodedCache({
database,
environmentId,
kind: "shell",
cacheKey: "snapshot",
operation: "load-shell",
decode: decodeStoredShellSnapshot,
select: (stored) =>
stored.environmentId === environmentId ? Option.some(stored.snapshot) : Option.none(),
}),
),
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
const payload = yield* encodeStoredShellSnapshot({
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
yield* database
.saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-shell")));
}),
loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
loadDecodedCache({
database,
environmentId,
kind: "thread",
cacheKey: threadId,
operation: "load-thread",
decode: decodeStoredThreadSnapshot,
select: (stored) =>
stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.snapshot)
: Option.none(),
}),
),
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
const threadId = snapshot.thread.id;
const payload = yield* encodeStoredThreadSnapshot({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
yield* database
.saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-thread")));
}),
removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
database
.removeCache(environmentId, "thread", threadId)
.pipe(Effect.mapError(mapDatabaseError("remove-thread"))),
),
loadServerConfig: Effect.fn("MobileEnvironmentCache.loadServerConfig")((environmentId) =>
loadDecodedCache({
database,
environmentId,
kind: "server-config",
cacheKey: "config",
operation: "load-server-config",
decode: decodeStoredServerConfig,
select: (stored) =>
stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
}),
),
saveServerConfig: Effect.fn("MobileEnvironmentCache.saveServerConfig")(
function* (environmentId, config) {
const payload = yield* encodeStoredServerConfig({
schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
environmentId,
config,
}).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
yield* database
.saveCache(
environmentId,
"server-config",
"config",
SERVER_CONFIG_CACHE_SCHEMA_VERSION,
payload,
)
.pipe(Effect.mapError(mapDatabaseError("save-server-config")));
},
),
loadVcsRefs: Effect.fn("MobileEnvironmentCache.loadVcsRefs")((environmentId, cwd) =>
loadDecodedCache({
database,
environmentId,
kind: "vcs-refs",
cacheKey: cwd,
operation: "load-vcs-refs",
decode: decodeStoredVcsRefs,
select: (stored) =>
stored.environmentId === environmentId && stored.cwd === cwd
? Option.some(stored.refs)
: Option.none(),
}),
),
saveVcsRefs: Effect.fn("MobileEnvironmentCache.saveVcsRefs")(
function* (environmentId, cwd, refs) {
const payload = yield* encodeStoredVcsRefs({
schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
environmentId,
cwd,
refs,
}).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
yield* database
.saveCache(environmentId, "vcs-refs", cwd, VCS_REFS_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-vcs-refs")));
},
),
clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) =>
database
.clearEnvironmentCache(environmentId)
.pipe(Effect.mapError(mapDatabaseError("clear-environment"))),
),
});
});
export const layer = Layer.effect(EnvironmentCacheStore, make());
+95 -80
View File
@@ -25,7 +25,8 @@ import * as Network from "expo-network";
import { AppState } from "react-native";
import { authClientMetadata } from "../lib/authClientMetadata";
import { loadOrCreateAgentAwarenessDeviceId } from "../lib/storage";
import * as Runtime from "../lib/runtime";
import * as MobileStorage from "../persistence/mobile-storage";
import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
@@ -83,82 +84,87 @@ const wakeupsLayer = Wakeups.layer({
),
});
const capabilitiesLayer = Layer.succeedContext(
Context.make(
CloudSession,
CloudSession.of({
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Cloud to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
Effect.mapError(
(error) =>
new ConnectionTransientError({
reason: "network",
detail: error.message,
const capabilitiesLayer = Layer.effectContext(
Effect.gen(function* () {
const storage = yield* MobileStorage.MobileStorage;
return Context.make(
CloudSession,
CloudSession.of({
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Connect to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
Effect.mapError(
(error) =>
new ConnectionTransientError({
reason: "network",
detail: error.message,
}),
),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Connect session is unavailable.",
});
}
return token;
}),
}),
).pipe(
Context.add(
PrimaryEnvironmentAuth,
PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
),
Context.add(
RelayDeviceIdentity,
RelayDeviceIdentity.of({
deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.mapError(
(cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not load the mobile device identity: ${String(cause)}`,
}),
),
Effect.map(Option.some),
),
}),
),
Context.add(
ClientPresentation,
ClientPresentation.of({
metadata: authClientMetadata(),
scopes: AuthStandardClientScopes,
}),
),
Context.add(
SshEnvironmentGateway,
SshEnvironmentGateway.of({
provision: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
});
}
return token;
}),
}),
).pipe(
Context.add(
PrimaryEnvironmentAuth,
PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
),
Context.add(
RelayDeviceIdentity,
RelayDeviceIdentity.of({
deviceId: Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not load the mobile device identity: ${String(cause)}`,
}),
}).pipe(Effect.map(Option.some)),
}),
),
Context.add(
ClientPresentation,
ClientPresentation.of({
metadata: authClientMetadata(),
scopes: AuthStandardClientScopes,
}),
),
Context.add(
SshEnvironmentGateway,
SshEnvironmentGateway.of({
provision: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
prepare: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
disconnect: () => Effect.void,
}),
),
),
),
prepare: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
disconnect: () => Effect.void,
}),
),
);
}),
);
const platformConnectionSourceLayer = Layer.succeed(
@@ -168,6 +174,13 @@ const platformConnectionSourceLayer = Layer.succeed(
}),
);
const providedConnectionStorageLayer = connectionStorageLayer.pipe(
Layer.provide(Runtime.runtimeContextLayer),
);
const providedCapabilitiesLayer = capabilitiesLayer.pipe(
Layer.provide(Runtime.runtimeContextLayer),
);
const environmentOwnedDataCleanupLayer = Layer.succeed(
EnvironmentOwnedDataCleanup,
EnvironmentOwnedDataCleanup.of({
@@ -190,10 +203,11 @@ const environmentOwnedDataCleanupLayer = Layer.succeed(
);
type ConnectionPlatformLayerSource =
| typeof connectionStorageLayer
| typeof providedConnectionStorageLayer
| typeof Runtime.runtimeContextLayer
| typeof connectivityLayer
| typeof wakeupsLayer
| typeof capabilitiesLayer
| typeof providedCapabilitiesLayer
| typeof platformConnectionSourceLayer
| typeof environmentOwnedDataCleanupLayer;
@@ -202,10 +216,11 @@ export const connectionPlatformLayer: Layer.Layer<
Layer.Error<ConnectionPlatformLayerSource>,
Layer.Services<ConnectionPlatformLayerSource>
> = Layer.mergeAll(
connectionStorageLayer,
providedConnectionStorageLayer,
Runtime.runtimeContextLayer,
connectivityLayer,
wakeupsLayer,
capabilitiesLayer,
providedCapabilitiesLayer,
platformConnectionSourceLayer,
environmentOwnedDataCleanupLayer,
);
+6 -1
View File
@@ -1,4 +1,6 @@
import { Connection } from "@t3tools/client-runtime/connection";
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
@@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
type ConnectionLayerSource =
| typeof Connection.layer
| typeof snapshotLoaderLayer
| typeof runtimeContextLayer
| typeof connectionPlatformLayer;
const connectionLayer = Connection.layer.pipe(
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
);
+25 -12
View File
@@ -1,28 +1,35 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { vi } from "vite-plus/test";
import {
CONNECTION_CATALOG_KEY,
LEGACY_CONNECTIONS_KEY,
makeCatalogStore,
type SecureCatalogStorage,
} from "./catalog-store";
vi.mock("react-native", () => ({
Platform: { OS: "ios" },
}));
vi.mock("expo-secure-store", () => ({
deleteItemAsync: vi.fn(),
getItemAsync: vi.fn(),
setItemAsync: vi.fn(),
}));
import { CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY, make } from "./catalog-store";
import { MobileSecureStorage } from "../persistence/mobile-secure-storage";
function makeStorage(initial: Readonly<Record<string, string>>) {
const values = new Map(Object.entries(initial));
const deleted: Array<string> = [];
const storage: SecureCatalogStorage = {
const storage = MobileSecureStorage.of({
getItem: (key) => Effect.sync(() => values.get(key) ?? null),
setItem: (key, value) =>
Effect.sync(() => {
values.set(key, value);
}),
deleteItem: (key) =>
removeItem: (key) =>
Effect.sync(() => {
deleted.push(key);
values.delete(key);
}),
};
});
return { deleted, storage, values };
}
@@ -32,7 +39,9 @@ describe("mobile connection catalog storage", () => {
const memory = makeStorage({
[CONNECTION_CATALOG_KEY]: "{not-json",
});
const catalog = yield* makeCatalogStore(memory.storage);
const catalog = yield* make().pipe(
Effect.provideService(MobileSecureStorage, memory.storage),
);
expect((yield* catalog.read).targets).toEqual([]);
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY]);
@@ -44,7 +53,9 @@ describe("mobile connection catalog storage", () => {
const memory = makeStorage({
[LEGACY_CONNECTIONS_KEY]: JSON.stringify({ connections: [{ invalid: true }] }),
});
const catalog = yield* makeCatalogStore(memory.storage);
const catalog = yield* make().pipe(
Effect.provideService(MobileSecureStorage, memory.storage),
);
expect((yield* catalog.read).targets).toEqual([]);
expect(memory.deleted).toEqual([LEGACY_CONNECTIONS_KEY]);
@@ -71,7 +82,9 @@ describe("mobile connection catalog storage", () => {
],
}),
});
const catalog = yield* makeCatalogStore(memory.storage);
const catalog = yield* make().pipe(
Effect.provideService(MobileSecureStorage, memory.storage),
);
expect((yield* catalog.read).targets).toHaveLength(1);
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY]);
+2 -296
View File
@@ -2,7 +2,6 @@ import {
ConnectionPersistenceError,
ConnectionRegistrationStore,
ConnectionTargetStore,
EnvironmentCacheStore,
registerConnectionInCatalog,
removeConnectionFromCatalog,
removeCatalogValue,
@@ -14,108 +13,11 @@ import {
CredentialStore,
ProfileStore,
} from "@t3tools/client-runtime/connection";
import {
EnvironmentId,
OrchestrationThread,
OrchestrationShellSnapshot,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
thread: OrchestrationThread,
});
const LegacyStoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
environmentId: EnvironmentId,
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
}
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
function* (
environmentId: EnvironmentId,
operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(
Paths.document,
THREAD_SNAPSHOT_CACHE_DIRECTORY,
encodeURIComponent(environmentId),
);
if (operation !== "clear-environment") {
directory.create({ idempotent: true, intermediates: true });
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
});
},
);
const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* (
environmentId: EnvironmentId,
threadId: ThreadId,
operation: "load-thread" | "save-thread" | "remove-thread",
) {
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(
yield* threadSnapshotDirectory(environmentId, operation),
threadSnapshotFileName(threadId),
);
});
import * as CatalogStore from "./catalog-store";
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
@@ -127,59 +29,9 @@ function targetPersistenceError(
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.getItemAsync(key),
catch: (cause) => catalogError("load", cause),
}),
setItem: (key, value) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(key, value),
catch: (cause) => catalogError("save", cause),
}),
deleteItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(key),
catch: (cause) => catalogError("delete", cause),
}),
};
function shellSnapshotFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
const shellSnapshotFileInDirectory = Effect.fn(
"mobile.connectionStorage.shellSnapshotFileInDirectory",
)(function* (
environmentId: EnvironmentId,
operation: "load-shell" | "save-shell" | "clear-environment",
directoryName: string,
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, directoryName);
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const shellSnapshotFile = (
environmentId: EnvironmentId,
operation: "load-shell" | "save-shell" | "clear-environment",
) => shellSnapshotFileInDirectory(environmentId, operation, SHELL_SNAPSHOT_CACHE_DIRECTORY);
const legacyShellSnapshotFile = (
environmentId: EnvironmentId,
operation: "load-shell" | "clear-environment",
) => shellSnapshotFileInDirectory(environmentId, operation, LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY);
export const connectionStorageLayer = Layer.effectContext(
Effect.gen(function* () {
const catalog = yield* makeCatalogStore(secureCatalogStorage);
const catalog = yield* CatalogStore.make();
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
@@ -276,157 +128,11 @@ export const connectionStorageLayer = Layer.effectContext(
),
})),
});
const cacheStore = EnvironmentCacheStore.of({
loadShell: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "load-shell");
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
if (!legacyFile.exists) {
return Option.none();
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
}),
saveShell: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "save-shell");
const stored = {
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
}),
saveThread: (environmentId, thread) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
if (file.exists) {
file.delete();
}
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
),
),
clear: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
environmentId,
"clear-environment",
);
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
});
return Context.make(ConnectionTargetStore, targetStore).pipe(
Context.add(ConnectionRegistrationStore, registrationStore),
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
Context.add(EnvironmentCacheStore, cacheStore),
);
}),
);
@@ -7,21 +7,30 @@ import * as Layer from "effect/Layer";
import { HttpClient } from "effect/unstable/http";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { MobileStorage } from "../../persistence/mobile-storage";
import {
CloudEnvironmentLinkError,
linkEnvironmentToCloudWithPreference,
} from "../cloud/linkEnvironment";
import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";
vi.mock("../../lib/storage", () => ({
savePreferencesPatch: vi.fn(() => Promise.resolve()),
vi.mock("expo-secure-store", () => ({
deleteItemAsync: vi.fn(),
getItemAsync: vi.fn(),
setItemAsync: vi.fn(),
}));
vi.mock("react-native", () => ({
Platform: { OS: "ios" },
}));
vi.mock("../cloud/linkEnvironment", () => ({
linkEnvironmentToCloud: vi.fn(() => Effect.void),
linkEnvironmentToCloudWithPreference: vi.fn(() => Effect.void),
}));
vi.mock("./remoteRegistration", () => ({
refreshAgentAwarenessRegistration: vi.fn(() => Effect.void),
updateAgentAwarenessRegistrationPreferences: vi.fn(() => Effect.void),
}));
const connection: SavedRemoteConnection = {
@@ -40,6 +49,19 @@ const testLayer = Layer.mergeAll(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
Layer.succeed(
MobileStorage,
MobileStorage.of({
loadSavedConnections: Effect.succeed([]),
saveConnection: () => Effect.void,
clearSavedConnection: () => Effect.void,
loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
saveAgentAwarenessRegistrationRecord: () => Effect.void,
clearAgentAwarenessRegistrationRecord: Effect.void,
}),
),
);
describe("liveActivityPreferences", () => {
@@ -51,15 +73,18 @@ describe("liveActivityPreferences", () => {
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
liveActivitiesEnabled: false,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: false,
});
}).pipe(Effect.provide(testLayer)),
);
@@ -68,15 +93,18 @@ describe("liveActivityPreferences", () => {
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: true,
previousEnabled: false,
clerkToken: "clerk-token",
connections: [connection],
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
liveActivitiesEnabled: true,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(testLayer)),
);
@@ -85,13 +113,15 @@ describe("liveActivityPreferences", () => {
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: true,
clerkToken: null,
connections: [connection],
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
liveActivitiesEnabled: false,
});
expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
}).pipe(Effect.provide(testLayer)),
);
@@ -104,14 +134,51 @@ describe("liveActivityPreferences", () => {
return Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: true,
previousEnabled: false,
clerkToken: "clerk-token",
connections: [connection, managedConnection],
});
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(testLayer));
});
it.effect("restores relay preferences when an environment update fails", () => {
vi.mocked(linkEnvironmentToCloudWithPreference).mockImplementationOnce(() =>
Effect.fail(new CloudEnvironmentLinkError({ message: "environment update failed" })),
);
return Effect.gen(function* () {
const exit = yield* Effect.exit(
setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
}),
);
expect(exit._tag).toBe("Failure");
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(1, {
liveActivitiesEnabled: false,
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(2, {
liveActivitiesEnabled: true,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(1, {
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: false,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(2, {
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(testLayer));
});
@@ -1,47 +1,73 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
import { linkEnvironmentToCloudWithPreference } from "../cloud/linkEnvironment";
import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";
export class LiveActivityPreferenceSaveError extends Schema.TaggedErrorClass<LiveActivityPreferenceSaveError>()(
"LiveActivityPreferenceSaveError",
{
enabled: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to save the Live Activity updates setting (enabled: ${this.enabled}).`;
}
}
export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(
function* (input: {
readonly enabled: boolean;
readonly previousEnabled: boolean;
readonly clerkToken: string | null;
readonly connections: ReadonlyArray<SavedRemoteConnection>;
}) {
const linkedConnections = input.connections.filter(
(connection) => connection.bearerToken !== null,
);
export function setLiveActivityUpdatesEnabled(input: {
readonly enabled: boolean;
readonly clerkToken: string | null;
readonly connections: ReadonlyArray<SavedRemoteConnection>;
}): Effect.Effect<void, unknown, HttpClient.HttpClient | ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
yield* Effect.tryPromise({
try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }),
catch: (cause) => new LiveActivityPreferenceSaveError({ enabled: input.enabled, cause }),
const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) {
yield* updateAgentAwarenessRegistrationPreferences({
liveActivitiesEnabled: enabled,
});
const clerkToken = input.clerkToken;
if (!clerkToken) return;
yield* Effect.forEach(
linkedConnections,
(connection) =>
linkEnvironmentToCloudWithPreference({
clerkToken,
connection,
liveActivitiesEnabled: enabled,
}),
{ concurrency: "unbounded" },
);
});
yield* refreshAgentAwarenessRegistration();
const restoreRelayPreference = Effect.fn("restoreRelayPreference")(function* () {
yield* updateAgentAwarenessRegistrationPreferences({
liveActivitiesEnabled: input.previousEnabled,
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Could not restore Live Activity device preference.", cause),
),
);
const clerkToken = input.clerkToken;
if (!clerkToken) {
return;
}
const clerkToken = input.clerkToken;
if (!clerkToken) return;
yield* Effect.forEach(
input.connections.filter((connection) => connection.bearerToken !== null),
(connection) => linkEnvironmentToCloud({ clerkToken, connection }),
{ concurrency: "unbounded" },
yield* Effect.forEach(
linkedConnections,
(connection) =>
linkEnvironmentToCloudWithPreference({
clerkToken,
connection,
liveActivitiesEnabled: input.previousEnabled,
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
`Could not restore Live Activity preference for environment ${connection.environmentId}.`,
cause,
),
),
),
{ concurrency: "unbounded" },
);
});
yield* updateRelayPreference(input.enabled).pipe(
Effect.onError(() => restoreRelayPreference()),
);
});
}
},
);
@@ -1,12 +1,12 @@
import { useEffect, useRef } from "react";
import * as Notifications from "expo-notifications";
import { useRouter } from "expo-router";
import { useLinkTo } from "@react-navigation/native";
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
export function useAgentNotificationNavigation(): void {
const router = useRouter();
const linkTo = useLinkTo();
const handledResponseIds = useRef(new Set<string>());
useEffect(() => {
@@ -14,7 +14,7 @@ export function useAgentNotificationNavigation(): void {
routeAgentNotificationResponseOnce({
handledResponseIds: handledResponseIds.current,
response,
navigate: (deepLink) => router.push(deepLink as never),
navigate: linkTo,
});
};
@@ -28,5 +28,5 @@ export function useAgentNotificationNavigation(): void {
return () => {
subscription.remove();
};
}, [router]);
}, [linkTo]);
}
@@ -1,12 +1,21 @@
import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
import type { Preferences } from "../../lib/storage";
import type { Preferences } from "../../persistence/mobile-preferences";
// Development builds are Xcode-signed and receive sandbox APNs tokens;
// preview and production builds are distribution-signed and use production
// APNs. The relay routes each device's pushes accordingly.
export function resolveApsEnvironment(appVariant: unknown): "sandbox" | "production" {
return appVariant === "development" ? "sandbox" : "production";
}
export function makeRelayDeviceRegistrationRequest(input: {
readonly deviceId: string;
readonly label: string;
readonly iosMajorVersion: number;
readonly appVersion?: string;
readonly bundleId?: string;
readonly apsEnvironment?: "sandbox" | "production";
readonly pushToken?: string;
readonly pushToStartToken?: string;
readonly notificationsEnabled: boolean;
@@ -19,6 +28,8 @@ export function makeRelayDeviceRegistrationRequest(input: {
platform: "ios",
iosMajorVersion: input.iosMajorVersion,
appVersion: input.appVersion,
...(input.bundleId ? { bundleId: input.bundleId } : {}),
...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}),
...(input.pushToken ? { pushToken: input.pushToken } : {}),
...(input.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
preferences: {
@@ -16,15 +16,24 @@ import { verifyDpopProof } from "@t3tools/shared/dpop";
import type { SavedRemoteConnection } from "../../lib/connection";
import { cryptoLayer } from "../cloud/dpop";
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
clearAgentAwarenessRegistrationRecord,
loadAgentAwarenessRegistrationRecord,
loadOrCreateAgentAwarenessDeviceId,
saveAgentAwarenessRegistrationRecord,
} from "../../persistence/imperative";
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
import {
AgentAwarenessOperationError,
__resetAgentAwarenessRemoteRegistrationForTest,
getAgentAwarenessRegistrationStatus,
mergeAgentAwarenessRegistrationPreferences,
refreshActiveLiveActivityRemoteRegistration,
refreshAgentAwarenessRegistration,
normalizeAgentAwarenessRelayBaseUrl,
registerAgentAwarenessConnection,
registerLiveActivityPushToken,
releaseAgentAwarenessRelayTokenProvider,
setAgentAwarenessRelayTokenProvider,
shouldRegisterAgentAwarenessDeviceForProvider,
unregisterAgentAwarenessConnection,
@@ -41,6 +50,16 @@ const backgroundRuntime = vi.hoisted(() => ({
readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
}>,
}));
const appStateMock = vi.hoisted(() => ({
listeners: [] as Array<(state: string) => void>,
}));
const registrationRecordStore = vi.hoisted(() => ({
current: null as {
readonly identity: string;
readonly signature: string;
readonly pushToStartToken?: string;
} | null,
}));
vi.mock("expo-constants", () => ({
default: {
@@ -100,6 +119,19 @@ vi.mock("react-native", () => ({
OS: "ios",
Version: "18.0",
},
AppState: {
addEventListener: (_event: string, listener: (state: string) => void) => {
appStateMock.listeners.push(listener);
return {
remove: () => {
const index = appStateMock.listeners.indexOf(listener);
if (index >= 0) {
appStateMock.listeners.splice(index, 1);
}
},
};
},
},
}));
vi.mock("../../lib/runtime", () => ({
@@ -111,10 +143,21 @@ vi.mock("../../lib/runtime", () => ({
},
}));
vi.mock("../../lib/storage", () => ({
vi.mock("../../persistence/imperative", () => ({
loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadPreferences: vi.fn(() => Promise.resolve({})),
loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),
loadAgentAwarenessRegistrationRecord: vi.fn(() =>
Promise.resolve(registrationRecordStore.current),
),
saveAgentAwarenessRegistrationRecord: vi.fn((record: { identity: string; signature: string }) => {
registrationRecordStore.current = record;
return Promise.resolve();
}),
clearAgentAwarenessRegistrationRecord: vi.fn(() => {
registrationRecordStore.current = null;
return Promise.resolve();
}),
}));
function proofIat(proof: string): number {
@@ -176,6 +219,12 @@ describe("makeRelayDeviceRegistrationRequest", () => {
backgroundRuntime.pending.length = 0;
Constants.expoConfig!.extra = {};
__resetAgentAwarenessRemoteRegistrationForTest();
appStateMock.listeners.length = 0;
registrationRecordStore.current = null;
vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();
vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
widgetMocks.getInstances.mockReset();
widgetMocks.getInstances.mockReturnValue([]);
});
@@ -213,6 +262,31 @@ describe("makeRelayDeviceRegistrationRequest", () => {
});
});
it("registers the app's APNs routing so the relay targets the right bundle", () => {
expect(
makeRelayDeviceRegistrationRequest({
deviceId: "device-1",
label: "Julius's iPhone",
iosMajorVersion: 18,
appVersion: "1.0.0",
bundleId: "com.t3tools.t3code.preview",
apsEnvironment: resolveApsEnvironment("preview"),
notificationsEnabled: true,
preferences: {},
}),
).toMatchObject({
bundleId: "com.t3tools.t3code.preview",
apsEnvironment: "production",
});
});
it("routes development builds to the APNs sandbox", () => {
expect(resolveApsEnvironment("development")).toBe("sandbox");
expect(resolveApsEnvironment("preview")).toBe("production");
expect(resolveApsEnvironment("production")).toBe("production");
expect(resolveApsEnvironment(undefined)).toBe("production");
});
it("marks notification delivery disabled when APNs permission is unavailable", () => {
expect(
makeRelayDeviceRegistrationRequest({
@@ -251,6 +325,15 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull();
});
it("overrides persisted preferences for an in-flight registration", () => {
expect(
mergeAgentAwarenessRegistrationPreferences(
{ liveActivitiesEnabled: false, baseFontSize: 18 },
{ liveActivitiesEnabled: true },
),
).toEqual({ liveActivitiesEnabled: true, baseFontSize: 18 });
});
it.effect("registers at most one listener while a Live Activity push token is pending", () => {
registerAgentAwarenessConnection(savedConnection());
const addPushTokenListener = vi.fn();
@@ -329,6 +412,53 @@ describe("makeRelayDeviceRegistrationRequest", () => {
},
);
it.effect(
"re-registers active Live Activity tokens when the app returns to the foreground",
() => {
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* runBackgroundOperations();
activity.getPushToken.mockClear();
expect(appStateMock.listeners).toHaveLength(1);
for (const listener of appStateMock.listeners) {
listener("background");
}
yield* runBackgroundOperations();
expect(activity.getPushToken).not.toHaveBeenCalled();
for (const listener of appStateMock.listeners) {
listener("active");
}
yield* runBackgroundOperations();
expect(activity.getPushToken).toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
},
);
it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {
const end = vi.fn(() => Promise.resolve());
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
end,
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
expect(appStateMock.listeners).toHaveLength(1);
setAgentAwarenessRelayTokenProvider(null);
expect(end).toHaveBeenCalledWith("immediate");
expect(appStateMock.listeners).toHaveLength(0);
});
it.effect("refreshes APNs registration for connected environments after settings changes", () => {
registerAgentAwarenessConnection(savedConnection());
return Effect.gen(function* () {
@@ -395,6 +525,174 @@ describe("makeRelayDeviceRegistrationRequest", () => {
nowEpochSeconds: proofIat(dpop),
}),
).toMatchObject({ ok: true });
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("marks registration failed when device registration cannot complete", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
new Error("registration failed"),
);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
// Drive the registration directly so the assertion does not depend on the
// background queue draining; refreshAgentAwarenessRegistration swallows the
// error but must record the failed status so the settings toggles cannot
// read as enabled.
yield* refreshAgentAwarenessRegistration();
expect(getAgentAwarenessRegistrationStatus()).toBe("failed");
}).pipe(Effect.provide(relayTestLayer));
});
it("clears registration status on cloud sign-out", () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
setAgentAwarenessRelayTokenProvider(null);
expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
expect(clearAgentAwarenessRegistrationRecord).toHaveBeenCalled();
});
it("releases the provider without ending activities or clearing the registration", () => {
const end = vi.fn(() => Promise.resolve());
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
end,
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
registrationRecordStore.current = { identity: "", signature: "sig" };
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
expect(appStateMock.listeners).toHaveLength(1);
releaseAgentAwarenessRelayTokenProvider();
expect(appStateMock.listeners).toHaveLength(0);
expect(end).not.toHaveBeenCalled();
expect(clearAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
expect(registrationRecordStore.current).not.toBeNull();
});
it.effect("resets a pending status to unknown when relay config is missing", () => {
// No relay url configured: registration can neither run nor ever succeed,
// so the status must not stick at "pending".
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("keeps a registered status when a later refresh fails", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
// The relay still holds the accepted registration; a transient refresh
// failure must not flip the settings toggles off.
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
new Error("transient failure"),
);
yield* refreshAgentAwarenessRegistration();
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("does not re-register the same account when nothing has changed", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* refreshAgentAwarenessRegistration();
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
expect(registrationRecordStore.current).not.toBeNull();
// Second attempt with an identical payload must skip the relay entirely,
// so no new registration record is written.
vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
yield* refreshAgentAwarenessRegistration();
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("dedupes rapid activity-token re-registrations within the replay window", () => {
// Fetch counts are unreliable here (the module-level relay layer captures
// the first test's fetch), so assert on the flow's own seams: a real
// registration attempt loads the device id, a deduped one short-circuits
// before it.
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/",
},
};
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
// Drains the sign-in refresh, which registers the activity token.
yield* runBackgroundOperations();
expect(activity.getPushToken).toHaveBeenCalled();
// A burst refresh (foreground / connection update seconds later) must
// dedupe: it reads the token but never proceeds to a registration
// attempt (which would load the device id first).
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockClear();
yield* refreshActiveLiveActivityRemoteRegistration();
expect(loadOrCreateAgentAwarenessDeviceId).not.toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("re-registers when the stored account identity differs", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
registrationRecordStore.current = { identity: "someone-else", signature: "stale" };
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* refreshAgentAwarenessRegistration();
expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
});
@@ -1,12 +1,13 @@
import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
import { type LiveActivity } from "expo-widgets";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Platform } from "react-native";
import { AppState, Platform } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import {
type RelayDeviceRegistrationRequest,
type RelayAgentActivitySnapshotResponse,
type RelayLiveActivityRegistrationRequest,
} from "@t3tools/contracts/relay";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
@@ -19,14 +20,18 @@ import {
import type { SavedRemoteConnection } from "../../lib/connection";
import { runtime } from "../../lib/runtime";
import type { Preferences } from "../../persistence/mobile-preferences";
import {
clearAgentAwarenessRegistrationRecord,
loadAgentAwarenessDeviceId,
loadAgentAwarenessRegistrationRecord,
loadOrCreateAgentAwarenessDeviceId,
loadPreferences,
} from "../../lib/storage";
saveAgentAwarenessRegistrationRecord,
} from "../../persistence/imperative";
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
@@ -42,6 +47,8 @@ const AgentAwarenessOperation = Schema.Literals([
"read-live-activity-push-token",
"load-live-activity-registration-identifier",
"list-active-live-activities",
"load-live-activity-prime-preferences",
"prime-live-activity",
]);
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
@@ -58,8 +65,49 @@ export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentA
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
let pushToStartSubscription: { remove: () => void } | null = null;
// Activity tokens the relay recently accepted, by acceptance time. The refresh
// runs on sign-in, every app foreground, and every environment-connection
// update, which arrive in bursts and spammed identical registrations. But the
// registration is not a pure no-op: the relay replays the current aggregate to
// this device on every accepted registration, and that replay is the
// foreground reconciliation that repairs drifted or orphaned activities. So
// dedupe only within a short window — bursts collapse to one request, while a
// foreground after real time away still triggers a replay. Cleared on
// sign-out/identity change alongside the device registration state.
const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
const registeredActivityPushTokens = new Map<string, number>();
let pushTokenSubscription: { remove: () => void } | null = null;
let appStateSubscription: { remove: () => void } | null = null;
// Whether the relay has actually accepted this device's registration. The
// notification/Live Activity settings toggles must reflect this rather than
// only local iOS permission or saved preferences: if the registration request
// never succeeded, the device cannot receive anything, so the switches must
// not read as enabled.
export type AgentAwarenessRegistrationStatus = "unknown" | "pending" | "registered" | "failed";
let registrationStatus: AgentAwarenessRegistrationStatus = "unknown";
const registrationStatusListeners = new Set<() => void>();
function setRegistrationStatus(next: AgentAwarenessRegistrationStatus): void {
if (registrationStatus === next) {
return;
}
registrationStatus = next;
for (const listener of registrationStatusListeners) {
listener();
}
}
export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistrationStatus {
return registrationStatus;
}
export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void {
registrationStatusListeners.add(listener);
return () => {
registrationStatusListeners.delete(listener);
};
}
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
let relayTokenProvider: (() => Promise<string | null>) | null = null;
let relayTokenProviderIdentity: string | null = null;
@@ -74,10 +122,20 @@ let pendingDeviceRegistration: {
} | null = null;
interface DeviceRegistrationInput {
readonly pushToStartToken?: string;
readonly observedPushToken?: string;
}
interface RegisterDeviceInput extends DeviceRegistrationInput {
readonly preferencesOverride?: Partial<Preferences>;
}
export function mergeAgentAwarenessRegistrationPreferences(
stored: Preferences,
override: Partial<Preferences> | undefined,
): Preferences {
return { ...stored, ...override };
}
export function normalizeAgentAwarenessRelayBaseUrl(
value: string | null | undefined,
): string | null {
@@ -120,32 +178,66 @@ export function setAgentAwarenessRelayTokenProvider(
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
registeredActivityPushTokens.clear();
}
relayTokenProvider = provider;
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
if (!provider) {
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
appStateSubscription?.remove();
appStateSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
// Without a signed-in user the relay can no longer update or end these
// activities, so they would sit orphaned on the lock screen.
endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
setRegistrationStatus("unknown");
// Sign-out is the only thing that invalidates a stored registration, so the
// next sign-in re-registers.
void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
logRegistrationError("clear registration record on sign-out failed", error);
});
return;
}
ensurePushToStartListener();
ensurePushTokenListener();
ensureAppStateListener();
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity registration after cloud sign-in failed",
);
if (isExistingIdentity) {
// Same account re-activating (e.g. Clerk token refresh) normally needs no
// re-registration — but if the previous attempt never succeeded, this is
// the only trigger that will retry it before the next cold start.
if (registrationStatus !== "registered") {
enqueueDeviceRegistration({}, "device registration retry after cloud session refresh failed");
}
return;
}
enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
}
// Detach the provider and native listeners without the destructive sign-out
// cleanup. For provider teardown while the user is still signed in (e.g. the
// auth bridge unmounting/remounting), ending lock-screen activities and wiping
// the persisted registration would be wrong — the relay still holds a valid
// registration and the next mount reuses it.
export function releaseAgentAwarenessRelayTokenProvider(): void {
relayTokenProvider = null;
relayTokenProviderIdentity = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
appStateSubscription?.remove();
appStateSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
}
function iosMajorVersion(): number {
const version = Platform.Version;
if (typeof version === "number") {
@@ -211,6 +303,27 @@ const relayToken = (
});
});
// Stable fingerprint of everything the relay stores for this device. When it
// matches the last accepted registration for the same account, re-registering
// is a no-op, so a launch that changed nothing skips the request entirely.
function registrationSignature(body: RelayDeviceRegistrationRequest): string {
return [
body.deviceId,
body.pushToken ?? "",
body.bundleId ?? "",
body.apsEnvironment ?? "",
body.appVersion ?? "",
body.label,
body.iosMajorVersion,
body.preferences.notificationsEnabled,
body.preferences.liveActivitiesEnabled,
body.preferences.notifyOnApproval,
body.preferences.notifyOnInput,
body.preferences.notifyOnCompletion,
body.preferences.notifyOnFailure,
].join("|");
}
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
expectedGeneration: number,
@@ -223,7 +336,13 @@ function registerDeviceWithRelay(
});
return;
}
if (!readRelayConfig()) return;
const relayConfig = readRelayConfig();
if (!relayConfig) {
// Nothing is in flight and nothing can succeed until configuration
// appears; "pending" would otherwise stick forever.
setRegistrationStatus("unknown");
return;
}
const token = yield* relayToken("read-device-registration-relay-token");
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled after auth lookup", {
@@ -234,6 +353,37 @@ function registerDeviceWithRelay(
}
if (!token) {
logRegistrationDebug("relay device registration skipped; user is not signed in");
setRegistrationStatus("unknown");
return;
}
// Skip the request when this account already registered an identical
// payload; the relay upsert would be a no-op. The record is only cleared on
// sign-out, so a device stays registered across launches without re-hitting
// the relay every time the app opens.
const identity = relayTokenProviderIdentity ?? "";
const persisted = yield* Effect.tryPromise({
try: () => loadAgentAwarenessRegistrationRecord(),
catch: (cause) => cause,
}).pipe(Effect.orElseSucceed(() => null));
if (expectedGeneration !== deviceRegistrationGeneration) {
// Signed out while the record loaded — do not resurrect the cleared
// record or report the previous account's registration as current.
logRegistrationDebug("device registration cancelled after record lookup", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
const payload = body;
// The relay URL participates so pointing the app at a different relay
// invalidates the record and re-registers there.
const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
if (persisted && persisted.identity === identity && persisted.signature === signature) {
setRegistrationStatus("registered");
logRegistrationDebug("relay device registration skipped; already registered for account", {
expectedGeneration,
});
return;
}
@@ -243,8 +393,27 @@ function registerDeviceWithRelay(
});
yield* client.registerDevice({
clerkToken: token,
payload: body,
payload,
});
if (expectedGeneration !== deviceRegistrationGeneration) {
// Signed out while the request was in flight: the sign-out path already
// reset the status and cleared the record for the next account, so a
// stale success must not overwrite either.
logRegistrationDebug("device registration completed after sign-out; result discarded", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
setRegistrationStatus("registered");
yield* Effect.promise(() =>
saveAgentAwarenessRegistrationRecord({
identity,
signature,
}).catch((error: unknown) => {
logRegistrationError("persist registration record failed", error);
}),
);
logRegistrationDebug("relay device registration request completed", {
expectedGeneration,
});
@@ -278,6 +447,91 @@ function unregisterDeviceWithRelay(input: {
});
}
// Arms the lock-screen card the moment the user starts agent work from this
// phone, while the app is still foregrounded and the fresh activity's token
// can be registered immediately. The seeded row is a best-effort placeholder;
// the relay's registration replay repaints it with the authoritative
// aggregate within seconds. No-ops when a card is already armed.
export function armAgentAwarenessLiveActivityForLocalWork(input: {
readonly threadTitle: string;
readonly projectTitle: string;
}): void {
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
return;
}
void loadPreferences()
.catch(() => null)
.then((preferences) => {
if (preferences?.liveActivitiesEnabled === false) {
return;
}
armAgentAwarenessLiveActivityForLocalWorkNow(input);
});
}
function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
readonly threadTitle: string;
readonly projectTitle: string;
}): void {
try {
if (AgentActivity.getInstances().length > 0) {
return;
}
const nowIso = new Date(Date.now()).toISOString();
const activity = AgentActivity.start({
title: "T3 Code",
subtitle: "Agent work in progress",
activeCount: 1,
updatedAt: nowIso,
activities: [
{
environmentId: "",
threadId: "",
projectTitle: input.projectTitle,
threadTitle: input.threadTitle,
modelTitle: "",
phase: "starting",
status: "Connecting",
updatedAt: nowIso,
deepLink: "/",
},
],
});
logRegistrationDebug("live activity card armed for local work", {
threadTitle: input.threadTitle,
});
runRegistrationInBackground(
registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid),
"live activity arming after local task start failed",
);
} catch (error) {
logRegistrationError("live activity arming failed", error);
}
}
function readAgentActivitySnapshot(): Effect.Effect<
RelayAgentActivitySnapshotResponse | null,
never,
ManagedRelay.ManagedRelayClient
> {
return Effect.gen(function* () {
if (!readRelayConfig()) return null;
const token = yield* relayToken("read-live-activity-registration-relay-token");
if (!token) {
return null;
}
const client = yield* ManagedRelay.ManagedRelayClient;
return yield* client.getAgentActivitySnapshot({ clerkToken: token });
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
logRegistrationError("agent activity snapshot read failed", error);
return null;
}),
),
);
}
function registerLiveActivityWithRelay(
body: RelayLiveActivityRegistrationRequest,
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
@@ -332,14 +586,8 @@ function mergeDeviceRegistrationInput(
current: DeviceRegistrationInput,
next: DeviceRegistrationInput,
): DeviceRegistrationInput {
return {
...((next.pushToStartToken ?? current.pushToStartToken)
? { pushToStartToken: next.pushToStartToken ?? current.pushToStartToken }
: {}),
...((next.observedPushToken ?? current.observedPushToken)
? { observedPushToken: next.observedPushToken ?? current.observedPushToken }
: {}),
};
const observedPushToken = next.observedPushToken ?? current.observedPushToken;
return observedPushToken ? { observedPushToken } : {};
}
function registrationAddsInformation(
@@ -347,8 +595,7 @@ function registrationAddsInformation(
next: DeviceRegistrationInput,
): boolean {
return (
(next.pushToStartToken !== undefined && next.pushToStartToken !== current.pushToStartToken) ||
(next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken)
next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken
);
}
@@ -363,8 +610,10 @@ function startPendingDeviceRegistration(): void {
logRegistrationDebug("device registration started", {
generation,
hasObservedPushToken: next.input.observedPushToken !== undefined,
hasPushToStartToken: next.input.pushToStartToken !== undefined,
});
if (registrationStatus !== "registered") {
setRegistrationStatus("pending");
}
const registration = {
input: next.input,
operation: Promise.resolve(),
@@ -375,6 +624,13 @@ function startPendingDeviceRegistration(): void {
runtime.runPromiseExit(registerDevice(next.input, generation)),
);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
// A transient failure on a later refresh (e.g. token rotation) leaves
// the prior accepted registration intact on the relay, so an already
// registered device stays "registered" rather than flipping the
// settings toggles off.
if (registrationStatus !== "registered") {
setRegistrationStatus("failed");
}
logRegistrationError(next.context, squashAtomCommandFailure(result));
}
logRegistrationDebug("device registration finished", { generation });
@@ -411,7 +667,7 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri
}
function registerDevice(
input: DeviceRegistrationInput = {},
input: RegisterDeviceInput = {},
expectedGeneration = deviceRegistrationGeneration,
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
@@ -421,7 +677,7 @@ function registerDevice(
}
logRegistrationDebug("device registration loading local state", { expectedGeneration });
const [deviceId, preferences] = yield* Effect.all([
const [deviceId, storedPreferences] = yield* Effect.all([
Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
@@ -439,19 +695,25 @@ function registerDevice(
}),
}),
]);
const preferences = mergeAgentAwarenessRegistrationPreferences(
storedPreferences,
input.preferencesOverride,
);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
logRegistrationDebug("device registration local state ready", {
expectedGeneration,
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
});
const bundleId = Constants.expoConfig?.ios?.bundleIdentifier?.trim();
yield* registerDeviceWithRelay(
makeRelayDeviceRegistrationRequest({
deviceId,
label: Constants.deviceName?.trim() || "iOS device",
iosMajorVersion: iosMajorVersion(),
appVersion: Constants.expoConfig?.version,
...(bundleId ? { bundleId } : {}),
apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant),
...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
...(input?.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
preferences,
}),
@@ -460,27 +722,12 @@ function registerDevice(
});
}
function registerDeviceForCurrentUser(
pushToStartToken?: string,
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return registerDevice(pushToStartToken ? { pushToStartToken } : undefined);
}
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
enqueueDeviceRegistration({ 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 registerDeviceForCurrentUser(): Effect.Effect<
void,
unknown,
ManagedRelay.ManagedRelayClient
> {
return registerDevice(undefined);
}
function ensurePushTokenListener(): void {
@@ -498,14 +745,51 @@ function ensurePushTokenListener(): void {
});
}
// Re-registering activity tokens on foreground makes the relay replay the
// current aggregate to this device, which updates content that drifted while
// pushes could not be delivered and ends orphaned activities whose end push
// never arrived. (Deduped by ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS: rapid
// foreground/sign-in bursts collapse to one registration, but returning after
// real time away still replays.)
function ensureAppStateListener(): void {
if (appStateSubscription || !canRegisterRemoteLiveActivities()) {
return;
}
appStateSubscription = AppState.addEventListener("change", (state) => {
if (state !== "active") {
return;
}
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity reconciliation after app foreground failed",
);
});
}
function endLocalLiveActivities(context: string): void {
if (!canRegisterRemoteLiveActivities()) {
return;
}
try {
for (const activity of AgentActivity.getInstances()) {
activity.end("immediate").catch((error: unknown) => {
logRegistrationError(context, error);
});
}
} catch (error) {
logRegistrationError(context, error);
}
}
export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void {
if (!canRegisterRemoteLiveActivities()) {
return;
}
environmentConnections.set(connection.environmentId, connection);
ensurePushToStartListener();
ensurePushTokenListener();
ensureAppStateListener();
enqueueDeviceRegistration({}, "device registration failed");
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
@@ -523,10 +807,10 @@ export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId)
export function unregisterAllAgentAwarenessConnections(): void {
environmentConnections.clear();
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
appStateSubscription?.remove();
appStateSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
@@ -541,18 +825,38 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
return registerDeviceForCurrentUser().pipe(
Effect.catch((error) =>
Effect.sync(() => {
// Same rationale as the queued path: a failed refresh does not undo an
// already accepted registration.
if (registrationStatus !== "registered") {
setRegistrationStatus("failed");
}
logRegistrationError("device registration refresh failed", error);
}),
),
);
}
export function updateAgentAwarenessRegistrationPreferences(
preferencesOverride: Partial<Preferences>,
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return registerDevice({ preferencesOverride }).pipe(
Effect.tapError((error) =>
Effect.sync(() => {
if (registrationStatus !== "registered") {
setRegistrationStatus("failed");
}
logRegistrationError("device preference registration refresh failed", error);
}),
),
);
}
export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
environmentConnections.clear();
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
appStateSubscription?.remove();
appStateSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
@@ -562,6 +866,9 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
registrationStatus = "unknown";
registrationStatusListeners.clear();
registeredActivityPushTokens.clear();
}
export function unregisterAgentAwarenessDeviceForCurrentUser(
@@ -649,6 +956,13 @@ function registerLiveActivityPushTokenValue(input: {
readonly activityPushToken: string;
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
if (
acceptedAt !== undefined &&
Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
) {
return true;
}
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
@@ -662,6 +976,7 @@ function registerLiveActivityPushTokenValue(input: {
activityPushToken: input.activityPushToken,
});
if (registered) {
registeredActivityPushTokens.set(input.activityPushToken, Date.now());
logRegistrationDebug("live activity push token registered", {
tokenSuffix: input.activityPushToken.slice(-8),
});
@@ -694,7 +1009,7 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
return;
}
const activities = yield* Effect.try({
let activities = yield* Effect.try({
try: () => AgentActivity.getInstances(),
catch: (cause) =>
new AgentAwarenessOperationError({
@@ -710,6 +1025,79 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
),
);
// The relay tracks exactly one card per device; if concurrent arming ever
// produced extras, end them so only one keeps receiving updates.
if (activities.length > 1) {
for (const extra of activities.slice(1)) {
extra.end("immediate").catch((error: unknown) => {
logRegistrationError("duplicate live activity cleanup failed", error);
});
}
activities = activities.slice(0, 1);
}
// Activities are only ever created here, in the foreground, where the
// update token can be observed and registered immediately — the relay
// never remote-starts one (background push-to-start wakes proved too
// unreliable to hand the token over). Arming is conditional: the relay is
// asked what the card would show first, so an idle open never creates an
// empty lock-screen card, and an armed card is born with the real
// aggregate instead of a placeholder.
if (activities.length === 0) {
const preferences = yield* Effect.tryPromise({
try: () => loadPreferences(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-live-activity-prime-preferences",
cause,
}),
}).pipe(Effect.orElseSucceed(() => null));
// The toggle defaults to on: an unset preference (fresh install) must
// prime, so only an explicit false blocks it.
if (preferences?.liveActivitiesEnabled !== false) {
const snapshot = yield* readAgentActivitySnapshot();
// The snapshot request yields; an arm-on-send may have created the
// card in the meantime. Re-check so two cards are never started.
const armedMeanwhile = yield* Effect.try({
try: () => AgentActivity.getInstances(),
catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
}).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
if (armedMeanwhile.length > 0) {
activities = [...armedMeanwhile];
} else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
const aggregate = snapshot.aggregate;
const primed = yield* Effect.try({
try: () =>
AgentActivity.start({
title: aggregate.title,
subtitle: aggregate.subtitle,
activeCount: aggregate.activeCount,
updatedAt: aggregate.updatedAt,
activities: aggregate.activities,
}),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "prime-live-activity",
cause,
}),
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
logRegistrationError("live activity priming failed", error);
return null;
}),
),
);
if (primed) {
logRegistrationDebug("live activity card primed", {
activeCount: aggregate.activeCount,
});
activities = [primed];
}
}
}
}
const registrationResults = yield* Effect.forEach(activities, (activity) =>
registerLiveActivityPushToken({ activity }).pipe(
Effect.map((registered) => !registered),
@@ -1,7 +1,7 @@
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useFocusEffect } from "expo-router";
import { useFocusEffect } from "@react-navigation/native";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -2,23 +2,22 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { LegendList } from "@legendapp/list/react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import * as Haptics from "expo-haptics";
import { Stack } from "expo-router";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "expo-symbols";
import { useCallback, useRef } from "react";
import { useCallback, useMemo, useRef, type ComponentProps } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
RefreshControl,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
@@ -26,11 +25,8 @@ import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "../home/thread-swipe-actions";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
export interface ArchivedThreadsHeaderEnvironment {
@@ -52,84 +48,185 @@ const THREAD_ACTIONS: MenuAction[] = [
},
];
type ArchivedThreadListItem =
| {
readonly kind: "project";
readonly key: string;
readonly environmentLabel: string | null;
readonly project: EnvironmentProject;
}
| {
readonly kind: "thread";
readonly key: string;
readonly environmentLabel: string | null;
readonly isFirst: boolean;
readonly isLast: boolean;
readonly thread: EnvironmentThreadShell;
};
function ArchivedThreadsHeader(props: {
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly sortOrder: ArchivedThreadSortOrder;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onRefresh: () => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
}) {
const { width } = useWindowDimensions();
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
const usesNativeChrome = Platform.OS === "ios";
const usesCompactMailToolbar = Platform.OS === "ios" && width < 700;
const archiveFilterMenu = {
title: "Archived thread options",
items: [
{
type: "submenu" as const,
title: "Environment",
items: [
{
type: "action" as const,
title: "All environments",
state: props.selectedEnvironmentId === null ? ("on" as const) : ("off" as const),
onPress: () => props.onEnvironmentChange(null),
},
...props.environments.map((environment) => ({
type: "action" as const,
title: environment.label,
state:
props.selectedEnvironmentId === environment.environmentId
? ("on" as const)
: ("off" as const),
onPress: () => props.onEnvironmentChange(environment.environmentId),
})),
],
},
{
type: "submenu" as const,
title: "Sort by archived date",
items: [
{
type: "action" as const,
title: "Newest first",
state: props.sortOrder === "newest" ? ("on" as const) : ("off" as const),
onPress: () => props.onSortOrderChange("newest"),
},
{
type: "action" as const,
title: "Oldest first",
state: props.sortOrder === "oldest" ? ("on" as const) : ("off" as const),
onPress: () => props.onSortOrderChange("oldest"),
},
],
},
],
};
return (
<>
<Stack.Screen
{/* Static header config (glass preset + title) lives in Stack.tsx; only
dynamic toolbar/search wiring is set here. */}
<NativeStackScreenOptions
options={{
title: "Archived Threads",
headerSearchBarOptions: {
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
placeholder: "Search archived threads",
placement: "stacked",
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
},
unstable_headerToolbarItems: usesCompactMailToolbar
? () => [
createNativeMailSearchToolbarItem({
composeButtonId: "archived-refresh",
composeSystemImageName: "arrow.clockwise",
filterMenu: archiveFilterMenu,
filterButtonId: "archived-filter",
filterSystemImageName: hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease",
onComposePress: props.onRefresh,
onSearchTextChange: props.onSearchQueryChange,
placeholder: "Search",
searchTextChangeId: "archived-search-text",
}),
]
: undefined,
headerSearchBarOptions: usesCompactMailToolbar
? undefined
: {
...(usesNativeChrome
? {
allowToolbarIntegration: true,
placement: "integratedButton" as const,
}
: {
placement: "stacked" as const,
}),
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
placeholder: "Search archived threads",
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
accessibilityLabel="Filter and sort archived threads"
icon={
hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Archived thread options"
>
<Stack.Toolbar.Menu title="Environment">
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
>
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
{props.environments.map((environment) => (
<Stack.Toolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
{usesCompactMailToolbar ? null : (
<NativeHeaderToolbar placement="right">
{usesNativeChrome ? (
<NativeHeaderToolbar.Button
accessibilityLabel="Refresh archived threads"
icon="arrow.clockwise"
onPress={props.onRefresh}
separateBackground
/>
) : null}
<NativeHeaderToolbar.Menu
accessibilityLabel="Filter and sort archived threads"
icon={
hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Archived thread options"
>
<NativeHeaderToolbar.Menu title="Environment">
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
>
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
{props.environments.map((environment) => (
<NativeHeaderToolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
<Stack.Toolbar.Menu title="Sort by archived date">
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "newest"}
onPress={() => props.onSortOrderChange("newest")}
>
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "oldest"}
onPress={() => props.onSortOrderChange("oldest")}
>
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
<NativeHeaderToolbar.Menu title="Sort by archived date">
<NativeHeaderToolbar.Label>Sort by archived date</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.sortOrder === "newest"}
onPress={() => props.onSortOrderChange("newest")}
>
<NativeHeaderToolbar.Label>Newest first</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
isOn={props.sortOrder === "oldest"}
onPress={() => props.onSortOrderChange("oldest")}
>
<NativeHeaderToolbar.Label>Oldest first</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar>
)}
</>
);
}
@@ -147,9 +244,8 @@ function ProjectGroupLabel(props: {
workspaceRoot={props.project.workspaceRoot}
/>
<Text
className="flex-1 text-xs font-t3-medium uppercase text-foreground-muted"
className="flex-1 text-xs font-t3-medium tracking-[0.5px] uppercase text-foreground-muted"
numberOfLines={1}
style={{ letterSpacing: 0.5 }}
>
{props.project.title}
</Text>
@@ -164,30 +260,25 @@ function ProjectGroupLabel(props: {
function ArchivedThreadRow(props: {
readonly environmentLabel: string | null;
readonly isFirst: boolean;
readonly isLast: boolean;
readonly onDelete: () => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
readonly onUnarchive: () => void;
readonly thread: EnvironmentThreadShell;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const cardColor = useThemeColor("--color-card");
const iconColor = useThemeColor("--color-icon-subtle");
const separatorColor = useThemeColor("--color-separator");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
Boolean(part),
);
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
}
fullSwipeArmedRef.current = armed;
}, []);
const handleMenuAction = useCallback(
(event: { nativeEvent: { event: string } }) => {
if (event.nativeEvent.event === "unarchive") {
@@ -200,114 +291,80 @@ function ArchivedThreadRow(props: {
);
return (
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
childrenContainerStyle={{ backgroundColor: cardColor }}
containerStyle={{ backgroundColor: cardColor }}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
if (swipeableRef.current) {
props.onSwipeableClose(swipeableRef.current);
}
<ThreadSwipeable
backgroundColor={cardColor}
fullSwipeWidth={windowWidth - 32}
onDelete={props.onDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
onSwipeableOpenStartDrag={() => {
if (swipeableRef.current) {
props.onSwipeableWillOpen(swipeableRef.current);
}
}}
onSwipeableWillOpen={() => {
const methods = swipeableRef.current;
if (!methods) return;
props.onSwipeableWillOpen(methods);
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
props.onDelete();
}
}}
overshootFriction={1}
overshootRight
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={cardColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={props.thread.title}
>
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
{() => (
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
borderTopLeftRadius: props.isFirst ? 20 : 0,
borderTopRightRadius: props.isFirst ? 20 : 0,
borderBottomLeftRadius: props.isLast ? 20 : 0,
borderBottomRightRadius: props.isLast ? 20 : 0,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconColor}
type="monochrome"
/>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
className="min-w-0 flex-1 text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
{props.thread.title}
</Text>
<Text className="min-w-[30px] text-right text-xs tabular-nums text-foreground-tertiary">
{timestamp}
</Text>
</View>
) : null}
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconColor}
type="monochrome"
/>
<Text
className="min-w-0 flex-1 font-mono text-2xs text-foreground-tertiary"
numberOfLines={1}
>
{subtitle.join(" · ")}
</Text>
</View>
) : null}
</View>
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Actions for ${props.thread.title}`}
accessibilityRole="button"
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
hitSlop={6}
>
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
</Pressable>
</ControlPillMenu>
</View>
</ReanimatedSwipeable>
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Actions for ${props.thread.title}`}
accessibilityRole="button"
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
hitSlop={6}
>
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
</Pressable>
</ControlPillMenu>
</View>
)}
</ThreadSwipeable>
);
}
@@ -317,7 +374,7 @@ function ArchiveError(props: { readonly message: string; readonly onRetry: () =>
<Text className="text-base font-t3-bold text-danger-foreground">
Could not load every archive
</Text>
<Text className="mt-1 text-sm leading-[18px] text-foreground-muted">{props.message}</Text>
<Text className="mt-1 text-sm text-foreground-muted">{props.message}</Text>
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
<Text className="text-sm font-t3-bold text-danger-foreground">Try again</Text>
</Pressable>
@@ -340,8 +397,41 @@ export function ArchivedThreadsScreen(props: {
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
}) {
const { onDeleteThread, onUnarchiveThread } = props;
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const archiveScrollGesture = useMemo(() => Gesture.Native(), []);
const refreshTint = useThemeColor("--color-icon");
const environmentLabelsById = useMemo(
() =>
new Map(
props.environments.map((environment) => [environment.environmentId, environment.label]),
),
[props.environments],
);
const listItems = useMemo<ReadonlyArray<ArchivedThreadListItem>>(() => {
const items: ArchivedThreadListItem[] = [];
for (const group of props.groups) {
const environmentLabel = environmentLabelsById.get(group.project.environmentId) ?? null;
items.push({
kind: "project",
key: `${group.key}:project`,
environmentLabel,
project: group.project,
});
group.threads.forEach((thread, index) => {
items.push({
kind: "thread",
key: `${thread.environmentId}:${thread.id}`,
environmentLabel,
isFirst: index === 0,
isLast: index === group.threads.length - 1,
thread,
});
});
}
return items;
}, [environmentLabelsById, props.groups]);
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
openSwipeableRef.current.close();
@@ -355,82 +445,103 @@ export function ArchivedThreadsScreen(props: {
}, []);
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
const renderListItem = useCallback(
({ item }: { item: ArchivedThreadListItem }) => {
if (item.kind === "project") {
return (
<View className="pt-4">
<ProjectGroupLabel environmentLabel={item.environmentLabel} project={item.project} />
</View>
);
}
return (
<ArchivedThreadRow
environmentLabel={item.environmentLabel}
isFirst={item.isFirst}
isLast={item.isLast}
onDelete={() => onDeleteThread(item.thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => onUnarchiveThread(item.thread)}
simultaneousSwipeGesture={archiveScrollGesture}
thread={item.thread}
/>
);
},
[
archiveScrollGesture,
handleSwipeableClose,
handleSwipeableWillOpen,
onDeleteThread,
onUnarchiveThread,
],
);
const listEmptyComponent = useMemo(() => {
if (isInitialLoad) {
return (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-sm text-foreground-muted">Loading archive...</Text>
</View>
);
}
return (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
);
}, [isFiltered, isInitialLoad, refreshTint]);
return (
<View className="flex-1 bg-sheet">
<ArchivedThreadsHeader
environments={props.environments}
onEnvironmentChange={props.onEnvironmentChange}
onRefresh={props.onRefresh}
onSearchQueryChange={props.onSearchQueryChange}
onSortOrderChange={props.onSortOrderChange}
selectedEnvironmentId={props.selectedEnvironmentId}
sortOrder={props.sortOrder}
/>
<ScrollView
className="flex-1"
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
onRefresh={props.onRefresh}
refreshing={props.isLoading && !isInitialLoad}
tintColor={String(refreshTint)}
/>
}
showsVerticalScrollIndicator={false}
>
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
{isInitialLoad ? (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
</View>
) : props.groups.length === 0 ? (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
) : (
props.groups.map((group) => {
const environmentLabel =
props.environments.find(
(environment) => environment.environmentId === group.project.environmentId,
)?.label ?? null;
return (
<View key={group.key} collapsable={false}>
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{group.threads.map((thread, index) => (
<ArchivedThreadRow
key={`${thread.environmentId}:${thread.id}`}
environmentLabel={environmentLabel}
isLast={index === group.threads.length - 1}
onDelete={() => props.onDeleteThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => props.onUnarchiveThread(thread)}
thread={thread}
/>
))}
</View>
</View>
);
})
)}
</ScrollView>
<GestureDetector gesture={archiveScrollGesture}>
<LegendList
className="flex-1"
contentContainerStyle={{
paddingBottom: 32,
paddingHorizontal: 16,
paddingTop: 4,
}}
contentInsetAdjustmentBehavior="automatic"
data={listItems}
estimatedItemSize={62}
getItemType={(item) => item.kind}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
keyExtractor={(item) => item.key}
ListEmptyComponent={listEmptyComponent}
ListHeaderComponent={
props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null
}
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
onRefresh={props.onRefresh}
refreshing={props.isLoading && !isInitialLoad}
tintColor={String(refreshTint)}
/>
}
renderItem={renderListItem}
showsVerticalScrollIndicator={false}
/>
</GestureDetector>
</View>
);
}
@@ -14,9 +14,11 @@ import { runtime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import { useAtomCommand } from "../../state/use-atom-command";
import {
releaseAgentAwarenessRelayTokenProvider,
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function resetManagedRelayTokenCache() {
@@ -66,6 +68,19 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
const nextAccount = isSignedIn && userId ? userId : null;
observedAccountRef.current = nextAccount;
// Every sign-in or account switch that completes during this session (a
// cold start observes undefined → account and must not re-prompt) requests
// the T3 Connect onboarding sheet — account transitions clear the
// connected environments, so each new session starts with no devices to
// reach. The request itself is issued after the cleanup transition inside
// activateSession, so the sheet never lists the previous account's
// environments; sign-out drops any not-yet-presented request instead.
const isAccountTransition =
previousObservedAccount !== undefined && previousObservedAccount !== nextAccount;
if (isAccountTransition && nextAccount === null) {
clearConnectOnboardingRequest();
}
const queueAccountCleanup = (
previous: {
readonly userId: string;
@@ -113,6 +128,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
previousTokenProviderRef.current = { userId, provider: tokenProvider };
activateCloudRelayAccount(userId, tokenProvider);
if (isAccountTransition) {
requestConnectOnboarding(userId);
}
};
const activateAfterTransition = (transition: Promise<void>) => {
void (async () => {
@@ -143,7 +161,11 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
useEffect(
() => () => {
previousTokenProviderRef.current = null;
deactivateCloudRelayAccount();
// Unmounting is not a sign-out: the user is usually still signed in, so
// detach the provider without ending lock-screen activities or wiping the
// persisted registration (a remount reuses both).
releaseAgentAwarenessRelayTokenProvider();
setManagedRelaySession(appAtomRegistry, null);
},
[],
);
@@ -1,14 +1,12 @@
import { useWaitlist } from "@clerk/expo";
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { ActivityIndicator, Pressable, Text, TextInput, View } from "react-native";
import { useState } from "react";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { cn } from "../../lib/cn";
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
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";
@@ -35,10 +33,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
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.
<View className="gap-[18px]">
<Text className="text-center font-t3-bold text-xl text-foreground">
You are on the waitlist
</Text>
<Text className="text-center font-sans text-base text-foreground-secondary">
We will email you when your T3 Connect access is ready.
</Text>
<SignInAction onPress={props.onSignIn} />
</View>
@@ -46,18 +46,22 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}
return (
<View style={styles.content}>
<Text style={[styles.body, { color: colors.secondaryForeground }]}>
<View className="gap-[18px]">
<Text className="font-sans text-base text-foreground-secondary">
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>
<View className="gap-2">
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
<TextInput
accessibilityLabel="Email address"
autoCapitalize="none"
autoComplete="email"
autoCorrect={false}
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-4 py-3.5 font-sans text-lg text-foreground border-continuous",
(fieldError || requestError) && "border-danger-foreground",
)}
keyboardType="email-address"
onChangeText={(value) => {
setEmailAddress(value);
@@ -65,24 +69,15 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}}
onSubmitEditing={() => void joinWaitlist()}
placeholder="Enter your email address"
placeholderTextColor={colors.placeholder}
placeholderTextColorClassName="accent-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 }]}
className="font-sans text-sm text-danger-foreground"
selectable
>
{fieldError ?? requestError}
@@ -98,16 +93,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}}
disabled={isSubmitting || emailAddress.trim().length === 0}
onPress={() => void joinWaitlist()}
style={[
styles.primaryButton,
{
backgroundColor: colors.primary,
opacity: isSubmitting || emailAddress.trim().length === 0 ? 0.45 : 1,
},
]}
className="min-h-[54px] flex-row items-center justify-center gap-2 rounded-full bg-primary px-5 py-3 disabled:opacity-[0.45]"
>
{isSubmitting ? <ActivityIndicator color={colors.primaryForeground} size="small" /> : null}
<Text style={[styles.buttonText, { color: colors.primaryForeground }]}>
{isSubmitting ? (
<ActivityIndicator colorClassName="accent-primary-foreground" size="small" />
) : null}
<Text className="font-t3-bold text-base text-primary-foreground">
{isSubmitting ? "Joining" : "Join the waitlist"}
</Text>
</Pressable>
@@ -118,90 +109,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}
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>
<View className="flex-row items-center justify-center gap-1 pt-1">
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
<Text style={[styles.signInText, { color: colors.foreground }]}>Sign in</Text>
<Text className="font-t3-bold text-base text-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",
...MOBILE_TYPOGRAPHY.body,
},
buttonText: {
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.body.fontSize,
},
content: {
gap: 18,
},
confirmationBody: {
textAlign: "center",
},
error: {
fontFamily: "DMSans_400Regular",
...MOBILE_TYPOGRAPHY.footnote,
},
field: {
gap: 8,
},
input: {
borderCurve: "continuous",
borderRadius: 16,
borderWidth: 1,
fontFamily: "DMSans_400Regular",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
minHeight: 54,
paddingHorizontal: 16,
paddingVertical: 14,
},
label: {
fontFamily: "DMSans_700Bold",
...MOBILE_TYPOGRAPHY.footnote,
},
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",
...MOBILE_TYPOGRAPHY.body,
},
title: {
fontFamily: "DMSans_700Bold",
...MOBILE_TYPOGRAPHY.title,
textAlign: "center",
},
});
@@ -0,0 +1,129 @@
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useAuth } from "@clerk/expo";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useEffect, useState } from "react";
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
import { AppText as Text } from "../../components/AppText";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
import { splitEnvironmentSections } from "../connection/environmentSections";
import { useConnectionController } from "../connection/useConnectionController";
import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";
import { hasCloudPublicConfig } from "./publicConfig";
/**
* Post-sign-in onboarding sheet for T3 Connect. Mobile never publishes
* environments itself — it consumes ones published elsewhere — so this simply
* surfaces the account's T3 Connect environments right after sign-in so every
* device can be connected in one go. It shows on every sign-in: sign-out
* clears the connected environments, so each new session starts from zero.
*/
export function ConnectOnboardingRouteScreen() {
const navigation = useNavigation();
// The route is deep-linkable; without cloud config the sheet would present
// empty with no chrome to dismiss it, so bail back out instead.
useEffect(() => {
if (hasCloudPublicConfig()) {
return;
}
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.dispatch(StackActions.replace("Home"));
}
}, [navigation]);
return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
}
function ConfiguredConnectOnboardingRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const { isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections();
const { refreshRelayEnvironments } = useConnectionController();
const { connectedCloudEnvironments } = splitEnvironmentSections({
connectedEnvironments,
cloudEnvironments: null,
});
// Pull-to-refresh tracks its own spinner instead of discovery's refreshing
// flag, so background refreshes (e.g. the sign-in one) don't yank the
// content down.
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullRefresh = useCallback(() => {
void (async () => {
setIsPullRefreshing(true);
await refreshRelayEnvironments();
setIsPullRefreshing(false);
})();
}, [refreshRelayEnvironments]);
const handleClose = useCallback(() => {
navigation.goBack();
}, [navigation]);
// Persist before dismissing so a quick sign-out/sign-in cannot race ahead
// of the preference write; the write is a local secure-store update.
const handleDontShowAgain = useCallback(() => {
void (async () => {
if (userId) {
const result = await settlePromise(() => optOutOfConnectOnboarding(userId));
reportAtomCommandResult(result, { label: "connect onboarding opt-out" });
}
navigation.goBack();
})();
}, [navigation, userId]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
</NativeHeaderToolbar>
<ScrollView
alwaysBounceVertical
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 16,
paddingHorizontal: 20,
paddingTop: 16,
}}
refreshControl={
<RefreshControl refreshing={isPullRefreshing} onRefresh={handlePullRefresh} />
}
>
{isSignedIn ? (
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
showHeader={false}
/>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
Sign in to your T3 account to set up T3 Connect.
</Text>
</View>
)}
{userId ? (
<Pressable
accessibilityRole="button"
hitSlop={8}
onPress={handleDontShowAgain}
className="items-center py-1 active:opacity-70"
>
<Text className="text-xs text-foreground-muted">{"Don't show this again"}</Text>
</Pressable>
) : null}
</ScrollView>
</View>
);
}
@@ -0,0 +1,24 @@
import { Atom } from "effect/unstable/reactivity";
import { appAtomRegistry } from "../../state/atom-registry";
// Signals RootStackLayout (inside the navigation tree) that an in-session
// sign-in just completed. Holds the account id so a sign-out between the
// request and the navigation cannot present the sheet for the wrong account.
export const connectOnboardingRequestAtom = Atom.make<string | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:connect-onboarding-request"),
);
/**
* Requests the onboarding sheet for the given account. Sign-out clears the
* connected environments, so onboarding runs on every in-session sign-in —
* each new session starts with no connected devices.
*/
export function requestConnectOnboarding(accountId: string): void {
appAtomRegistry.set(connectOnboardingRequestAtom, accountId);
}
export function clearConnectOnboardingRequest(): void {
appAtomRegistry.set(connectOnboardingRequestAtom, null);
}
@@ -0,0 +1,49 @@
import { useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
import { useEffect } from "react";
import { appAtomRegistry } from "../../state/atom-registry";
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
// Sign-in happens inside the Settings sheet; give its detent/session-state
// transitions a beat to settle before presenting another formSheet on top.
const PRESENT_ONBOARDING_DELAY_MS = 600;
/**
* Consumes the onboarding request inside the navigation tree (RootStackLayout)
* and presents the onboarding formSheet. Lives apart from connectOnboarding.ts
* so non-navigation consumers (CloudAuthProvider) do not pull
* @react-navigation into their module graph.
*/
export function useConnectOnboardingNavigation(): void {
const navigation = useNavigation();
const requestedAccountId = useAtomValue(connectOnboardingRequestAtom);
useEffect(() => {
if (requestedAccountId === null) {
return;
}
let cancelled = false;
const timer = setTimeout(() => {
void (async () => {
// A failed preference read prefers showing the sheet.
const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false);
// The cancelled flag covers effect re-runs, but a sign-out can clear
// the request atom moments before this render commits — re-check the
// atom so a stale request never presents the sheet.
if (cancelled || appAtomRegistry.get(connectOnboardingRequestAtom) !== requestedAccountId) {
return;
}
clearConnectOnboardingRequest();
if (!optedOut) {
navigation.navigate("ConnectOnboarding");
}
})();
}, PRESENT_ONBOARDING_DELAY_MS);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [navigation, requestedAccountId]);
}
@@ -0,0 +1,21 @@
import { loadPreferences, updatePreferences } from "../../persistence/imperative";
// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports
// the request signal) never pulls the persistence adapter into its
// module graph; that breaks CloudAuthProvider.test.ts suite loading.
/** Whether the account chose "Don't show this again". */
export async function isConnectOnboardingOptedOut(accountId: string): Promise<boolean> {
const preferences = await loadPreferences();
return preferences.connectOnboardingOptOutAccounts?.includes(accountId) ?? false;
}
/** Persists "Don't show this again" for the account. */
export async function optOutOfConnectOnboarding(accountId: string): Promise<void> {
await updatePreferences((current) => {
const optedOut = current.connectOnboardingOptOutAccounts ?? [];
return optedOut.includes(accountId)
? {}
: { connectOnboardingOptOutAccounts: [...optedOut, accountId] };
});
}
+41 -9
View File
@@ -8,12 +8,7 @@ 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 { DpopPublicJwk, normalizeDpopHtu } from "@t3tools/shared/dpopCommon";
import * as Layer from "effect/Layer";
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
@@ -107,6 +102,40 @@ function sha256Digest(
);
}
function base64UrlSha256(
data: Uint8Array,
message: string,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return sha256Digest(data, message).pipe(Effect.map(Encoding.encodeBase64Url));
}
function dpopThumbprintInput(jwk: DpopPublicJwk): string {
return JSON.stringify({
crv: jwk.crv,
kty: jwk.kty,
x: jwk.x,
y: jwk.y,
});
}
function computeDpopJwkThumbprintEffect(
jwk: DpopPublicJwk,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return base64UrlSha256(
new TextEncoder().encode(dpopThumbprintInput(jwk)),
"Could not hash the DPoP public key thumbprint.",
);
}
function computeDpopAccessTokenHashEffect(
accessToken: string,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return base64UrlSha256(
new TextEncoder().encode(accessToken),
"Could not hash the DPoP access token.",
);
}
function secureRandomBytes(
byteCount: number,
message: string,
@@ -153,7 +182,7 @@ export function generateDpopProofKeyPair(): Effect.Effect<
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
catch: cloudDpopError("Generated DPoP public key is invalid."),
});
const thumbprint = computeDpopJwkThumbprint(publicJwk);
const thumbprint = yield* computeDpopJwkThumbprintEffect(publicJwk);
return {
privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk),
publicJwk,
@@ -189,9 +218,10 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
},
catch: cloudDpopError("Stored DPoP proof key is invalid."),
});
const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk);
return {
...restored,
thumbprint: computeDpopJwkThumbprint(restored.publicJwk),
thumbprint,
};
}
const generated = yield* generateDpopProofKeyPair();
@@ -243,7 +273,9 @@ export function createDpopProof(input: {
Effect.map(Encoding.encodeBase64Url),
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
);
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
const ath = input.accessToken
? yield* computeDpopAccessTokenHashEffect(input.accessToken)
: null;
const payload = yield* encodeDpopJwtPayloadJson({
htm: input.method.toUpperCase(),
htu,
@@ -7,10 +7,13 @@ import { RelayMobileClientId } from "@t3tools/contracts/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { HttpClient } from "effect/unstable/http";
import { MobilePreferencesStore } from "../../persistence/mobile-preferences";
import { MobileStorage } from "../../persistence/mobile-storage";
import {
cloudEnvironmentsPendingStatus,
linkEnvironmentToCloud,
linkEnvironmentToCloudWithPreference,
connectCloudEnvironment,
listCloudEnvironments,
listCloudEnvironmentsWithStatus,
@@ -36,11 +39,14 @@ vi.mock("react-native", () => ({
},
}));
vi.mock("../../lib/storage", () => ({
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadPreferences: vi.fn(() => Promise.resolve({})),
vi.mock("expo-secure-store", () => ({
deleteItemAsync: vi.fn(),
getItemAsync: vi.fn(),
setItemAsync: vi.fn(),
}));
const loadPreferences = vi.fn(() => Effect.succeed({}));
const savedConnection = {
environmentId: EnvironmentId.make("env-1"),
environmentLabel: "Desktop",
@@ -69,6 +75,27 @@ function cloudClientLayer() {
const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init));
return Layer.mergeAll(
httpClientLayer,
Layer.succeed(
MobilePreferencesStore,
MobilePreferencesStore.of({
load: loadPreferences(),
savePatch: (patch) => Effect.succeed(patch),
update: () => Effect.succeed({}),
}),
),
Layer.succeed(
MobileStorage,
MobileStorage.of({
loadSavedConnections: Effect.succeed([]),
saveConnection: () => Effect.void,
clearSavedConnection: () => Effect.void,
loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
saveAgentAwarenessRegistrationRecord: () => Effect.void,
clearAgentAwarenessRegistrationRecord: Effect.void,
}),
),
ManagedRelay.layer({
relayUrl: "https://relay.example.test",
clientId: RelayMobileClientId,
@@ -80,7 +107,11 @@ const withCloudServices = <A, E>(
effect: Effect.Effect<
A,
E,
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
| HttpClient.HttpClient
| ManagedRelay.ManagedRelayClient
| ManagedRelay.ManagedRelayDpopSigner
| MobilePreferencesStore
| MobileStorage
>,
) => effect.pipe(Effect.provide(cloudClientLayer()));
@@ -146,6 +177,7 @@ describe("mobile cloud link environment client", () => {
beforeEach(() => {
vi.restoreAllMocks();
createProofMock.mockClear();
loadPreferences.mockClear();
});
it("normalizes configured relay base URLs before building DPoP-bound requests", () => {
@@ -705,10 +737,7 @@ describe("mobile cloud link environment client", () => {
it.effect("preserves disabled Live Activity preferences when linking an environment", () =>
Effect.gen(function* () {
const storage = yield* Effect.promise(() => import("../../lib/storage"));
vi.mocked(storage.loadPreferences).mockResolvedValueOnce({
liveActivitiesEnabled: false,
});
loadPreferences.mockReturnValueOnce(Effect.succeed({ liveActivitiesEnabled: false }));
const bodies: Array<unknown> = [];
const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
if (init?.body) {
@@ -761,6 +790,45 @@ describe("mobile cloud link environment client", () => {
}),
);
it.effect("uses an explicit Live Activity preference when persisted state is unavailable", () =>
Effect.gen(function* () {
loadPreferences.mockReturnValueOnce(Effect.die("persisted preferences must not be read"));
const bodies: Array<Record<string, unknown>> = [];
const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
if (init?.body) {
// @effect-diagnostics-next-line preferSchemaOverJson:off
bodies.push(JSON.parse(requestBodyText(init.body)) as Record<string, unknown>);
}
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
if (String(url).endsWith("/v1/client/environment-links")) {
return Promise.resolve(Response.json(validLinkResponse()));
}
return Promise.resolve(
Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
);
});
vi.stubGlobal("fetch", fetchMock);
yield* withCloudServices(
linkEnvironmentToCloudWithPreference({
clerkToken: "clerk-token",
connection: savedConnection,
liveActivitiesEnabled: true,
}),
);
expect(bodies.filter((body) => "liveActivitiesEnabled" in body)).toEqual([
expect.objectContaining({ liveActivitiesEnabled: true }),
expect.objectContaining({ liveActivitiesEnabled: true }),
]);
}),
);
it.effect(
"does not persist cloud connect bootstrap credentials in saved connection records",
() =>
Loaded 100 of 390 files, more files were not shown because too many files have changed in this diff. Show more