Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 65e5983e57 Avoid discovered SSH row rerenders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-10 16:20:25 +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
236 changed files with 17037 additions and 4858 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 -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:"
},
+64 -4
View File
@@ -15,6 +15,7 @@ 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;
@@ -24,6 +25,7 @@ const VARIANT_CONFIG: Record<
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",
@@ -32,6 +34,7 @@ const VARIANT_CONFIG: Record<
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",
@@ -40,6 +43,7 @@ const VARIANT_CONFIG: Record<
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",
@@ -59,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",
@@ -66,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",
@@ -113,8 +131,32 @@ const config: ExpoConfig = {
favicon: "./assets/favicon.png",
},
plugins: [
"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",
[
@@ -127,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",
},
},
@@ -151,12 +193,21 @@ 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",
@@ -179,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"
}
}
}
+9 -6
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,9 +196,10 @@
/* ─── 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: 11px;
@@ -221,14 +224,14 @@
/* ─── 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;
}
@@ -300,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
@@ -608,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,
+4 -1
View File
@@ -6,6 +6,7 @@
"scripts": {
"dev": "expo start --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",
@@ -79,6 +80,7 @@
"expo-font": "~56.0.7",
"expo-glass-effect": "~56.0.4",
"expo-haptics": "~56.0.3",
"expo-image": "~56.0.11",
"expo-image-picker": "~56.0.18",
"expo-linking": "~56.0.14",
"expo-network": "~56.0.5",
@@ -86,6 +88,7 @@
"expo-paste-input": "^0.1.15",
"expo-secure-store": "~56.0.4",
"expo-splash-screen": "~56.0.10",
"expo-sqlite": "~56.0.5",
"expo-symbols": "~56.0.6",
"expo-updates": "~56.0.19",
"expo-web-browser": "~56.0.5",
@@ -96,7 +99,7 @@
"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.6",
"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",
@@ -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,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.");
}
+3 -14
View File
@@ -1,11 +1,6 @@
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
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";
@@ -13,7 +8,6 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native";
import { RegistryContext } from "@effect/atom-react";
import { useEffect } from "react";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
@@ -29,17 +23,12 @@ const appLinking = {
const Navigation = createStaticNavigation(RootStack);
export default function App() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
useEffect(() => {
if (fontsLoaded) SplashScreen.hide();
}, [fontsLoaded]);
SplashScreen.hide();
}, []);
return (
<RegistryContext.Provider value={appAtomRegistry}>
+27
View File
@@ -17,6 +17,8 @@ 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";
@@ -39,6 +41,7 @@ import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScr
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";
@@ -145,6 +148,13 @@ const SettingsSheetStack = createNativeStackNavigator({
title: "Appearance",
},
}),
SettingsClientStorage: createNativeStackScreen({
screen: SettingsClientStorageRouteScreen,
linking: "client-storage",
options: {
title: "Client Storage",
},
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
@@ -220,6 +230,7 @@ const NewTaskSheetStack = createNativeStackNavigator({
// 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",
@@ -251,6 +262,8 @@ function RootStackLayout(props: {
}) {
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);
@@ -412,6 +425,20 @@ export const RootStack = createNativeStackNavigator({
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",
+3 -11
View File
@@ -4,7 +4,6 @@ import {
type TextInputProps as RNTextInputProps,
type TextProps as RNTextProps,
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
@@ -18,7 +17,7 @@ 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?: React.Ref<RNTextInput>;
};
@@ -27,14 +26,7 @@ export type AppTextInputProps = RNTextInputProps & {
* 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}
@@ -42,7 +34,7 @@ export function AppTextInput({
"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"
@@ -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,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),
@@ -244,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>
@@ -331,10 +330,7 @@ function ArchivedThreadRow(props: {
>
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
<Text className="min-w-[30px] text-right text-xs tabular-nums text-foreground-tertiary">
{timestamp}
</Text>
</View>
@@ -347,9 +343,8 @@ function ArchivedThreadRow(props: {
type="monochrome"
/>
<Text
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
className="min-w-0 flex-1 font-mono text-2xs text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
</Text>
@@ -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,13 +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 { 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";
@@ -34,12 +33,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
if (waitlist.id) {
return (
<View style={styles.content}>
<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 Cloud access is ready.
We will email you when your T3 Connect access is ready.
</Text>
<SignInAction onPress={props.onSignIn} />
</View>
@@ -47,19 +46,22 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}
return (
<View style={styles.content}>
<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}>
<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="font-sans text-lg text-foreground"
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);
@@ -67,16 +69,8 @@ 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,
},
]}
textContentType="emailAddress"
value={emailAddress}
/>
@@ -99,15 +93,11 @@ 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}
{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>
@@ -120,7 +110,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
function SignInAction(props: { readonly onPress: () => void }) {
return (
<View style={styles.signInRow}>
<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 className="font-t3-bold text-base text-foreground">Sign in</Text>
@@ -128,48 +118,3 @@ function SignInAction(props: { readonly onPress: () => void }) {
</View>
);
}
function useCloudWaitlistColors() {
return {
dangerForeground: String(useThemeColor("--color-danger-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")),
};
}
const styles = StyleSheet.create({
content: {
gap: 18,
},
field: {
gap: 8,
},
input: {
borderCurve: "continuous",
borderRadius: 16,
borderWidth: 1,
minHeight: 54,
paddingHorizontal: 16,
paddingVertical: 14,
},
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,
},
});
@@ -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] };
});
}
@@ -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",
() =>
@@ -30,7 +30,8 @@ import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
import { authClientMetadata } from "../../lib/authClientMetadata";
import type { SavedRemoteConnection } from "../../lib/connection";
import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
import * as MobilePreferences from "../../persistence/mobile-preferences";
import * as MobileStorage from "../../persistence/mobile-storage";
import { resolveCloudPublicConfig } from "./publicConfig";
const RELAY_STATUS_AND_CONNECT_SCOPES = [
@@ -256,14 +257,19 @@ function ensureConnectEndpointMatchesEnvironment(input: {
return Effect.void;
}
export function linkEnvironmentToCloud(input: {
interface LinkEnvironmentToCloudInput {
readonly connection: SavedRemoteConnection;
readonly clerkToken: string;
}): Effect.Effect<
void,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
> {
}
type LinkEnvironmentToCloudRequirements =
| HttpClient.HttpClient
| ManagedRelay.ManagedRelayClient
| MobileStorage.MobileStorage;
export function linkEnvironmentToCloudWithPreference(
input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean },
): Effect.Effect<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {
return Effect.gen(function* () {
if (!input.connection.bearerToken) {
return yield* new CloudEnvironmentLinkError({
@@ -273,15 +279,11 @@ export function linkEnvironmentToCloud(input: {
const localBearerToken = input.connection.bearerToken;
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelay.ManagedRelayClient;
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
const preferences = yield* Effect.tryPromise({
try: () => loadPreferences(),
catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
});
const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
const storage = yield* MobileStorage.MobileStorage;
const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),
);
const liveActivitiesEnabled = input.liveActivitiesEnabled;
const challenge = yield* relayClient
.createEnvironmentLinkChallenge({
clerkToken: input.clerkToken,
@@ -350,6 +352,25 @@ export function linkEnvironmentToCloud(input: {
});
}
export function linkEnvironmentToCloud(
input: LinkEnvironmentToCloudInput,
): Effect.Effect<
void,
CloudEnvironmentLinkError,
LinkEnvironmentToCloudRequirements | MobilePreferences.MobilePreferencesStore
> {
return MobilePreferences.MobilePreferencesStore.pipe(
Effect.flatMap((preferencesStore) => preferencesStore.load),
Effect.mapError(cloudEnvironmentLinkError("Could not load mobile notification preferences.")),
Effect.flatMap((preferences) =>
linkEnvironmentToCloudWithPreference({
...input,
liveActivitiesEnabled: preferences.liveActivitiesEnabled !== false,
}),
),
);
}
export function listCloudEnvironments(input: {
readonly clerkToken: string;
}): Effect.Effect<
@@ -460,10 +481,10 @@ export function listCloudEnvironmentsWithStatus(input: {
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
function* () {
return yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
const storage = yield* MobileStorage.MobileStorage;
return yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),
);
},
);
@@ -557,7 +578,10 @@ export function connectCloudEnvironment(input: {
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
| HttpClient.HttpClient
| ManagedRelay.ManagedRelayClient
| ManagedRelay.ManagedRelayDpopSigner
| MobileStorage.MobileStorage
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
@@ -572,7 +596,10 @@ export function refreshCloudEnvironmentConnection(input: {
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
| HttpClient.HttpClient
| ManagedRelay.ManagedRelayClient
| ManagedRelay.ManagedRelayDpopSigner
| MobileStorage.MobileStorage
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
@@ -0,0 +1,377 @@
import { useAuth } from "@clerk/expo";
import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import {
ActivityIndicator,
Pressable,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
/**
* "T3 Connect" section: every environment published to the signed-in account,
* with connect switches, availability status, refresh, and loading/error
* states. Shared between the Settings environments screen and the T3 Connect
* onboarding sheet.
*/
export function CloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
/**
* Hide the "T3 Connect" section title + refresh button for hosts that
* provide their own chrome (the onboarding sheet's native header and
* pull-to-refresh).
*/
readonly showHeader?: boolean;
}) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const handleConnectCloudEnvironment = useCallback(
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
const showHeader = props.showHeader ?? true;
if (!isSignedIn) return null;
return (
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
{showHeader ? (
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
</View>
) : null}
{hasCloudRows ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{props.connectedCloudEnvironments.map((environment, index) => (
<ConnectedCloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
))}
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environment.environmentId}
environment={environment}
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/>
))}
</View>
) : controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-sm leading-normal text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : controller.relayDiscovery.error ? null : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
{/* Rendered alongside any connected rows — a failed discovery must not
hide behind an otherwise-healthy list. */}
{controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-base font-t3-bold text-foreground">
Could not load T3 Connect environments
</Text>
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
<Pressable
accessibilityRole="button"
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70"
>
<Text className="text-xs font-t3-bold text-foreground">Try again</Text>
</Pressable>
</View>
) : null}
</View>
);
}
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) {
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
/>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayEnvironmentView;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onToggleError: () => void;
}) {
const presentation = availableCloudEnvironmentPresentation({
isStatusPending: props.environment.availability === "checking",
status: props.environment.status,
statusError: props.environment.error,
statusErrorTraceId: props.environment.traceId,
});
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={presentation.connectionError}
connectionErrorTraceId={presentation.connectionErrorTraceId}
connectionState={presentation.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environment.label}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
}
}}
onToggleError={props.onToggleError}
statusText={presentation.statusText}
value={false}
/>
);
}
function CloudEnvironmentRowShell(props: {
readonly borderTop: boolean;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly disabled?: boolean;
readonly errorExpanded: boolean;
readonly label: string;
readonly onToggleError: () => void;
readonly onValueChange: (enabled: boolean) => void;
readonly statusText?: string;
readonly value: boolean;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
const chevron = useThemeColor("--color-chevron");
const isRetrying =
props.connectionState === "connecting" || props.connectionState === "reconnecting";
const shouldPulse = isRetrying;
const statusText =
props.statusText ??
connectionStatusText({
phase: props.connectionState,
error: props.connectionError,
traceId: props.connectionErrorTraceId,
});
const statusClassName = props.connectionError
? "text-rose-500 dark:text-rose-400"
: "text-foreground-muted";
const [errorMeasurement, setErrorMeasurement] = useState<{
readonly text: string;
readonly lineCount: number;
} | null>(null);
const errorTraceId = props.connectionErrorTraceId;
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
const errorLineCount =
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
const isErrorExpanded = errorCanExpand && props.errorExpanded;
const StatusContainer = errorCanExpand ? Pressable : View;
const onMeasuredErrorTextLayout = useCallback(
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
if (!props.connectionError) {
return;
}
const nextLineCount = event.nativeEvent.lines.length;
setErrorMeasurement((currentMeasurement) =>
currentMeasurement?.text === measuredErrorText &&
currentMeasurement.lineCount === nextLineCount
? currentMeasurement
: { text: measuredErrorText, lineCount: nextLineCount },
);
},
[measuredErrorText, props.connectionError],
);
return (
<View
collapsable={false}
className={cn(
"flex-row items-center gap-3 bg-card px-4 py-3.5",
props.borderTop && "border-t border-border",
)}
>
<View className="min-w-0 flex-1 gap-0.5">
<View className="min-w-0 flex-row items-center gap-2">
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
<Text
className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.label}
</Text>
</View>
{props.connectionError ? (
<Text
aria-hidden
onTextLayout={onMeasuredErrorTextLayout}
className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
>
{measuredErrorText}
</Text>
) : null}
<StatusContainer
{...(errorCanExpand
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
: {})}
className="min-w-0 flex-row items-start gap-1"
>
<Text
className={cn("min-w-0 flex-1 text-xs", statusClassName)}
numberOfLines={isErrorExpanded ? undefined : 1}
>
{statusText}
{errorTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-xs underline decoration-dotted", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
}}
>
{errorTraceId}
</Text>
</>
) : null}
</Text>
{errorCanExpand ? (
<SymbolView
name="chevron.down"
size={10}
tintColor={chevron}
type="monochrome"
style={{
marginTop: 3,
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
}}
/>
) : null}
</StatusContainer>
</View>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
function CopyTraceIdButton(props: { readonly traceId: string }) {
const iconColor = useThemeColor("--color-icon");
return (
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
</Pressable>
);
}
@@ -38,7 +38,6 @@ export function ConnectionEnvironmentRow(props: {
const [url, setUrl] = useState(props.environment.displayUrl);
const mutedColor = useThemeColor("--color-icon-subtle");
const placeholderColor = useThemeColor("--color-placeholder");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const statusLabel = connectionStatusLabel(props.environment);
@@ -98,7 +97,7 @@ export function ConnectionEnvironmentRow(props: {
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className="underline"
className="underline decoration-dotted"
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(statusTraceId, { target: "connection-trace-id" });
@@ -106,7 +105,6 @@ export function ConnectionEnvironmentRow(props: {
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{statusTraceId}
</Text>
@@ -135,22 +133,18 @@ export function ConnectionEnvironmentRow(props: {
>
{props.environment.isRelayManaged ? (
<Text className="text-sm text-foreground-muted">
Managed by T3 Cloud. Tunnel details update automatically.
Managed by T3 Connect. Tunnel details update automatically.
</Text>
) : (
<>
<View className="gap-1.5">
<Text
className="text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
Label
</Text>
<TextInput
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook"
placeholderTextColor={placeholderColor}
value={label}
onChangeText={setLabel}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"
@@ -158,10 +152,7 @@ export function ConnectionEnvironmentRow(props: {
</View>
<View className="gap-1.5">
<Text
className="text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
URL
</Text>
<TextInput
@@ -169,7 +160,6 @@ export function ConnectionEnvironmentRow(props: {
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={url}
onChangeText={setUrl}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"
@@ -185,10 +175,7 @@ export function ConnectionEnvironmentRow(props: {
onPress={handleSave}
>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
<Text
className="text-xs font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.8 }}
>
<Text className="text-xs font-t3-bold tracking-[0.8px] uppercase text-primary-foreground">
Save
</Text>
</Pressable>
@@ -37,33 +37,11 @@ export function ConnectionSheetButton(props: {
}) {
const tone = props.tone ?? "secondary";
const primaryBg = useThemeColor("--color-primary");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerBg = useThemeColor("--color-danger");
const dangerBorderColor = useThemeColor("--color-danger-border");
const dangerFg = useThemeColor("--color-danger-foreground");
const secondaryBg = useThemeColor("--color-secondary");
const secondaryFg = useThemeColor("--color-secondary-foreground");
const borderColor = useThemeColor("--color-border");
const colors =
tone === "primary"
? {
backgroundColor: primaryBg,
borderColor: "transparent",
textColor: primaryFg,
}
: tone === "danger"
? {
backgroundColor: dangerBg,
borderColor: dangerBorderColor,
textColor: dangerFg,
}
: {
backgroundColor: secondaryBg,
borderColor: borderColor,
textColor: secondaryFg,
};
const textColor = tone === "primary" ? primaryFg : tone === "danger" ? dangerFg : secondaryFg;
const primaryShadow =
tone === "primary"
@@ -84,28 +62,32 @@ export function ConnectionSheetButton(props: {
props.compact
? "min-h-[42px] flex-row items-center justify-center gap-1.5 rounded-[14px] px-3.5 py-2.5"
: "min-h-[48px] flex-row items-center justify-center gap-2 rounded-[16px] px-4 py-3",
"disabled:opacity-50",
tone === "primary"
? "bg-primary"
: tone === "danger"
? "border border-danger-border bg-danger"
: "border border-border bg-secondary",
)}
disabled={props.disabled}
onPress={props.onPress}
style={[
{
backgroundColor: colors.backgroundColor,
borderWidth: tone === "primary" ? 0 : 1,
borderColor: colors.borderColor,
opacity: props.disabled ? 0.5 : 1,
},
primaryShadow,
]}
style={primaryShadow}
>
<SymbolView
name={props.icon}
size={props.compact ? 13 : 14}
tintColor={colors.textColor}
tintColor={textColor}
type="monochrome"
/>
<Text
className="text-xs font-t3-bold uppercase"
style={{ color: colors.textColor, letterSpacing: 0.8 }}
className={cn(
"text-xs font-t3-bold tracking-[0.8px] uppercase",
tone === "primary"
? "text-primary-foreground"
: tone === "danger"
? "text-danger-foreground"
: "text-secondary-foreground",
)}
>
{props.label}
</Text>
@@ -38,7 +38,6 @@ export function ConnectionsNewRouteScreen({
const [scannerLocked, setScannerLocked] = useState(false);
const headerIconColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
@@ -158,7 +157,7 @@ export function ConnectionsNewRouteScreen({
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
className="flex-1"
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
@@ -168,10 +167,7 @@ export function ConnectionsNewRouteScreen({
<View collapsable={false} className="gap-5">
{showScanner ? (
cameraPermission?.granted ? (
<View
className="overflow-hidden rounded-[24px]"
style={{ borderCurve: "continuous" }}
>
<View className="overflow-hidden rounded-[24px] border-continuous">
<CameraView
barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
onBarcodeScanned={handleQrScan}
@@ -179,10 +175,7 @@ export function ConnectionsNewRouteScreen({
/>
</View>
) : (
<View
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<View className="items-center gap-3 rounded-[24px] border-continuous bg-card px-5 py-8">
<Text className="text-center text-sm leading-normal text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
@@ -200,10 +193,7 @@ export function ConnectionsNewRouteScreen({
) : (
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
<View collapsable={false} className="gap-1.5">
<Text
className="text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
Host
</Text>
<TextInput
@@ -211,7 +201,6 @@ export function ConnectionsNewRouteScreen({
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={hostInput}
onChangeText={handleHostChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
@@ -219,17 +208,13 @@ export function ConnectionsNewRouteScreen({
</View>
<View collapsable={false} className="gap-1.5">
<Text
className="text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
Pairing code
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
placeholder="abc-123-xyz"
placeholderTextColor={placeholderColor}
value={codeInput}
onChangeText={handleCodeChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
@@ -42,7 +42,7 @@ export function ConnectionsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
className="flex-1"
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
@@ -55,10 +55,7 @@ export function ConnectionsRouteScreen() {
<View
key={environment.environmentId}
collapsable={false}
style={{
borderTopWidth: index === 0 ? 0 : 1,
}}
className={cn(index !== 0 && "border-border")}
className={cn(index !== 0 && "border-t border-border")}
>
<ConnectionEnvironmentRow
environment={environment}
@@ -35,7 +35,7 @@ function cloudEnvironment(environmentId: string): RelayClientEnvironmentRecord {
}
describe("mobile environment settings sections", () => {
it("keeps saved relay-managed connections under T3 Cloud", () => {
it("keeps saved relay-managed connections under T3 Connect", () => {
const local = connectedEnvironment({
environmentId: "environment-local",
isRelayManaged: false,
@@ -8,6 +8,7 @@ import {
import { RefreshControl, ScrollView, Text as NativeText, View } from "react-native";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { useFontFamily } from "../../lib/useFontFamily";
import {
resolveMarkdownFontSizes,
resolveNativeMarkdownTypography,
@@ -45,11 +46,15 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
const codeBackground = String(useThemeColor("--color-md-code-bg"));
const codeText = String(useThemeColor("--color-md-code-text"));
const horizontalRule = String(useThemeColor("--color-md-hr"));
const regularFontFamily = useFontFamily("regular");
const mediumFontFamily = useFontFamily("medium");
const boldFontFamily = useFontFamily("bold");
return useMemo(() => {
const renderers: CustomRenderers = {
link: ({ href, children }) => (
<NativeText
className="font-t3-medium"
onPress={() => {
if (href) {
void tryOpenExternalUrl(href, "markdown-link");
@@ -57,7 +62,6 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
}}
style={{
color: link,
fontFamily: "DMSans_500Medium",
textDecorationLine: "none",
}}
>
@@ -86,21 +90,21 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
styles: {
text: {
color: body,
fontFamily: "DMSans_400Regular",
fontFamily: regularFontFamily,
fontSize: markdownFontSizes.m,
lineHeight: markdownFontSizes.bodyLineHeight,
},
heading: {
color: strong,
fontFamily: "DMSans_700Bold",
fontFamily: boldFontFamily,
},
strong: {
color: strong,
fontFamily: "DMSans_700Bold",
fontFamily: boldFontFamily,
},
link: {
color: link,
fontFamily: "DMSans_500Medium",
fontFamily: mediumFontFamily,
},
blockquote: {
backgroundColor: blockquoteBackground,
@@ -141,9 +145,9 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
fontSize: nativeMarkdownTypography.fontSize,
lineHeight: nativeMarkdownTypography.lineHeight,
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
fontFamily: regularFontFamily,
headingFontFamily: boldFontFamily,
boldFontFamily,
},
};
}, [
@@ -155,8 +159,11 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
horizontalRule,
link,
markdownFontSizes,
mediumFontFamily,
nativeMarkdownTypography,
regularFontFamily,
strong,
boldFontFamily,
]);
}
@@ -246,7 +246,7 @@ export function FileTreeBrowser(props: {
// flex-1 Views is ignored, which is why the tree rendered under the header with no blur.
return (
<FlatList
style={{ flex: 1 }}
className="flex-1"
data={visibleNodes}
keyExtractor={(item) => item.node.path}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
@@ -224,14 +224,7 @@ function FilesToolbarBottomFade() {
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={{
bottom: 0,
height: 112,
left: 0,
position: "absolute",
right: 0,
zIndex: 1,
}}
className="absolute inset-x-0 bottom-0 z-[1] h-28"
>
<Svg width="100%" height="100%">
<Defs>
@@ -122,6 +122,16 @@ export function HomeRouteScreen() {
}}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
onNewThreadInProject={(project) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
pendingTasks={pendingTasks}
+50 -12
View File
@@ -12,6 +12,8 @@ import type {
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Platform, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
@@ -22,6 +24,7 @@ import { EmptyState } from "../../components/EmptyState";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
PendingTaskListRow,
@@ -72,6 +75,7 @@ interface HomeScreenProps {
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
}
/* ─── Layout constants ───────────────────────────────────────────────── */
@@ -153,21 +157,48 @@ export function HomeScreen(props: HomeScreenProps) {
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
>(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
setGroupDisplayStates((previous) => {
const next = new Map(previous);
next.set(
key,
nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
);
const effectiveGroupDisplayStates = useMemo(() => {
const next = new Map(groupDisplayStates);
if (!AsyncResult.isSuccess(preferencesResult)) {
return next;
});
}, []);
}
for (const key of preferencesResult.value.collapsedProjectGroups ?? []) {
const existing = next.get(key);
next.set(key, {
...(existing ?? DEFAULT_GROUP_DISPLAY_STATE),
collapsed: true,
});
}
return next;
}, [groupDisplayStates, preferencesResult]);
const effectiveGroupDisplayStatesRef = useRef(effectiveGroupDisplayStates);
effectiveGroupDisplayStatesRef.current = effectiveGroupDisplayStates;
const updateGroupDisplay = useCallback(
(key: string, action: HomeGroupDisplayAction) => {
const next = new Map(effectiveGroupDisplayStatesRef.current);
next.set(key, nextGroupDisplayState(next.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action));
effectiveGroupDisplayStatesRef.current = next;
setGroupDisplayStates(next);
if (action === "toggle-collapsed") {
const collapsedProjectGroups: string[] = [];
for (const [groupKey, state] of next) {
if (state.collapsed) {
collapsedProjectGroups.push(groupKey);
}
}
savePreferences({ collapsedProjectGroups });
}
},
[savePreferences],
);
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current !== methods) {
@@ -218,10 +249,10 @@ export function HomeScreen(props: HomeScreenProps) {
() =>
buildHomeListLayout({
groups: projectGroups,
displayStates: groupDisplayStates,
displayStates: effectiveGroupDisplayStates,
showAllThreads: hasSearchQuery,
}),
[projectGroups, groupDisplayStates, hasSearchQuery],
[projectGroups, effectiveGroupDisplayStates, hasSearchQuery],
);
const projectCwdByKey = useMemo(() => {
@@ -248,6 +279,12 @@ export function HomeScreen(props: HomeScreenProps) {
isFirst={item.isFirst}
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
// Aggregated groups (same repo across machines) have no single
// target project, and `pending-project:` groups hold a placeholder
// built from queued-task metadata rather than a real project shell,
// so the quick new-thread button is single-real-project only.
newThreadTarget={item.group.newThreadTarget}
onNewThread={props.onNewThreadInProject}
project={item.group.representative}
threadCount={item.group.threads.length + item.group.pendingTasks.length}
title={item.group.title}
@@ -308,6 +345,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.onArchiveThread,
props.onDeletePendingTask,
props.onDeleteThread,
props.onNewThreadInProject,
props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
@@ -374,7 +412,7 @@ export function HomeScreen(props: HomeScreenProps) {
{Platform.OS === "ios" ? null : <HomeTopContentSpacer topInset={insets.top} />}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View style={{ paddingBottom: 16 }}>
<View className="pb-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
@@ -57,15 +57,20 @@ function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
const project = makeProject(key, key);
const threads = Array.from({ length: threadCount }, (_, index) =>
makeThread(`${key}-thread-${index}`, project.id),
);
return {
key,
title: key,
representative: project,
projects: [project],
pendingTasks: [],
threads: Array.from({ length: threadCount }, (_, index) =>
makeThread(`${key}-thread-${index}`, project.id),
),
threads,
// All threads inside the recency window, so the baseline stays at the
// initial page size and the pagination expectations below hold.
recentThreads: threads,
newThreadTarget: project,
};
}
@@ -153,6 +158,48 @@ describe("buildHomeListLayout", () => {
expect(reset.visibleCount).toBe(HOME_INITIAL_VISIBLE_THREADS);
});
it("offers show-less after expanding a stale group whose baseline is below the page size", () => {
// Stale project: 10 threads total but only 3 within the recency window.
const project = makeProject("stale", "stale");
const threads = Array.from({ length: 10 }, (_, index) =>
makeThread(`stale-thread-${index}`, project.id),
);
const group: HomeThreadGroup = {
key: "stale",
title: "stale",
representative: project,
projects: [project],
pendingTasks: [],
threads,
recentThreads: threads.slice(0, 3),
newThreadTarget: project,
};
const collapsedToRecent = buildHomeListLayout({
groups: [group],
displayStates: displayStates({}),
});
expect(collapsedToRecent.items.filter((item) => item.type === "thread")).toHaveLength(3);
expect(collapsedToRecent.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 7,
canShowLess: false,
});
const expanded = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
stale: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
}),
});
expect(expanded.items.filter((item) => item.type === "thread")).toHaveLength(10);
expect(expanded.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 0,
canShowLess: true,
});
});
it("hides threads and the show-more row for collapsed groups", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 12), makeGroup("beta", 2)],
+21 -3
View File
@@ -145,12 +145,27 @@ export function buildHomeListLayout(input: {
}
const totalCount = group.threads.length;
// Default to the group's recent-activity window (last few days, or a small
// fallback for stale projects), capped at the initial page size. Until the
// user taps "Show more", older threads stay hidden to save vertical space;
// "Show less" resets visibleCount to the initial constant, which lands back
// here at the recency baseline.
const baselineCount = Math.min(
group.recentThreads.length,
HOME_INITIAL_VISIBLE_THREADS,
totalCount,
);
const visibleCount = input.showAllThreads
? totalCount
: Math.min(Math.max(display.visibleCount, HOME_INITIAL_VISIBLE_THREADS), totalCount);
: Math.min(
display.visibleCount > HOME_INITIAL_VISIBLE_THREADS
? display.visibleCount
: baselineCount,
totalCount,
);
const visibleThreads = group.threads.slice(0, visibleCount);
const hiddenCount = totalCount - visibleCount;
const hasShowMoreRow = !input.showAllThreads && totalCount > HOME_INITIAL_VISIBLE_THREADS;
const hasShowMoreRow = !input.showAllThreads && totalCount > baselineCount;
// Pending (unsent) tasks lead the group and are never paginated away.
for (const [pendingIndex, pendingTask] of group.pendingTasks.entries()) {
@@ -180,7 +195,10 @@ export function buildHomeListLayout(input: {
key: `show-more:${group.key}`,
groupKey: group.key,
hiddenCount,
canShowLess: visibleCount > HOME_INITIAL_VISIBLE_THREADS,
// Compare against the group's own baseline, not the global page size:
// stale projects start below HOME_INITIAL_VISIBLE_THREADS, and "Show
// less" must be offered as soon as anything beyond the baseline shows.
canShowLess: visibleCount > baselineCount,
});
}
}
@@ -44,6 +44,8 @@ function makeThread(
};
}
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
function buildGroups(
projects: ReadonlyArray<EnvironmentProject>,
threads: ReadonlyArray<EnvironmentThreadShell>,
@@ -57,6 +59,7 @@ function buildGroups(
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
projectGroupingMode: "repository",
now: NOW,
...overrides,
});
}
@@ -220,4 +223,144 @@ describe("buildHomeThreadGroups", () => {
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
});
it("default view shows only threads from the last 5 days", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("recent-1"),
projectId: project.id,
title: "Today",
updatedAt: "2026-06-28T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("recent-2"),
projectId: project.id,
title: "Within window",
updatedAt: "2026-06-25T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("old"),
projectId: project.id,
title: "Two weeks ago",
updatedAt: "2026-06-14T00:00:00.000Z",
}),
];
const group = buildGroups([project], threads)[0];
// Default view trims to recent threads...
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2"]);
// ...while full history stays available for the expanded view.
expect(group?.threads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2", "old"]);
});
it("falls back to the most recent 3 threads when none are within 5 days", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
(day, index) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${index}`),
projectId: project.id,
title: `Thread ${index}`,
updatedAt: `${day}T00:00:00.000Z`,
}),
);
const group = buildGroups([project], threads)[0];
expect(group?.recentThreads.map((thread) => thread.id)).toEqual([
"thread-4",
"thread-3",
"thread-2",
]);
expect(group?.threads).toHaveLength(5);
});
it("does not apply the recency window while searching", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
(day, index) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${index}`),
projectId: project.id,
title: `Thread ${index}`,
updatedAt: `${day}T00:00:00.000Z`,
}),
);
const group = buildGroups([project], threads, { searchQuery: "T3 Code" })[0];
// Search reaches the full history rather than the 3-thread fallback.
expect(group?.recentThreads).toHaveLength(5);
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(
group?.threads.map((thread) => thread.id),
);
});
it("targets quick new threads at the group member with the newest thread", () => {
const laptopEnv = EnvironmentId.make("environment-laptop");
const desktopEnv = EnvironmentId.make("environment-desktop");
const repositoryIdentity = {
canonicalKey: "github.com/pingdotgg/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
};
const laptopProject = makeProject({
environmentId: laptopEnv,
id: ProjectId.make("project-laptop"),
title: "t3code",
repositoryIdentity,
});
const desktopProject = makeProject({
environmentId: desktopEnv,
id: ProjectId.make("project-desktop"),
title: "t3code",
repositoryIdentity,
});
const threads = [
makeThread({
environmentId: laptopEnv,
id: ThreadId.make("thread-laptop"),
projectId: laptopProject.id,
title: "Older laptop thread",
updatedAt: "2026-06-27T00:00:00.000Z",
}),
makeThread({
environmentId: desktopEnv,
id: ThreadId.make("thread-desktop"),
projectId: desktopProject.id,
title: "Newest desktop thread",
updatedAt: "2026-06-28T00:00:00.000Z",
}),
];
// Aggregated into one group by repository; the quick new-thread target
// must follow the newest thread (desktop), not the arbitrary first member.
const groups = buildGroups([laptopProject, desktopProject], threads);
expect(groups).toHaveLength(1);
expect(groups[0]?.projects).toHaveLength(2);
expect(groups[0]?.newThreadTarget?.environmentId).toBe(desktopEnv);
expect(groups[0]?.newThreadTarget?.id).toBe(desktopProject.id);
});
});
@@ -14,6 +14,7 @@ import type {
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Option from "effect/Option";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
@@ -21,13 +22,33 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
/**
* Default home view only surfaces threads active within this window, to keep the
* screen compact while keeping recent work visible.
*/
const RECENT_THREAD_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;
/** Fallback when a project has no threads inside the recency window. */
const RECENT_THREAD_FALLBACK_COUNT = 3;
export interface HomeThreadGroup {
readonly key: string;
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
/** Full sorted thread history for the group (revealed when expanded / searching). */
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
/** Subset shown by default: threads from the last few days, or the most recent few. */
readonly recentThreads: ReadonlyArray<EnvironmentThreadShell>;
/**
* Where a quick "new thread in this project" should land. For aggregated
* groups (same repo on several machines) this is the member that owns the
* group's most recent thread — the machine the user last worked on — rather
* than the arbitrary first member; the draft's computer picker covers
* switching from there. Null only for synthetic pending-project groups,
* whose single "project" is a placeholder built from queued-task metadata.
*/
readonly newThreadTarget: EnvironmentProject | null;
}
interface MutableHomeThreadGroup {
@@ -48,6 +69,24 @@ function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOr
}, latestThread);
}
/**
* Trims a group's threads to recent activity for the default home view.
* `sortedThreads` must already be ordered newest-first for `threadSortOrder`.
* Keeps threads within {@link RECENT_THREAD_WINDOW_MS}; when none qualify, keeps
* the most recent {@link RECENT_THREAD_FALLBACK_COUNT} so a project never vanishes.
*/
function selectRecentThreads(
sortedThreads: ReadonlyArray<EnvironmentThreadShell>,
threadSortOrder: SidebarThreadSortOrder,
now: number,
): ReadonlyArray<EnvironmentThreadShell> {
const cutoff = now - RECENT_THREAD_WINDOW_MS;
const recent = sortedThreads.filter(
(thread) => getThreadSortTimestamp(thread, threadSortOrder) >= cutoff,
);
return recent.length > 0 ? recent : sortedThreads.slice(0, RECENT_THREAD_FALLBACK_COUNT);
}
export function buildHomeThreadGroups(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
@@ -57,7 +96,10 @@ export function buildHomeThreadGroups(input: {
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
/** Current time used for the recency window; defaults to now. Injectable for tests. */
readonly now?: number;
}): ReadonlyArray<HomeThreadGroup> {
const now = input.now ?? Date.now();
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
@@ -165,13 +207,43 @@ export function buildHomeThreadGroups(input: {
continue;
}
const sortedThreads = sortThreads(matchingThreads, input.threadSortOrder);
// An active search should reach the full history, so the recency window
// only trims the default (no-query) view.
const recentThreads =
query.length === 0
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
: sortedThreads;
// Sorted newest-first, so the first thread whose project is a group member
// marks the machine the user last worked on.
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
group.projects.some(
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
).pipe(
Option.flatMap((thread) =>
Arr.findFirst(
group.projects,
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
),
Option.getOrNull,
);
result.push({
key: group.key,
title,
representative,
projects: group.projects,
pendingTasks: matchingPendingTasks,
threads: sortThreads(matchingThreads, input.threadSortOrder),
threads: sortedThreads,
recentThreads,
newThreadTarget: group.key.startsWith("pending-project:")
? null
: (lastActiveProject ?? representative),
});
}
@@ -1,4 +1,7 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useFocusEffect } from "@react-navigation/native";
import {
@@ -401,6 +404,20 @@ export function AdaptiveWorkspaceLayout(props: {
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
}, [navigation]);
const handleNewThreadInProject = useCallback(
(project: EnvironmentProject) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
},
[navigation],
);
const renderedSidebarWidth = useSharedValue(
panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0,
);
@@ -459,16 +476,17 @@ export function AdaptiveWorkspaceLayout(props: {
return (
<HomeListOptionsProvider>
<AdaptiveWorkspaceContext.Provider value={contextValue}>
<View testID="adaptive-workspace-layout" style={{ flex: 1, flexDirection: "row" }}>
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
<Animated.View
className="self-stretch overflow-hidden"
accessibilityElementsHidden={!panes.primarySidebarVisible}
collapsable={false}
importantForAccessibility={
panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
}
pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
style={[{ alignSelf: "stretch", overflow: "hidden" }, sidebarAnimatedStyle]}
style={sidebarAnimatedStyle}
>
<ThreadNavigationSidebar
width={layout.listPaneWidth}
@@ -477,13 +495,14 @@ export function AdaptiveWorkspaceLayout(props: {
selectedThreadKey={selectedThreadKey}
onOpenSettings={handleOpenSettings}
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
onNewThreadInProject={handleNewThreadInProject}
onSelectThread={handleSelectThread}
onSearchQueryChange={setPrimarySidebarSearchQuery}
searchQuery={primarySidebarSearchQuery}
/>
</Animated.View>
) : null}
<View className="bg-screen" collapsable={false} style={{ flex: 1, overflow: "hidden" }}>
<View className="flex-1 overflow-hidden bg-screen" collapsable={false}>
<View
collapsable={false}
style={
@@ -129,13 +129,14 @@ export function WorkspaceInspectorPane(props: {
) : null}
{inspectorSupported ? (
<Animated.View
className="shrink-0 overflow-hidden"
accessibilityElementsHidden={!inspectorVisible}
collapsable={false}
importantForAccessibility={inspectorVisible ? "auto" : "no-hide-descendants"}
pointerEvents={inspectorVisible ? "auto" : "none"}
style={[{ flexShrink: 0, overflow: "hidden" }, inspectorStyle]}
style={inspectorStyle}
>
<Animated.View style={[{ flex: 1 }, inspectorContentStyle]}>
<Animated.View className="flex-1" style={inspectorContentStyle}>
{props.renderInspector?.()}
</Animated.View>
</Animated.View>
@@ -69,6 +69,7 @@ export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
return (
<GestureDetector gesture={resizeGesture}>
<Pressable
className="relative z-[100] -mx-[22px] w-11 self-stretch cursor-pointer justify-center"
accessibilityActions={[
{ name: "increment", label: "Make pane wider" },
{ name: "decrement", label: "Make pane narrower" },
@@ -82,7 +83,6 @@ export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
onAccessibilityAction={handleAccessibilityAction}
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
style={styles.hitTarget}
>
<View style={[styles.line, (hovered || dragging) && styles.activeLine]} />
</Pressable>
@@ -91,15 +91,6 @@ export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
}
const styles = StyleSheet.create({
hitTarget: {
alignSelf: "stretch",
cursor: "pointer",
justifyContent: "center",
marginHorizontal: -22,
position: "relative",
width: 44,
zIndex: 100,
},
line: {
alignSelf: "center",
backgroundColor:
@@ -31,6 +31,7 @@ import * as Arr from "effect/Array";
import * as Cause from "effect/Cause";
import * as Order from "effect/Order";
import { AsyncResult } from "effect/unstable/reactivity";
import { cn } from "../../lib/cn";
import { useProjects, useServerConfigs } from "../../state/entities";
import { filesystemEnvironment } from "../../state/filesystem";
@@ -99,10 +100,7 @@ function sourceFromParam(value: string | string[] | undefined): AddProjectRemote
function SectionTitle(props: { readonly children: string }) {
return (
<Text
className="px-1 text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.7 }}
>
<Text className="px-1 text-2xs font-t3-bold tracking-[0.7px] uppercase text-foreground-muted">
{props.children}
</Text>
);
@@ -112,7 +110,12 @@ function AddProjectShell(props: { readonly children: ReactNode }) {
const insets = useSafeAreaInsets();
return (
<View className="flex-1 bg-sheet">
// collapsable={false} is load-bearing: if this wrapper is flattened, the
// ScrollView lands directly under RNSSafeAreaView and RNS's formSheet
// scroll-view frame correction mistakes this full-height wrapper for a
// "header" sibling, coercing the ScrollView to zero height (blank sheet
// as soon as the sheet re-lays-out, e.g. when the keyboard opens).
<View collapsable={false} className="flex-1 bg-sheet">
<ScrollView
keyboardShouldPersistTaps="handled"
contentInsetAdjustmentBehavior="automatic"
@@ -143,19 +146,17 @@ function ListRow(props: {
readonly right?: ReactNode;
readonly onPress?: () => void;
}) {
const borderColor = useThemeColor("--color-border-subtle");
const chevronColor = useThemeColor("--color-chevron");
return (
<Pressable
disabled={props.disabled}
onPress={props.onPress}
className="bg-card px-3.5 py-2.5 active:opacity-70"
style={{
opacity: props.disabled ? 0.45 : 1,
borderTopWidth: props.isFirst ? 0 : 1,
borderTopColor: borderColor,
}}
className={cn(
"bg-card px-3.5 py-2.5 active:opacity-70",
!props.isFirst && "border-t border-border-subtle",
props.disabled && "opacity-[0.45]",
)}
>
<View className="flex-row items-center gap-3">
<View
@@ -144,15 +144,11 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
}
return (
<View style={{ flex: 1 }}>
<KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
<View className="flex-1">
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View
style={{
flex: 1,
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: target ? 0 : Math.max(insets.bottom, 18),
}}
className="flex-1 px-5 pt-2"
style={{ paddingBottom: target ? 0 : Math.max(insets.bottom, 18) }}
>
<View className="flex-row items-center justify-between py-2">
<Pressable
@@ -253,8 +249,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
textAlignVertical="top"
value={commentText}
onChangeText={setCommentText}
className="h-full flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base"
style={{ flex: 1, minHeight: 0 }}
className="h-full min-h-0 flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base"
/>
</TextInputWrapper>
</View>
@@ -655,7 +655,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
<View className="flex-1 bg-sheet">
{showConnectionNotice ? (
<View style={{ flex: 1, paddingTop: topContentInset }}>
<View className="flex-1" style={{ paddingTop: topContentInset }}>
<EnvironmentConnectionNotice
environmentLabel={environment.presentation?.entry.target.label ?? "Environment"}
connection={
@@ -722,7 +722,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
bottom: Math.max(insets.bottom, 18) + 18,
}}
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
className="flex-1"
>
{listHeader}
{!selectedSection ? (
@@ -48,8 +48,8 @@ export function ReviewChangeBar(props: {
<View>
{Array.from({ length: Math.ceil(height / 2) }, (_, index) => (
<View key={index}>
<View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
<View style={{ height: 1 }} />
<View className="h-px w-[5px] bg-rose-400" />
<View className="h-px" />
</View>
))}
</View>
@@ -13,12 +13,10 @@ export function SettingsAppearanceRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<TextAppearanceSection />
@@ -0,0 +1,215 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { SymbolView } from "expo-symbols";
import { useMemo } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import {
clearClientCacheAtom,
clientCacheSummaryAtom,
type EnvironmentClientCacheSummary,
} from "../../state/client-cache-state";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { SettingsSection } from "./components/SettingsSection";
export function SettingsClientStorageRouteScreen() {
const insets = useSafeAreaInsets();
const iconColor = useThemeColor("--color-icon");
const dangerForegroundColor = useThemeColor("--color-danger-foreground");
const summaryResult = useAtomValue(clientCacheSummaryAtom);
const clearResult = useAtomValue(clearClientCacheAtom);
const clearCache = useAtomSet(clearClientCacheAtom);
const { savedConnectionsById } = useSavedRemoteConnections();
const isClearing = clearResult.waiting;
const summary = AsyncResult.isSuccess(summaryResult) ? summaryResult.value : null;
const environmentSummaries = useMemo(
() =>
[...(summary?.environments ?? [])].sort((left, right) => {
const leftLabel = savedConnectionsById[left.environmentId]?.environmentLabel ?? "";
const rightLabel = savedConnectionsById[right.environmentId]?.environmentLabel ?? "";
return leftLabel.localeCompare(rightLabel);
}),
[savedConnectionsById, summary?.environments],
);
const confirmClearEnvironment = (environment: EnvironmentClientCacheSummary) => {
const label =
savedConnectionsById[environment.environmentId]?.environmentLabel ??
environment.environmentId;
Alert.alert(
`Clear cache for ${label}?`,
"This removes offline threads, server metadata, and cached branches for this environment. The saved connection and credentials stay intact.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Clear Cache",
style: "destructive",
onPress: () =>
clearCache({ type: "environment", environmentId: environment.environmentId }),
},
],
);
};
const confirmClearAll = () => {
Alert.alert(
"Clear all client caches?",
"This removes offline data for every environment. Connections, credentials, account data, and app preferences stay intact.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Clear All Caches",
style: "destructive",
onPress: () => clearCache({ type: "all" }),
},
],
);
};
return (
<View collapsable={false} className="flex-1 bg-sheet">
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentInset={{ bottom: Math.max(insets.bottom, 18) }}
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4 pb-[18px]"
>
<SettingsSection title="Environment caches">
{AsyncResult.isFailure(summaryResult) ? (
<View className="items-center gap-2 px-6 py-8">
<SymbolView
name="exclamationmark.triangle"
size={28}
tintColor={dangerForegroundColor}
type="monochrome"
weight="regular"
/>
<Text className="text-center text-base text-foreground">Storage unavailable</Text>
<Text className="text-center text-sm text-foreground-muted">
Restart the app and try again.
</Text>
</View>
) : !summary ? (
<View className="items-center gap-3 px-6 py-8">
<ActivityIndicator />
<Text className="text-center text-sm text-foreground-muted">
Inspecting cached data…
</Text>
</View>
) : environmentSummaries.length > 0 ? (
environmentSummaries.map((environment, index) => (
<CacheEnvironmentRow
key={environment.environmentId}
environment={environment}
environmentLabel={
savedConnectionsById[environment.environmentId]?.environmentLabel ??
environment.environmentId
}
disabled={isClearing}
first={index === 0}
onClear={() => confirmClearEnvironment(environment)}
/>
))
) : (
<View className="items-center gap-2 px-6 py-8">
<SymbolView
name="checkmark.circle"
size={28}
tintColor={iconColor}
type="monochrome"
weight="regular"
/>
<Text className="text-center text-base text-foreground">No cached data</Text>
<Text className="text-center text-sm text-foreground-muted">
Offline cache records will appear here after environments are used.
</Text>
</View>
)}
</SettingsSection>
<View className="gap-3">
<SettingsSection title="Actions">
<Pressable
accessibilityRole="button"
disabled={isClearing || !summary || summary.recordCount === 0}
onPress={confirmClearAll}
className="flex-row items-center gap-4 p-4 disabled:opacity-40"
>
<SymbolView
name="trash"
size={22}
tintColor={dangerForegroundColor}
type="monochrome"
weight="regular"
/>
<Text className="flex-1 text-lg tabular-nums text-danger-foreground">
{summary ? `Clear ${formatBytes(summary.payloadBytes)}` : "Clear caches"}
</Text>
{isClearing ? <ActivityIndicator color={dangerForegroundColor} /> : null}
</Pressable>
</SettingsSection>
<Text className="px-2 text-sm leading-normal text-foreground-muted">
Clearing caches never removes environment connections, credentials, account data, or
appearance preferences.
</Text>
{AsyncResult.isFailure(summaryResult) || AsyncResult.isFailure(clearResult) ? (
<Text selectable className="px-2 text-sm text-danger-foreground">
Client storage is temporarily unavailable. Try again after restarting the app.
</Text>
) : null}
</View>
</ScrollView>
</View>
);
}
function CacheEnvironmentRow(props: {
readonly environment: EnvironmentClientCacheSummary;
readonly environmentLabel: string;
readonly disabled: boolean;
readonly first: boolean;
readonly onClear: () => void;
}) {
const iconColor = useThemeColor("--color-icon");
return (
<View
className={
props.first
? "flex-row items-center gap-3 p-4"
: "border-t border-border flex-row items-center gap-3 p-4"
}
>
<SymbolView
name="desktopcomputer"
size={22}
tintColor={iconColor}
type="monochrome"
weight="regular"
/>
<Text className="min-w-0 flex-1 text-base text-foreground" numberOfLines={1}>
{props.environmentLabel}
</Text>
<Pressable
accessibilityLabel={`Clear cache for ${props.environmentLabel}`}
accessibilityRole="button"
disabled={props.disabled}
onPress={props.onClear}
className="rounded-full px-3 py-2 disabled:opacity-40"
>
<Text className="font-t3-medium tabular-nums text-danger-foreground" numberOfLines={1}>
Clear {formatBytes(props.environment.payloadBytes)}
</Text>
</Pressable>
</View>
);
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
}
@@ -1,38 +1,18 @@
import { useAuth } from "@clerk/expo";
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useNavigation } from "@react-navigation/native";
import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import {
ActivityIndicator,
Pressable,
ScrollView,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import { ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import {
type RelayEnvironmentView,
useConnectionController,
} from "../connection/useConnectionController";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
import { splitEnvironmentSections } from "../connection/environmentSections";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
export function SettingsEnvironmentsRouteScreen() {
@@ -70,11 +50,10 @@ export function SettingsEnvironmentsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
className="flex-1"
contentContainerClassName="px-5 pt-4"
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
{hasLocalEnvironments ? (
@@ -83,10 +62,7 @@ export function SettingsEnvironmentsRouteScreen() {
<View
key={environment.environmentId}
collapsable={false}
style={{
borderTopWidth: index === 0 ? 0 : 1,
}}
className={cn(index !== 0 && "border-border")}
className={cn(index !== 0 && "border-t border-border")}
>
<ConnectionEnvironmentRow
environment={environment}
@@ -117,7 +93,7 @@ export function SettingsEnvironmentsRouteScreen() {
)}
{hasCloudPublicConfig() ? (
<ConfiguredCloudEnvironmentRows
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
/>
@@ -126,323 +102,3 @@ export function SettingsEnvironmentsRouteScreen() {
</View>
);
}
function ConfiguredCloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
}) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const handleConnectCloudEnvironment = useCallback(
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
if (!isSignedIn) return null;
return (
<View collapsable={false} className="mt-5 gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
)}
</Pressable>
</View>
{hasCloudRows ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{props.connectedCloudEnvironments.map((environment, index) => (
<ConnectedCloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
))}
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environment.environmentId}
environment={environment}
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/>
))}
</View>
) : controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-sm leading-normal text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : controller.relayDiscovery.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-base font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
</View>
);
}
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) {
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
/>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayEnvironmentView;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onToggleError: () => void;
}) {
const presentation = availableCloudEnvironmentPresentation({
isStatusPending: props.environment.availability === "checking",
status: props.environment.status,
statusError: props.environment.error,
statusErrorTraceId: props.environment.traceId,
});
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={presentation.connectionError}
connectionErrorTraceId={presentation.connectionErrorTraceId}
connectionState={presentation.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environment.label}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
}
}}
onToggleError={props.onToggleError}
statusText={presentation.statusText}
value={false}
/>
);
}
function CloudEnvironmentRowShell(props: {
readonly borderTop: boolean;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly disabled?: boolean;
readonly errorExpanded: boolean;
readonly label: string;
readonly onToggleError: () => void;
readonly onValueChange: (enabled: boolean) => void;
readonly statusText?: string;
readonly value: boolean;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
const chevron = useThemeColor("--color-chevron");
const isRetrying =
props.connectionState === "connecting" || props.connectionState === "reconnecting";
const shouldPulse = isRetrying;
const statusText =
props.statusText ??
connectionStatusText({
phase: props.connectionState,
error: props.connectionError,
traceId: props.connectionErrorTraceId,
});
const statusClassName = props.connectionError
? "text-rose-500 dark:text-rose-400"
: "text-foreground-muted";
const [errorMeasurement, setErrorMeasurement] = useState<{
readonly text: string;
readonly lineCount: number;
} | null>(null);
const errorTraceId = props.connectionErrorTraceId;
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
const errorLineCount =
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
const isErrorExpanded = errorCanExpand && props.errorExpanded;
const StatusContainer = errorCanExpand ? Pressable : View;
const onMeasuredErrorTextLayout = useCallback(
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
if (!props.connectionError) {
return;
}
const nextLineCount = event.nativeEvent.lines.length;
setErrorMeasurement((currentMeasurement) =>
currentMeasurement?.text === measuredErrorText &&
currentMeasurement.lineCount === nextLineCount
? currentMeasurement
: { text: measuredErrorText, lineCount: nextLineCount },
);
},
[measuredErrorText, props.connectionError],
);
return (
<View
collapsable={false}
className={cn(
"flex-row items-center gap-3 bg-card px-4 py-3.5",
props.borderTop && "border-t border-border",
)}
>
<View className="min-w-0 flex-1 gap-0.5">
<View className="min-w-0 flex-row items-center gap-2">
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
<Text
className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.label}
</Text>
</View>
{props.connectionError ? (
<Text
aria-hidden
className={cn("absolute left-0 right-0 text-xs", statusClassName)}
onTextLayout={onMeasuredErrorTextLayout}
style={{ opacity: 0, zIndex: -1 }}
>
{measuredErrorText}
</Text>
) : null}
<StatusContainer
{...(errorCanExpand
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
: {})}
className="min-w-0 flex-row items-start gap-1"
>
<Text
className={cn("min-w-0 flex-1 text-xs", statusClassName)}
numberOfLines={isErrorExpanded ? undefined : 1}
>
{statusText}
{errorTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-xs underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{errorTraceId}
</Text>
</>
) : null}
</Text>
{errorCanExpand ? (
<SymbolView
name="chevron.down"
size={10}
tintColor={chevron}
type="monochrome"
style={{
marginTop: 3,
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
}}
/>
) : null}
</StatusContainer>
</View>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
function CopyTraceIdButton(props: { readonly traceId: string }) {
const iconColor = useThemeColor("--color-icon");
return (
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
</Pressable>
);
}
@@ -1,10 +1,14 @@
import { useAuth, useUser } from "@clerk/expo";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Updates from "expo-updates";
import { useNavigation } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "expo-symbols";
import * as Effect from "effect/Effect";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { Alert, Linking, Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -18,15 +22,19 @@ import {
import { AppText as Text } from "../../components/AppText";
import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";
import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
import { refreshAgentAwarenessRegistration } from "../agent-awareness/remoteRegistration";
import {
getAgentAwarenessRegistrationStatus,
refreshAgentAwarenessRegistration,
subscribeAgentAwarenessRegistrationStatus,
} from "../agent-awareness/remoteRegistration";
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { runtime } from "../../lib/runtime";
import { loadPreferences } from "../../lib/storage";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
@@ -35,6 +43,19 @@ import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
// Reflects whether the relay actually accepted this device's registration.
// The notification and Live Activity switches are gated on this so they can
// never read as enabled when the device cannot receive anything (e.g. the
// registration request timed out).
function useDeviceRegistered(): boolean {
const status = useSyncExternalStore(
subscribeAgentAwarenessRegistrationStatus,
getAgentAwarenessRegistrationStatus,
() => "unknown" as const,
);
return status === "registered";
}
export function SettingsRouteScreen() {
const navigation = useNavigation();
@@ -73,12 +94,10 @@ function LocalSettingsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<SettingsSection title="Configuration">
@@ -103,6 +122,8 @@ function LocalSettingsRouteScreen() {
}
function ConfiguredSettingsRouteScreen() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
@@ -111,6 +132,10 @@ function ConfiguredSettingsRouteScreen() {
const { savedConnectionsById } = useSavedRemoteConnections();
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
const deviceRegistered = useDeviceRegistered();
const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.liveActivitiesEnabled !== false
: true;
const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
const environmentCount = connections.length;
@@ -147,16 +172,19 @@ function ConfiguredSettingsRouteScreen() {
setLiveActivityStatus("signed-out");
return;
}
void (async () => {
const result = await settlePromise(() => loadPreferences());
if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "live activity preference load" });
if (!AsyncResult.isSuccess(preferencesResult)) {
if (AsyncResult.isFailure(preferencesResult)) {
reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
setLiveActivityStatus("enabled");
return;
} else {
setLiveActivityStatus("checking");
}
setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled");
})();
}, [isLoaded, isSignedIn]);
return;
}
setLiveActivityStatus(
preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
);
}, [isLoaded, isSignedIn, preferencesResult]);
const requestNotifications = useCallback(async () => {
const result = await settleAsyncResult(() =>
@@ -180,10 +208,19 @@ function ConfiguredSettingsRouteScreen() {
}
if (result.value.type === "granted") {
setNotificationStatus("enabled");
Alert.alert(
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
);
// Permission alone is not enough: the switch stays off until the relay
// registration succeeds, so tell the user the truth about which happened.
if (getAgentAwarenessRegistrationStatus() === "registered") {
Alert.alert(
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
);
} else {
Alert.alert(
"Couldn't finish enabling notifications",
"Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",
);
}
return;
}
if (result.value.type === "unsupported") {
@@ -211,8 +248,8 @@ function ConfiguredSettingsRouteScreen() {
const promptSignIn = useCallback(() => {
Alert.alert(
"Request T3 Cloud access",
"Live Activity updates require approved T3 Cloud access so relay can deliver updates to this device.",
"Request T3 Connect access",
"Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.",
[
{ text: "Cancel", style: "cancel" },
{
@@ -250,6 +287,7 @@ function ConfiguredSettingsRouteScreen() {
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: true,
previousEnabled: liveActivitiesPreferenceEnabled,
clerkToken: tokenResult.value,
connections,
}),
@@ -267,15 +305,34 @@ function ConfiguredSettingsRouteScreen() {
return;
}
savePreferences({ liveActivitiesEnabled: true });
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
}, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
// The environment link can succeed while this device's own registration
// (the push-to-start token the relay needs) has not — don't claim Live
// Activities are live until the device is actually registered.
if (getAgentAwarenessRegistrationStatus() === "registered") {
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
} else {
Alert.alert(
"Couldn't finish enabling Live Activities",
"This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.",
);
}
}, [
connections,
environmentCount,
getToken,
isSignedIn,
liveActivitiesPreferenceEnabled,
promptSignIn,
savePreferences,
]);
const handleDeviceNotificationsChange = useCallback(
(enabled: boolean) => {
@@ -319,17 +376,20 @@ function ConfiguredSettingsRouteScreen() {
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: liveActivitiesPreferenceEnabled,
clerkToken: token,
connections,
}),
),
);
if (updateResult._tag === "Failure") {
setLiveActivityStatus("enabled");
reportAtomCommandResult(updateResult, {
label: "live activity disable",
});
return;
}
savePreferences({ liveActivitiesEnabled: false });
refreshManagedRelayEnvironments();
})();
return;
@@ -342,7 +402,15 @@ function ConfiguredSettingsRouteScreen() {
void linkEnvironments();
},
[connections, getToken, isSignedIn, linkEnvironments, promptSignIn],
[
connections,
getToken,
isSignedIn,
linkEnvironments,
liveActivitiesPreferenceEnabled,
promptSignIn,
savePreferences,
],
);
const openAccount = useCallback(() => {
@@ -360,12 +428,10 @@ function ConfiguredSettingsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<View className="gap-3">
@@ -393,7 +459,10 @@ function ConfiguredSettingsRouteScreen() {
icon="bell.badge"
label="Device Notifications"
disabled={notificationStatus === "checking" || notificationStatus === "unsupported"}
value={notificationStatus === "enabled"}
// Only reads as on when this device is actually registered with the
// relay; otherwise notifications cannot be delivered regardless of
// the local iOS permission.
value={notificationStatus === "enabled" && deviceRegistered}
onValueChange={handleDeviceNotificationsChange}
/>
<SettingsSwitchRow
@@ -402,7 +471,12 @@ function ConfiguredSettingsRouteScreen() {
}
icon="bolt.circle"
label="Live Activity Updates"
value={liveActivityStatus === "enabled" || liveActivityStatus === "linking"}
// Same gate: a saved preference is meaningless until the device
// registration the relay needs to push updates has succeeded.
value={
(liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
deviceRegistered
}
onValueChange={handleLiveActivitiesChange}
/>
</SettingsSection>
@@ -422,8 +496,26 @@ function ConfiguredSettingsRouteScreen() {
function AppSettingsSection() {
const icon = useThemeColor("--color-icon");
const version = Constants.expoConfig?.version ?? "0.0.0";
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
// missing variant never mislabels a production build as development.
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
// Which JS is actually running: the bundle shipped in the binary, or an OTA
// update downloaded on top of it. Surfacing this makes "am I even on the
// right build?" answerable at a glance.
const bundleLabel = Updates.isEnabled
? Updates.isEmbeddedLaunch
? "Embedded"
: Updates.updateId
? `OTA ${Updates.updateId.slice(0, 7)}`
: null
: null;
return (
<SettingsSection title="App">
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
<View className="flex-row items-center gap-4 p-4">
<SymbolView
name="info.circle"
@@ -433,12 +525,21 @@ function AppSettingsSection() {
weight="regular"
/>
<Text className="flex-1 text-lg text-foreground">Version</Text>
<Text className="text-lg text-foreground-muted">Alpha</Text>
<View className="items-end">
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
{bundleLabel ? (
<Text className="text-xs text-foreground-muted/70">{bundleLabel}</Text>
) : null}
</View>
</View>
</SettingsSection>
);
}
function capitalize(value: string): string {
return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
}
function ArchivedThreadsSettingsSection() {
return (
<SettingsSection title="Threads">
@@ -1,12 +1,7 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import { createContext, use, useCallback, useEffect, useMemo, type ReactNode } from "react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { Uniwind } from "uniwind";
@@ -17,7 +12,7 @@ import {
type AppearancePreferences,
type ResolvedAppearance,
} from "../../../lib/appearancePreferences";
import { loadPreferences, savePreferencesPatch } from "../../../lib/storage";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";
import { cacheTerminalFontSize } from "../../terminal/terminalUiState";
interface AppearancePreferencesContextValue {
@@ -52,55 +47,28 @@ function applyTextScaleVariables(baseFontSize: number) {
}
export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) {
const [preferences, setPreferences] = useState<AppearancePreferences>(() =>
resolveAppearancePreferences(null),
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const preferences = useMemo(
() =>
resolveAppearancePreferences(
AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value : null,
),
[preferencesResult],
);
const [isReady, setIsReady] = useState(false);
useEffect(() => {
let cancelled = false;
void loadPreferences()
.then((stored) => {
if (cancelled) {
return;
}
const resolved = resolveAppearancePreferences(stored);
setPreferences(resolved);
cacheTerminalFontSize(resolveAppearance(resolved).terminalFontSize);
setIsReady(true);
})
.catch(() => {
if (cancelled) {
return;
}
setIsReady(true);
});
return () => {
cancelled = true;
};
}, []);
const isReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
useEffect(() => {
applyTextScaleVariables(preferences.baseFontSize);
}, [preferences.baseFontSize]);
cacheTerminalFontSize(resolveAppearance(preferences).terminalFontSize);
}, [preferences]);
const updatePreferences = useCallback((patch: Partial<AppearancePreferences>) => {
setPreferences((current) => {
const next = resolveAppearancePreferences({ ...current, ...patch });
cacheTerminalFontSize(resolveAppearance(next).terminalFontSize);
void savePreferencesPatch({
baseFontSize: next.baseFontSize,
terminalFontSize: next.terminalFontSize,
codeFontSize: next.codeFontSize,
codeWordBreak: next.codeWordBreak,
}).catch(() => undefined);
return next;
});
}, []);
const updatePreferences = useCallback(
(patch: Partial<AppearancePreferences>) => {
savePreferences(patch);
},
[savePreferences],
);
const setBaseFontSize = useCallback(
(value: number) => {
@@ -150,7 +118,7 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
}
export function useAppearancePreferences(): AppearancePreferencesContextValue {
const context = useContext(AppearancePreferencesContext);
const context = use(AppearancePreferencesContext);
if (!context) {
throw new Error("useAppearancePreferences must be used within AppearancePreferencesProvider");
}
@@ -136,7 +136,7 @@ export function FontSizeSliderRow(props: {
};
return (
<View className="gap-1 p-4" style={{ opacity: disabled ? 0.45 : 1 }}>
<View className={disabled ? "gap-1 p-4 opacity-[0.45]" : "gap-1 p-4"}>
<View className="flex-row items-center gap-4">
<SymbolView
name={props.icon}
@@ -22,8 +22,11 @@ export function SettingsRow(props: {
const chevron = useThemeColor("--color-chevron");
const content = (
<View
className="flex-row items-center gap-4 p-4"
style={{ opacity: props.disabled ? 0.45 : 1 }}
className={
props.disabled
? "flex-row items-center gap-4 p-4 opacity-[0.45]"
: "flex-row items-center gap-4 p-4"
}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="shrink-0 text-lg text-foreground" numberOfLines={1}>
@@ -7,10 +7,7 @@ export function SettingsSection(props: { readonly title: string; readonly childr
return (
<View className="gap-2">
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">{props.title}</Text>
<View
className="overflow-hidden rounded-[28px] bg-card"
style={{ borderCurve: "continuous" }}
>
<View className="overflow-hidden rounded-[28px] border-continuous bg-card">
{props.children}
</View>
</View>
@@ -20,8 +20,11 @@ export function SettingsSwitchRow(props: {
return (
<View
className="flex-row items-center gap-4 p-4"
style={{ opacity: props.disabled ? 0.45 : 1 }}
className={
props.disabled
? "flex-row items-center gap-4 p-4 opacity-[0.45]"
: "flex-row items-center gap-4 p-4"
}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="flex-1 text-lg text-foreground">{props.label}</Text>
@@ -1 +1,5 @@
export type SettingsSheetTarget = "SettingsEnvironments" | "SettingsArchive" | "SettingsAppearance";
export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsClientStorage";
@@ -82,9 +82,9 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
return (
<View
className="flex-1"
style={[
{
flex: 1,
backgroundColor: theme.background,
borderRadius: 8,
overflow: "hidden",
@@ -93,19 +93,18 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
]}
onLayout={handleLayout}
>
<View style={{ flex: 1, paddingHorizontal: 10, paddingVertical: 8 }}>
<View className="flex-1 px-2.5 py-2">
<Text
className="text-2xs"
className="pb-2 text-2xs"
style={{
color: theme.mutedForeground,
paddingBottom: 8,
}}
>
{statusLabel}
</Text>
<ScrollView
style={{ flex: 1 }}
contentContainerStyle={{ paddingBottom: 12 }}
className="flex-1"
contentContainerClassName="pb-3"
showsVerticalScrollIndicator={false}
>
<Text
@@ -122,13 +121,9 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
</ScrollView>
</View>
<View
className="flex-row items-center gap-2 border-t p-2"
style={{
borderTopWidth: 1,
borderTopColor: theme.border,
flexDirection: "row",
alignItems: "center",
gap: 8,
padding: 8,
}}
>
<TextInput
@@ -165,13 +160,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
})}
onPress={() => props.onInput("\u0003")}
>
<Text
className="text-2xs"
style={{
color: theme.foreground,
fontFamily: "DMSans_700Bold",
}}
>
<Text className="text-2xs font-t3-bold" style={{ color: theme.foreground }}>
Ctrl-C
</Text>
</Pressable>
@@ -929,7 +929,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
</NativeHeaderToolbar>
) : null}
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
<View className="flex-1" style={{ backgroundColor: terminalTheme.background }}>
{!isEnvironmentReady ? (
<EnvironmentConnectionNotice
environmentLabel={
@@ -949,7 +949,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
/>
) : (
<>
<View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
<View className="flex-1" style={{ paddingBottom: terminalBottomInset }}>
<TerminalSurface
buffer={terminalSurfaceBuffer}
fontSize={fontSize}
@@ -968,10 +968,10 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
offset={{ closed: 0, opened: 0 }}
>
<View
className="border-t"
style={{
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
borderTopWidth: 1,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
}}
>
@@ -154,23 +154,11 @@ const CommandRow = memo(function CommandRow(props: {
) : iconName ? (
<SymbolView name={iconName} size={14} tintColor={iconColor} type="monochrome" />
) : null}
<Text
className="text-base font-t3-medium text-foreground"
numberOfLines={1}
style={{ flexShrink: 0 }}
>
<Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>
{props.item.label}
</Text>
{props.item.description ? (
<Text
className="text-xs"
numberOfLines={1}
style={{
flex: 1,
minWidth: 0,
color: "#a1a1aa",
}}
>
<Text className="min-w-0 flex-1 text-xs text-zinc-400" numberOfLines={1}>
{props.item.description}
</Text>
) : null}
@@ -187,18 +175,15 @@ export const ComposerCommandPopover = memo(function ComposerCommandPopover(
return (
<PopoverSurface isDarkMode={isDarkMode}>
{label ? (
<View style={{ paddingHorizontal: 14, paddingTop: 10, paddingBottom: 4 }}>
<Text
className="text-3xs font-t3-bold text-foreground-muted"
style={{ letterSpacing: 0.8, textTransform: "uppercase" }}
>
<View className="px-3.5 pt-2.5 pb-1">
<Text className="text-3xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
{label}
</Text>
</View>
) : null}
{props.items.length > 0 ? (
<ScrollView
style={{ maxHeight: 180 }}
className="max-h-[180px]"
keyboardShouldPersistTaps="always"
showsVerticalScrollIndicator={false}
>
@@ -212,7 +197,7 @@ export const ComposerCommandPopover = memo(function ComposerCommandPopover(
))}
</ScrollView>
) : (
<View style={{ paddingHorizontal: 14, paddingVertical: 10 }}>
<View className="px-3.5 py-2.5">
<Text className="text-xs text-foreground-tertiary">
{emptyText(props.triggerKind, props.isLoading)}
</Text>
@@ -47,7 +47,8 @@ export function GitActionProgressOverlay(props: {
<Animated.View
entering={FadeIn.duration(200)}
exiting={FadeOut.duration(150)}
style={{ top: insets.top + 48, left: 12, right: 12, position: "absolute", zIndex: 100 }}
className="absolute inset-x-3 z-[100]"
style={{ top: insets.top + 48 }}
pointerEvents="box-none"
>
<Pressable onPress={handlePress}>
@@ -4,7 +4,6 @@ import { useCallback, useEffect, useMemo, useRef } from "react";
import { Alert, InteractionManager, View, useColorScheme } from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { EnvironmentId } from "@t3tools/contracts";
import {
@@ -34,6 +33,8 @@ import {
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
import { useProjects } from "../../state/entities";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
@@ -110,8 +111,7 @@ export function NewTaskDraftScreen(props: {
};
}, [props.pendingTaskId, cancelEditingPendingTask]);
const borderColor = useThemeColor("--color-border");
const bodyText = useScaledTextRole("body");
const headlineText = useScaledTextRole("headline");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
@@ -129,12 +129,13 @@ export function NewTaskDraftScreen(props: {
lastInitialProjectRefRef.current = props.initialProjectRef;
appliedInitialProjectKeyRef.current = null;
}
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
const initialEnvironmentId = props.initialProjectRef?.environmentId;
const initialProjectId = props.initialProjectRef?.projectId;
if (initialEnvironmentId && initialProjectId) {
const directProject =
projects.find(
(project) =>
project.environmentId === props.initialProjectRef?.environmentId &&
project.id === props.initialProjectRef?.projectId,
project.environmentId === initialEnvironmentId && project.id === initialProjectId,
) ?? null;
if (directProject) {
@@ -523,6 +524,14 @@ export function NewTaskDraftScreen(props: {
}
flow.setSubmitting(true);
// Arm the lock-screen card before the async thread creation: backgrounding
// the app right after tapping submit would otherwise reject the foreground
// -only Activity start. If creation fails, the token registration's replay
// finds no work and ends the card within seconds.
armAgentAwarenessLiveActivityForLocalWork({
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
projectTitle: selectedProject.title,
});
const result = await createProjectThread({
project: selectedProject,
modelSelection,
@@ -589,8 +598,8 @@ export function NewTaskDraftScreen(props: {
<View className="flex-1 bg-sheet">
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
<KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
<View style={{ flex: 1, minHeight: 0, paddingHorizontal: 20, paddingTop: 8 }}>
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View className="min-h-0 flex-1 px-5 pt-2">
<ComposerEditor
ref={promptInputRef}
autoFocus
@@ -602,19 +611,13 @@ export function NewTaskDraftScreen(props: {
onPasteImages={(uris) => void handleNativePasteImages(uris)}
placeholder={`Describe a coding task in ${selectedProject.title}`}
style={{ flex: 1, minHeight: 0 }}
textStyle={bodyText}
textStyle={headlineText}
/>
</View>
<View
style={{
borderTopWidth: 1,
borderTopColor: borderColor,
paddingBottom: controlsBottomPadding,
}}
>
<View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
{flow.attachments.length > 0 ? (
<View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
<View className="px-4 pt-3">
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={flow.removeAttachment}
@@ -6,6 +6,7 @@ import { useMemo } from "react";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { cn } from "../../lib/cn";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
@@ -79,7 +80,6 @@ export function NewTaskRouteScreen() {
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const accentColor = useThemeColor("--color-icon-muted");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
@@ -130,7 +130,7 @@ export function NewTaskRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
className="flex-1"
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
@@ -175,7 +175,6 @@ export function NewTaskRouteScreen() {
return (
<Pressable
key={item.key}
className="bg-card"
onPress={() =>
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
@@ -186,16 +185,12 @@ export function NewTaskRouteScreen() {
},
})
}
style={{
paddingHorizontal: 16,
paddingVertical: 14,
borderTopWidth: isFirst ? 0 : 1,
borderTopColor: borderSubtleColor,
borderTopLeftRadius: isFirst ? 24 : 0,
borderTopRightRadius: isFirst ? 24 : 0,
borderBottomLeftRadius: isLast ? 24 : 0,
borderBottomRightRadius: isLast ? 24 : 0,
}}
className={cn(
"bg-card px-4 py-3.5",
!isFirst && "border-t border-border-subtle",
isFirst && "rounded-t-[24px]",
isLast && "rounded-b-[24px]",
)}
>
<View className="flex-row items-center justify-between gap-3">
<View className="h-7 w-7 items-center justify-center">
@@ -25,7 +25,9 @@ import {
type ViewStyle,
} from "react-native";
import ImageViewing from "react-native-image-viewing";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { AppText as Text } from "../../components/AppText";
@@ -112,6 +114,10 @@ export interface ThreadComposerProps {
* The pill / card container — renders as LiquidGlassView on supported
* iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
*/
// One timing for every piece of the expanded↔compact morph so the surface,
// toolbar, and siblings move together instead of popping between layouts.
const COMPOSER_LAYOUT_TRANSITION = LinearTransition.duration(220);
function ComposerSurface(props: {
readonly children: ReactNode;
readonly style: ViewStyle;
@@ -130,7 +136,7 @@ function ComposerSurface(props: {
if (isLiquidGlassSupported) {
return (
<View style={shadowStyle}>
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
<LiquidGlassView
effect="regular"
interactive
@@ -139,12 +145,12 @@ function ComposerSurface(props: {
>
{props.children}
</LiquidGlassView>
</View>
</Animated.View>
);
}
return (
<View style={shadowStyle}>
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
<View
style={[
props.style,
@@ -157,7 +163,7 @@ function ComposerSurface(props: {
>
{props.children}
</View>
</View>
</Animated.View>
);
}
@@ -494,12 +500,24 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
if (inFlightThreadIdsRef.current.has(threadKey)) return;
inFlightThreadIdsRef.current.add(threadKey);
// Sending a prompt starts agent work: arm the lock-screen card now, while
// the app is foregrounded and the activity token can be registered.
armAgentAwarenessLiveActivityForLocalWork({
threadTitle: props.selectedThread.title,
projectTitle: props.environmentLabel ?? "T3 Code",
});
try {
await onSendMessage();
} finally {
inFlightThreadIdsRef.current.delete(threadKey);
}
}, [onSendMessage, props.environmentId, props.selectedThread.id]);
}, [
onSendMessage,
props.environmentId,
props.environmentLabel,
props.selectedThread.id,
props.selectedThread.title,
]);
const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => {
if (!composerTrigger) return;
@@ -669,9 +687,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}
return (
<View
<Animated.View
className="px-4"
layout={COMPOSER_LAYOUT_TRANSITION}
style={{
paddingHorizontal: 16,
paddingTop: isExpanded ? 8 : 6,
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
experimental_backgroundImage: isDarkMode
@@ -679,21 +698,13 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
}}
>
<View
className="w-full"
style={{ alignSelf: "center", maxWidth: props.contentMaxWidth, position: "relative" }}
<Animated.View
className="relative w-full self-center"
layout={COMPOSER_LAYOUT_TRANSITION}
style={{ maxWidth: props.contentMaxWidth }}
>
{composerTrigger && composerMenuItems.length > 0 ? (
<View
style={{
position: "absolute",
bottom: "100%",
left: 0,
right: 0,
marginBottom: 8,
zIndex: 10,
}}
>
<View className="absolute inset-x-0 bottom-full z-10 mb-2">
<ComposerCommandPopover
items={composerMenuItems}
triggerKind={composerTrigger.kind}
@@ -733,16 +744,20 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
>
{/* Attachment strip — inside the card, above the text input */}
{isExpanded ? (
<View style={{ paddingBottom: props.draftAttachments.length > 0 ? 10 : 0 }}>
<Animated.View
className={props.draftAttachments.length > 0 ? "pb-2.5" : undefined}
entering={FadeIn.duration(160)}
exiting={FadeOut.duration(120)}
>
<ComposerAttachmentStrip
attachments={props.draftAttachments}
onRemove={props.onRemoveDraftImage}
onPressImage={onPressImage}
/>
</View>
</Animated.View>
) : null}
<View style={isExpanded ? undefined : { flex: 1, minWidth: 0 }}>
<View className={isExpanded ? undefined : "min-w-0 flex-1"}>
<ComposerEditor
ref={inputRef}
multiline
@@ -773,37 +788,22 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
textStyle={{
...bodyText,
color: foregroundColor,
fontFamily: "DMSans_400Regular",
}}
/>
</View>
{!isExpanded && props.draftAttachments.length > 0 ? (
<View style={{ flexDirection: "row", gap: 4, paddingLeft: 4 }}>
<View className="flex-row gap-1 pl-1">
{props.draftAttachments.slice(0, 3).map((image) => (
<Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
<Image
source={{ uri: image.previewUri }}
className="bg-subtle"
style={{
width: 30,
height: 30,
borderRadius: 8,
}}
className="size-[30px] rounded-lg bg-subtle"
resizeMode="cover"
/>
</Pressable>
))}
{props.draftAttachments.length > 3 ? (
<View
className="bg-subtle-strong"
style={{
width: 30,
height: 30,
borderRadius: 8,
alignItems: "center",
justifyContent: "center",
}}
>
<View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
<Text className="text-foreground-muted text-2xs font-t3-bold">
+{props.draftAttachments.length - 3}
</Text>
@@ -812,81 +812,87 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</View>
) : null}
{!isExpanded ? (
showStopAction ? (
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
) : (
<ControlPill
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
/>
)
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
{showStopAction ? (
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
) : (
<ControlPill
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
/>
)}
</Animated.View>
) : null}
</ComposerSurface>
{/* Toolbar row — matches draft page layout (expanded only) */}
{isExpanded ? (
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
<ComposerToolbarScroller
fadeOpaque={toolbarFadeOpaque}
fadeTransparent={toolbarFadeTransparent}
>
<ComposerToolbarButton
icon="plus"
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
<ComposerToolbarScroller
fadeOpaque={toolbarFadeOpaque}
fadeTransparent={toolbarFadeTransparent}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
icon="stop.fill"
variant="danger"
onPress={props.onStopThread}
icon="plus"
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
) : null}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={sendLabel}
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
showChevron={false}
/>
</ComposerToolbarRow>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
icon="stop.fill"
variant="danger"
onPress={props.onStopThread}
showChevron={false}
/>
) : null}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={sendLabel}
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
showChevron={false}
/>
</ComposerToolbarRow>
</Animated.View>
) : null}
{/* Queue count */}
{props.queueCount > 0 ? (
<Text className="text-xs text-foreground-muted" style={{ paddingTop: 8 }}>
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
automatically.
</Text>
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
<Text className="pt-2 text-xs text-foreground-muted">
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
automatically.
</Text>
</Animated.View>
) : null}
</View>
</Animated.View>
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
@@ -896,6 +902,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</View>
</Animated.View>
);
});
@@ -17,11 +17,10 @@ import type {
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import * as Haptics from "expo-haptics";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import { Platform, View, type GestureResponderEvent } from "react-native";
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { runOnJS } from "react-native-reanimated";
import { AppText as Text } from "../../components/AppText";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
@@ -73,7 +72,6 @@ export interface ThreadDetailScreenProps {
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onOpenDrawer: () => void;
readonly onOpenConnectionEditor: () => void;
readonly onChangeDraftMessage: (value: string) => void;
readonly onPickDraftImages: () => Promise<void>;
@@ -173,7 +171,11 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
}, [threadId, feed]);
}
const WORKING_INDICATOR_HEIGHT = 44;
// Pre-measurement estimate for the working pill's slot (the real height is
// measured via onComposerLayout since the pill lives inside the composer
// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
const WORKING_INDICATOR_HEIGHT = 52;
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
readonly startedAt: string;
@@ -190,7 +192,11 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
return (
<View className="px-4 pb-2" style={{ flexShrink: 0 }}>
<Animated.View
className="shrink-0 px-4 pb-2 pt-2"
entering={FadeInDown.duration(200)}
exiting={FadeOut.duration(140)}
>
<View className="self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]">
<View className="flex-row items-center gap-2">
<View className="flex-row items-center gap-1">
@@ -203,13 +209,11 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
</Text>
</View>
</View>
</View>
</Animated.View>
);
});
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const { onOpenDrawer } = props;
const insets = useSafeAreaInsets();
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
@@ -243,11 +247,21 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
// The overlay's measured height includes the home-indicator inset (the
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
// UIKit add the safe-area bottom to the content inset AGAIN — leaving a
// dead strip between the resting content and the composer. Report the
// overlay height minus the safe area; UIKit adds it back, and ThreadFeed
// hands LegendList the same delta via contentInsetEndStaticAdjustment so
// its end-scroll math matches the real resting position.
const nativeInsetOvercount =
props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
listRef,
composerOverlayRef,
estimatedOverlayHeight,
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
-nativeInsetOvercount,
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
const showContent = props.showContent ?? true;
@@ -263,28 +277,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
[props.serverConfig, selectedInstanceId],
);
const completeDrawerGesture = useCallback(() => {
void Haptics.selectionAsync();
onOpenDrawer();
}, [onOpenDrawer]);
const drawerGestureThreshold = 80;
const headerDrawerGesture = useMemo(
() =>
Gesture.Pan()
.enabled(!isSplitLayout)
.hitSlop({ left: 0, width: 40 })
.activeOffsetX([10, 999])
.failOffsetY([-24, 24])
.onEnd((event) => {
const translationX = Math.max(event.translationX, 0);
if (event.y < drawerGestureThreshold && translationX > 56) {
runOnJS(completeDrawerGesture)();
}
}),
[completeDrawerGesture, isSplitLayout],
);
useLayoutEffect(() => {
selectedThreadKeyRef.current = selectedThreadKey;
}, [selectedThreadKey]);
@@ -311,16 +303,31 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
return;
}
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
) {
return;
}
lastScrolledAnchorMessageIdRef.current = null;
freeze.set(false);
});
// Wait for the keyboard dismissal (started by blur() on send) to finish
// before scrolling: scrollMessageToEnd freezes keyboard-driven inset
// updates while it runs, and a close event swallowed by that freeze
// leaves the keyboard padding permanently applied — overshooting the
// anchor and leaving a phantom bottom inset once the reply streams in.
void KeyboardController.dismiss()
.then(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
) {
return;
}
return scrollMessageToEnd({ animated: true, closeKeyboard: false });
})
.catch(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
) {
return;
}
lastScrolledAnchorMessageIdRef.current = null;
freeze.set(false);
});
});
return () => cancelAnimationFrame(frame);
}, [
@@ -379,115 +386,120 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
}, []);
return (
<GestureDetector gesture={headerDrawerGesture}>
<View className="flex-1">
{showContent ? (
<View
style={{ flex: 1 }}
onTouchStart={handleFeedTouchStart}
onTouchMove={handleFeedTouchMove}
onTouchEnd={handleFeedTouchEnd}
onTouchCancel={handleFeedTouchCancel}
>
<ThreadFeed
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
<View className="flex-1">
{showContent ? (
<View
className="flex-1"
onTouchStart={handleFeedTouchStart}
onTouchMove={handleFeedTouchMove}
onTouchEnd={handleFeedTouchEnd}
onTouchCancel={handleFeedTouchCancel}
>
<ThreadFeed
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
/>
</View>
) : (
<View className="flex-1" />
)}
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
{/* No paddingTop here: the overlay's measured height becomes the
list's bottom inset, so any padding above the pill/composer
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
<Animated.View
className="w-full self-center"
layout={LinearTransition.duration(220)}
style={{ maxWidth: contentMaxWidth }}
>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
entering={FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</Animated.View>
) : null}
</Animated.View>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
</View>
) : (
<View style={{ flex: 1 }} />
)}
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
ref={composerOverlayRef}
onLayout={onComposerLayout}
style={{ width: "100%", paddingTop: 8 }}
>
<View style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
) : null}
</View>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
</View>
</KeyboardStickyView>
) : null}
</View>
</GestureDetector>
</KeyboardStickyView>
) : null}
</View>
);
});
+159 -64
View File
@@ -4,11 +4,14 @@ import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { SymbolView } from "expo-symbols";
import { HeaderHeightContext } from "@react-navigation/elements";
import { useNavigation } from "@react-navigation/native";
import {
memo,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
@@ -41,8 +44,15 @@ import {
import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { type SharedValue } from "react-native-reanimated";
import Animated, {
FadeIn,
FadeInUp,
FadeOut,
LinearTransition,
type SharedValue,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import {
hasNativeSelectableMarkdownText,
@@ -96,6 +106,19 @@ function formatMessageTime(input: string): string {
return MESSAGE_TIME_FORMATTER.format(timestamp);
}
// Rows shift when content above them grows (streaming text, work-log folds);
// animating the container position turns those jumps into slides.
const FEED_ITEM_LAYOUT_TRANSITION = LinearTransition.duration(180);
// Entering animations must only play for rows born just now — LegendList
// remounts rows when they scroll back into view, and replaying an entrance for
// old content would be its own kind of jank.
const FRESH_ENTRY_WINDOW_MS = 3_000;
function isFreshTimestamp(input: string): boolean {
const timestamp = Date.parse(input);
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS;
}
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
@@ -212,10 +235,6 @@ const markdownLinkStyles = StyleSheet.create({
favicon: {
borderRadius: 3,
},
file: {
fontFamily: "DMSans_700Bold",
fontWeight: "700",
},
});
const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
@@ -228,12 +247,12 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
return (
<NativeText
className="font-sans"
onPress={() => {
void Linking.openURL(props.href);
}}
style={{
color: props.color,
fontFamily: "DMSans_400Regular",
textDecorationLine: "none",
}}
>
@@ -292,6 +311,8 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
);
const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"];
const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground"));
const regularFontFamily = useFontFamily("regular");
const boldFontFamily = useFontFamily("bold");
return useMemo(() => {
const markdownBodyColor = colors.body;
@@ -343,8 +364,8 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
h6: markdownFontSizes.h6,
},
fontFamilies: {
regular: "DMSans_400Regular",
heading: "DMSans_700Bold",
regular: regularFontFamily,
heading: boldFontFamily,
mono: "ui-monospace",
},
headingWeight: "700",
@@ -366,7 +387,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
bold: {
fontWeight: "700",
color: markdownStrongColor,
fontFamily: "DMSans_700Bold",
fontFamily: boldFontFamily,
},
italic: { fontStyle: "italic" },
link: {
@@ -382,7 +403,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
marginVertical: 10,
},
heading: {
fontFamily: "DMSans_700Bold",
fontFamily: boldFontFamily,
color: markdownStrongColor,
marginTop: 18,
marginBottom: 8,
@@ -406,8 +427,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
if (presentation.kind === "file") {
return (
<NativeText
className="font-t3-bold"
onPress={() => onLinkPress(href)}
style={[markdownLinkStyles.file, { color: inlineTextColor }]}
style={{ color: inlineTextColor }}
>
<Image
source={markdownFileIconSource(presentation.icon)}
@@ -431,6 +453,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
const linkHref = presentation.href;
return (
<NativeText
className="underline"
onPress={
linkHref
? () => {
@@ -438,17 +461,14 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
}
: undefined
}
style={{
color: markdownLinkColor,
textDecorationLine: "underline",
}}
style={{ color: markdownLinkColor }}
>
{children}
</NativeText>
);
},
list: ({ node, Renderer, ordered = false, start = 1 }) => (
<View style={{ marginTop: 2, marginBottom: 8 }}>
<View className="mt-0.5 mb-2">
{node.children?.map((child, index) => {
const childKey = `${child.type}:${child.beg ?? "unknown"}:${child.end ?? "unknown"}`;
if (child.type === "task_list_item") {
@@ -457,20 +477,13 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
);
}
return (
<View
key={childKey}
style={{
flexDirection: "row",
alignItems: "flex-start",
marginBottom: 3,
}}
>
<View className="mb-[3px] flex-row items-start" key={childKey}>
<NativeText
className="font-sans"
style={{
width: ordered ? 22 : 12,
marginRight: 5,
color: inlineTextColor,
fontFamily: "DMSans_400Regular",
fontSize: markdownFontSizes.m,
lineHeight: markdownFontSizes.bodyLineHeight,
textAlign: ordered ? "right" : "center",
@@ -478,7 +491,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
>
{ordered ? `${start + index}.` : "•"}
</NativeText>
<View style={{ flex: 1, minWidth: 0 }}>
<View className="min-w-0 flex-1">
<Renderer node={child} depth={1} inListItem parentIsText={false} />
</View>
</View>
@@ -490,9 +503,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
const value = content ?? "";
return (
<NativeText
className="font-mono"
style={{
color: inlineCodeTextColor,
fontFamily: "ui-monospace",
fontSize: markdownFontSizes.codeBlockFontSize,
lineHeight: markdownFontSizes.bodyLineHeight,
}}
@@ -508,31 +521,24 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
: {}),
code_block: ({ content, language }) => (
<View
className="my-3 overflow-hidden rounded-[10px] border"
style={{
backgroundColor: blockBackgroundColor,
borderRadius: 10,
borderWidth: 1,
borderColor: markdownHrColor,
marginVertical: 12,
overflow: "hidden",
}}
>
{language ? (
<View
className="border-b px-3.5 py-2"
style={{
borderBottomWidth: 1,
borderBottomColor: markdownHrColor,
paddingHorizontal: 14,
paddingVertical: 8,
}}
>
<NativeText
className="font-mono uppercase opacity-70"
style={{
color: markdownBodyColor,
fontFamily: "ui-monospace",
fontSize: markdownFontSizes.codeBlockFontSize,
opacity: 0.7,
textTransform: "uppercase",
}}
>
{language}
@@ -543,13 +549,13 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
horizontal
showsHorizontalScrollIndicator={false}
bounces={false}
contentContainerStyle={{ paddingHorizontal: 14, paddingVertical: 12 }}
contentContainerClassName="px-3.5 py-3"
>
<NativeText
selectable
className="font-mono"
style={{
color: blockTextColor,
fontFamily: "ui-monospace",
fontSize: markdownFontSizes.codeBlockFontSize,
lineHeight: markdownFontSizes.codeBlockLineHeight,
}}
@@ -579,7 +585,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
bold: {
fontWeight: "700",
color: markdownUserBodyColor,
fontFamily: "DMSans_700Bold",
fontFamily: boldFontFamily,
},
heading: {
...baseStyles.heading,
@@ -633,9 +639,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
fontSize: nativeMarkdownTypography.fontSize,
lineHeight: nativeMarkdownTypography.lineHeight,
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
fontFamily: regularFontFamily,
headingFontFamily: boldFontFamily,
boldFontFamily,
},
},
assistant: {
@@ -664,13 +670,21 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
fontSize: nativeMarkdownTypography.fontSize,
lineHeight: nativeMarkdownTypography.lineHeight,
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
fontFamily: regularFontFamily,
headingFontFamily: boldFontFamily,
boldFontFamily,
},
},
};
}, [colors, inlineSkillForeground, markdownFontSizes, nativeMarkdownTypography, onLinkPress]);
}, [
boldFontFamily,
colors,
inlineSkillForeground,
markdownFontSizes,
nativeMarkdownTypography,
onLinkPress,
regularFontFamily,
]);
}
function renderFeedEntry(
@@ -749,8 +763,12 @@ function renderFeedEntry(
!message.streaming;
if (isUser) {
const enterAnimated = isFreshTimestamp(message.createdAt);
return (
<View className="mb-5 items-end">
<Animated.View
className="mb-5 items-end"
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
>
<View
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
style={{
@@ -794,7 +812,7 @@ function renderFeedEntry(
/>
) : null}
</View>
</View>
</Animated.View>
);
}
@@ -804,8 +822,12 @@ function renderFeedEntry(
return null;
}
const enterAnimated = isFreshTimestamp(message.createdAt);
return (
<View className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}>
<Animated.View
className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}
{...(enterAnimated ? { entering: FadeIn.duration(220) } : {})}
>
{message.text.trim().length > 0 ? (
hasNativeSelectableMarkdownText() ? (
<SelectableMarkdownText
@@ -850,7 +872,7 @@ function renderFeedEntry(
</Text>
</View>
) : null}
</View>
</Animated.View>
);
}
@@ -989,11 +1011,10 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: {
return (
<View
className="w-full overflow-hidden rounded-[16px] border"
className="w-full overflow-hidden rounded-[16px] border border-continuous"
style={{
backgroundColor: props.colors.background,
borderColor: props.colors.border,
borderCurve: "continuous",
}}
>
<View
@@ -1001,8 +1022,8 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: {
style={{ borderColor: props.colors.border }}
>
<View
className="size-6 items-center justify-center rounded-[7px]"
style={{ backgroundColor: props.colors.mutedBackground, borderCurve: "continuous" }}
className="size-6 items-center justify-center rounded-[7px] border-continuous"
style={{ backgroundColor: props.colors.mutedBackground }}
>
<SymbolView
name="doc.text"
@@ -1055,9 +1076,9 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: {
>
<NativeText
selectable
className="font-mono"
style={{
color: props.colors.text,
fontFamily: "ui-monospace",
fontSize: codeSurface.fontSize,
lineHeight: codeSurface.rowHeight,
}}
@@ -1146,6 +1167,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const [viewportWidth, setViewportWidth] = useState(() =>
props.layoutVariant === "split" ? 0 : windowWidth,
);
const [viewportHeight, setViewportHeight] = useState(0);
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
@@ -1177,6 +1199,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const bottomContentInset = props.contentBottomInset ?? 18;
const usesNativeAutomaticInsets =
props.usesAutomaticContentInsets === true && Platform.OS === "ios";
// With automatic insets the header inset lives in UIKit's adjustedContentInset,
// which LegendList's JS anchoring math cannot see — it measures the anchored
// end space from the scroll view's frame top. Fold the header height back into
// the anchor offset or a just-sent message anchors underneath the header and
// the oversized end space keeps maintainScrollAtEnd snapping away from earlier
// messages. Read the context directly (useHeaderHeight throws outside a
// header-providing screen) and fall back to the standard iOS bar height.
const navigationHeaderHeight = useContext(HeaderHeightContext);
const anchorTopInset = usesNativeAutomaticInsets
? navigationHeaderHeight || insets.top + 44
: topContentInset;
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const userBubbleColor = useThemeColor("--color-user-bubble");
@@ -1242,13 +1275,19 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
const handleScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + topContentInset > 6);
// anchorTopInset, not topContentInset: under automatic insets the list
// rests at contentOffset.y = -headerHeight (the inset lives only in
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
// header height back or the material toggles a full header too late.
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
},
[reportHeaderMaterialVisibility, topContentInset],
[reportHeaderMaterialVisibility, anchorTopInset],
);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
const nextHeight = Math.round(event.nativeEvent.layout.height);
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
}, []);
useEffect(() => {
@@ -1275,15 +1314,30 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
);
// The empty↔filled key below remounts the list, which resets its imperative
// content-inset override — and useKeyboardChatComposerInset (mounted above
// the remount boundary) deduplicates by height, so it never re-reports the
// composer inset to the fresh instance. Without this, the remounted list's
// initial scroll-to-end computes with a zero end inset and rests one
// composer-height short of the end. Layout effect: it must land before the
// list's first positioning tick or the one-shot initial scroll misses it.
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
useLayoutEffect(() => {
const bottom = props.contentInsetEndAdjustment.value;
if (bottom > 0) {
props.listRef.current?.reportContentInset({ bottom });
}
}, [listMountKey, props.contentInsetEndAdjustment, props.listRef]);
const anchoredEndSpace = useMemo(
() =>
resolveChatListAnchoredEndSpace(
presentedFeed,
props.anchorMessageId,
(entry) => (entry.type === "message" ? entry.id : null),
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
{ anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET },
),
[presentedFeed, props.anchorMessageId, topContentInset],
[presentedFeed, props.anchorMessageId, anchorTopInset],
);
const terminalAssistantMessageIds = useMemo(() => {
const terminalIdsByTurn = new Map<TurnId, string>();
@@ -1496,8 +1550,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
return (
<>
<View style={{ flex: 1 }} onLayout={handleViewportLayout}>
<View style={{ flex: 1 }}>
<View className="flex-1" onLayout={handleViewportLayout}>
<View className="flex-1">
<KeyboardAwareLegendList
ref={props.listRef}
// The empty↔filled key remounts the list when messages first
@@ -1506,8 +1560,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// an already-attached list under a transparent header can pin
// short content at offset 0 (one header-height too high). A fresh
// mount positions during attach, where UIKit applies the inset.
key={`${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`}
key={listMountKey}
style={{ flex: 1 }}
// RN 0.81+ drops touches inside the contentInset area
// (facebook/react-native#54123); the anchored end space after a send
// is pure inset, so without this the blank region can't be scrolled.
applyWorkaroundForContentInsetHitTestBug
contentInsetAdjustmentBehavior={usesNativeAutomaticInsets ? "automatic" : "never"}
automaticallyAdjustsScrollIndicatorInsets={usesNativeAutomaticInsets}
{...(usesNativeAutomaticInsets
@@ -1523,13 +1581,35 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
itemLayoutAnimation={FEED_ITEM_LAYOUT_TRANSITION}
// Patched LegendList prop (patches/@[email protected]):
// lets its scroll math clamp programmatic scrolls to -headerInset
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
// content rest below the transparent header rather than at frame top.
contentInsetStartAdjustment={usesNativeAutomaticInsets ? anchorTopInset : 0}
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
// UIKit's automatic behavior adds the safe-area bottom on top of the
// raw contentInset the keyboard integration writes. The detail screen
// under-reports the composer inset by this amount (see
// ThreadDetailScreen); this tells LegendList's scroll math about the
// extra so programmatic end scrolls land at the true resting offset.
contentInsetEndStaticAdjustment={usesNativeAutomaticInsets ? insets.bottom : 0}
// The keyboard integration's offset math (end pinning, max scroll)
// must add the same UIKit-added extra, or its keyboard-open end
// targets land one safe-area short of the true resting offset.
adjustedInsetCompensation={usesNativeAutomaticInsets ? insets.bottom : 0}
freeze={props.freeze}
// Animated: on send, the optimistic message's dataChange fires
// maintainScrollAtEnd before any render-cycle suppression could
// engage — an instant snap there teleports the feed to the anchor
// instead of scrolling to it. Keeping it enabled (animated) during
// anchor scrolls also lets it correct a scroll that landed on a
// stale end target once the anchor row finishes measuring.
maintainScrollAtEnd={
disclosureToggleSettling
? false
: {
animated: false,
animated: true,
on: {
dataChange: true,
itemLayout: true,
@@ -1548,6 +1628,21 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
// Seed the list's scroll math with the real viewport before its own
// onLayout: the empty→filled remount can then tell at mount that
// short content underflows the viewport and skip programmatic
// positioning entirely (any offset write during screen attach races
// UIKit's adjustedContentInset application and lands high or low).
{...(viewportHeight > 0 && viewportWidth > 0
? { estimatedListSize: { height: viewportHeight, width: viewportWidth } }
: {})}
// RN's native scrollTo command clamps targets to a floor of
// -contentInset.top using the RAW inset — under automatic insets the
// header inset only exists in adjustedContentInset, so scrolls to
// negative offsets (content top below the transparent header) get
// clamped to 0. This prop disables that clamp; UIKit still bounces
// user overscroll back to the adjusted rest position.
scrollToOverflowEnabled
estimatedItemSize={180}
initialScrollAtEnd
onScroll={handleScroll}
@@ -1,255 +0,0 @@
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
type ColorValue,
Modal,
Pressable,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
runOnJS,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { StatusPill } from "../../components/StatusPill";
import { useProjects, useThreadShells } from "../../state/entities";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { resolveThreadStatus } from "./threadPresentation";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { buildThreadNavigationGroups } from "./thread-navigation-groups";
export function ThreadNavigationDrawer(props: {
readonly visible: boolean;
readonly selectedThreadKey: string | null;
readonly onClose: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onStartNewTask: () => void;
}) {
const insets = useSafeAreaInsets();
const { width } = useWindowDimensions();
const drawerWidth = Math.min(width * 0.84, 360);
const [mounted, setMounted] = useState(props.visible);
const translateX = useSharedValue(-drawerWidth);
const overlayOpacity = useSharedValue(0);
const backdropColor = useThemeColor("--color-backdrop");
const drawerBg = useThemeColor("--color-drawer");
const drawerShadow = useThemeColor("--color-drawer-shadow");
const primaryForeground = useThemeColor("--color-primary-foreground");
const borderSubtleColor = useThemeColor("--color-border-subtle");
useEffect(() => {
if (props.visible) {
setMounted(true);
translateX.value = withTiming(0, { duration: 240 });
overlayOpacity.value = withTiming(1, { duration: 220 });
return;
}
overlayOpacity.value = withTiming(0, { duration: 180 });
translateX.value = withTiming(-drawerWidth, { duration: 220 }, (finished) => {
if (finished) {
runOnJS(setMounted)(false);
}
});
}, [drawerWidth, overlayOpacity, props.visible, translateX]);
const closeDrawer = useCallback(() => {
props.onClose();
}, [props]);
const panGesture = useMemo(
() =>
Gesture.Pan()
.activeOffsetX([-12, 12])
.failOffsetY([-24, 24])
.onUpdate((event) => {
translateX.value = Math.min(0, event.translationX);
})
.onEnd((event) => {
const shouldClose = event.translationX < -drawerWidth * 0.2 || event.velocityX < -500;
if (shouldClose) {
runOnJS(closeDrawer)();
return;
}
translateX.value = withTiming(0, { duration: 180 });
}),
[closeDrawer, drawerWidth, translateX],
);
const drawerStyle = useAnimatedStyle(() => ({
transform: [{ translateX: translateX.value }],
}));
const backdropStyle = useAnimatedStyle(() => ({
opacity: overlayOpacity.value,
}));
if (!mounted) {
return null;
}
return (
<Modal transparent visible={mounted} onRequestClose={props.onClose} statusBarTranslucent>
<View style={{ flex: 1 }}>
<Animated.View
pointerEvents="none"
style={[
{
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
backgroundColor: backdropColor,
},
backdropStyle,
]}
/>
<Pressable
style={{ position: "absolute", left: 0, right: 0, top: 0, bottom: 0 }}
onPress={props.onClose}
/>
<GestureDetector gesture={panGesture}>
<Animated.View
style={[
{
position: "absolute",
left: 0,
top: 0,
bottom: 0,
width: drawerWidth,
backgroundColor: drawerBg,
paddingTop: insets.top + 10,
paddingBottom: Math.max(insets.bottom, 18),
boxShadow: `20px 0 36px ${String(drawerShadow)}`,
},
drawerStyle,
]}
>
<View className="flex-row items-center justify-between px-4 pb-5">
<Text className="text-2xl font-t3-bold">Threads</Text>
<Pressable
onPress={() => {
props.onClose();
props.onStartNewTask();
}}
className="h-11 w-11 items-center justify-center rounded-full bg-primary"
>
<SymbolView
name="square.and.pencil"
size={17}
tintColor={primaryForeground}
type="monochrome"
/>
</Pressable>
</View>
<ThreadNavigationDrawerContent
bottomInset={Math.max(insets.bottom, 18)}
borderSubtleColor={borderSubtleColor}
selectedThreadKey={props.selectedThreadKey}
onClose={props.onClose}
onSelectThread={props.onSelectThread}
/>
</Animated.View>
</GestureDetector>
</View>
</Modal>
);
}
function ThreadNavigationDrawerContent(props: {
readonly bottomInset: number;
readonly borderSubtleColor: ColorValue;
readonly selectedThreadKey: string | null;
readonly onClose: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
}) {
const projects = useProjects();
const threads = useThreadShells();
const groupedThreads = useMemo(
() => buildThreadNavigationGroups({ projects, threads }),
[projects, threads],
);
return (
<ScrollView
showsVerticalScrollIndicator={false}
contentInset={{ bottom: props.bottomInset + 12 }}
contentContainerStyle={{
gap: 20,
paddingHorizontal: 14,
}}
>
{groupedThreads.map((group) => (
<View key={group.key} className="gap-3">
<Text
className="px-1 text-base font-t3-bold text-foreground-muted"
style={{ letterSpacing: -0.2 }}
>
{group.title}
</Text>
<View className="overflow-hidden rounded-[22px] bg-card">
{group.threads.length === 0 ? (
<View className="px-4 py-4">
<Text className="text-sm font-medium text-foreground-tertiary">No threads yet</Text>
</View>
) : (
group.threads.map((thread, index) => {
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
const selected = props.selectedThreadKey === threadKey;
const status = resolveThreadStatus(thread);
return (
<Pressable
key={threadKey}
onPress={() => {
props.onSelectThread(thread);
props.onClose();
}}
style={{
paddingHorizontal: 16,
paddingVertical: 15,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: props.borderSubtleColor,
backgroundColor: selected ? undefined : "transparent",
}}
className={selected ? "bg-subtle" : undefined}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text className="text-base font-t3-bold" numberOfLines={1}>
{thread.title}
</Text>
<Text
className="text-sm font-medium text-foreground-muted"
numberOfLines={1}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
{status ? <StatusPill {...status} /> : null}
</View>
</Pressable>
);
})
)}
</View>
</View>
))}
</ScrollView>
);
}
@@ -1,5 +1,8 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { SymbolView } from "expo-symbols";
@@ -94,8 +97,6 @@ function SidebarHeaderButtonGroup(props: {
const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
const SIDEBAR_STICKY_HEADER_FADE_HEIGHT = 44;
const IOS_SEARCH_FILL_DARK = "rgba(118, 118, 128, 0.24)";
const IOS_SEARCH_FILL_LIGHT = "rgba(118, 118, 128, 0.12)";
const SIDEBAR_HEADER_WASH_OPACITY = {
dark: [0.22, 0.14, 0.04],
light: [0.46, 0.3, 0.08],
@@ -107,6 +108,7 @@ interface ThreadNavigationSidebarProps {
readonly selectedThreadKey: string | null;
readonly onOpenSettings: () => void;
readonly onOpenEnvironmentSettings: () => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onRequestVisibility: () => void;
@@ -136,15 +138,13 @@ function NativeSidebarContainer(props: ThreadNavigationSidebarProps) {
return (
<View
testID="thread-navigation-sidebar"
style={[
styles.container,
{
width: props.width,
backgroundColor,
borderRightColor: borderColor,
borderRightWidth: StyleSheet.hairlineWidth,
},
]}
className="flex-1"
style={{
width: props.width,
backgroundColor,
borderRightColor: borderColor,
borderRightWidth: StyleSheet.hairlineWidth,
}}
>
<SidebarNavigationShell>
<ThreadNavigationSidebarPane {...props} nativeChrome />
@@ -334,11 +334,8 @@ function ThreadNavigationSidebarPane(
const backgroundColor = useThemeColor("--color-drawer");
const borderColor = useThemeColor("--color-border");
const foregroundColor = useThemeColor("--color-foreground");
const mutedColor = useThemeColor("--color-foreground-muted");
const placeholderColor = useThemeColor("--color-placeholder");
const searchBackgroundColor =
colorScheme === "dark" ? IOS_SEARCH_FILL_DARK : IOS_SEARCH_FILL_LIGHT;
const headerFadeColor = String(backgroundColor);
const headerWashOpacity = SIDEBAR_HEADER_WASH_OPACITY[colorScheme];
const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
@@ -413,6 +410,11 @@ function ThreadNavigationSidebarPane(
isFirst={item.isFirst}
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
// Same gating as the compact Home list: aggregated groups have no
// single target project, and pending-project groups hold a
// placeholder shell rather than a real project.
newThreadTarget={item.group.newThreadTarget}
onNewThread={props.onNewThreadInProject}
project={item.group.representative}
threadCount={item.group.threads.length + item.group.pendingTasks.length}
title={item.group.title}
@@ -480,6 +482,7 @@ function ThreadNavigationSidebarPane(
handleSwipeableWillOpen,
openPendingTask,
projectCwdByKey,
props.onNewThreadInProject,
props.selectedThreadKey,
props.width,
savedConnectionsById,
@@ -522,7 +525,7 @@ function ThreadNavigationSidebarPane(
[filterIcon, filterMenu, props.onOpenSettings],
);
const listEmpty = (
<Text className="px-2 py-4 text-sm" style={{ color: mutedColor }}>
<Text className="px-2 py-4 text-sm text-foreground-muted">
{catalogState.isLoadingConnections
? "Loading threads…"
: props.searchQuery.trim().length > 0
@@ -556,7 +559,7 @@ function ThreadNavigationSidebarPane(
unstable_headerRightItems: () => nativeHeaderItems,
}}
/>
<View style={styles.container}>
<View className="flex-1">
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<GestureDetector gesture={sidebarScrollGesture}>
<LegendList
@@ -586,7 +589,7 @@ function ThreadNavigationSidebarPane(
style={styles.threadList}
ListHeaderComponent={
showsConnectionStatus ? (
<View style={styles.connectionStatusNative}>
<View className="px-1.5 pt-0.5 pb-2">
<WorkspaceConnectionStatus
onPress={props.onOpenEnvironmentSettings}
state={catalogState}
@@ -607,17 +610,15 @@ function ThreadNavigationSidebarPane(
return (
<View
testID="thread-navigation-sidebar"
style={[
styles.container,
{
width: props.width,
backgroundColor,
borderRightColor: borderColor,
borderRightWidth: StyleSheet.hairlineWidth,
},
]}
className="flex-1"
style={{
width: props.width,
backgroundColor,
borderRightColor: borderColor,
borderRightWidth: StyleSheet.hairlineWidth,
}}
>
<View style={{ flex: 1, paddingBottom: insets.bottom }}>
<View className="flex-1" style={{ paddingBottom: insets.bottom }}>
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<GestureDetector gesture={sidebarScrollGesture}>
<LegendList
@@ -650,25 +651,17 @@ function ThreadNavigationSidebarPane(
</View>
<View
className="absolute inset-x-0 top-0 z-[4]"
onLayout={handleStickyHeaderLayout}
pointerEvents="box-none"
style={[
styles.stickyHeader,
{
paddingTop: insets.top,
},
]}
style={{ paddingTop: insets.top }}
>
<View
className="absolute inset-x-0 top-0"
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={[
styles.stickyHeaderWash,
{
height: stickyHeaderHeight + SIDEBAR_STICKY_HEADER_FADE_HEIGHT,
},
]}
style={{ height: stickyHeaderHeight + SIDEBAR_STICKY_HEADER_FADE_HEIGHT }}
>
<Svg width="100%" height="100%">
<Defs>
@@ -694,12 +687,8 @@ function ThreadNavigationSidebarPane(
<Rect width="100%" height="100%" fill="url(#sidebar-header-wash)" />
</Svg>
</View>
<View style={styles.header}>
<Text
className="flex-1 text-[34px] font-t3-bold"
numberOfLines={1}
style={{ color: foregroundColor }}
>
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
Threads
</Text>
<SidebarHeaderButtonGroup colorScheme={colorScheme}>
@@ -714,14 +703,7 @@ function ThreadNavigationSidebarPane(
</SidebarHeaderButtonGroup>
</View>
<View
style={[
styles.searchField,
{
backgroundColor: searchBackgroundColor,
},
]}
>
<View className="mx-4 mt-[9px] h-[38px] flex-row items-center gap-1.5 rounded-xl bg-sidebar-search pr-2.5 pl-[11px]">
<SymbolView name="magnifyingglass" size={15} tintColor={mutedColor} type="monochrome" />
<TextInput
ref={searchInputRef}
@@ -733,14 +715,13 @@ function ThreadNavigationSidebarPane(
placeholder="Search"
placeholderTextColor={placeholderColor}
returnKeyType="search"
className="text-base"
style={[styles.searchInput, { color: foregroundColor }]}
className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
value={props.searchQuery}
/>
</View>
{showsConnectionStatus ? (
<View style={styles.connectionStatus}>
<View className="px-3.5 pt-2.5">
<WorkspaceConnectionStatus
onPress={props.onOpenEnvironmentSettings}
state={catalogState}
@@ -754,63 +735,12 @@ function ThreadNavigationSidebarPane(
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
stickyHeader: {
left: 0,
position: "absolute",
right: 0,
top: 0,
zIndex: 4,
},
stickyHeaderWash: {
left: 0,
position: "absolute",
right: 0,
top: 0,
},
header: {
height: 50,
paddingLeft: 20,
paddingRight: 8,
flexDirection: "row",
alignItems: "flex-end",
gap: 2,
},
headerButtonGroup: {
alignItems: "center",
borderRadius: 22,
flexDirection: "row",
overflow: "hidden",
},
connectionStatus: {
paddingTop: 10,
paddingHorizontal: 14,
},
connectionStatusNative: {
paddingBottom: 8,
paddingHorizontal: 6,
paddingTop: 2,
},
searchField: {
height: 38,
marginTop: 9,
marginHorizontal: 16,
paddingLeft: 11,
paddingRight: 10,
borderRadius: 12,
flexDirection: "row",
alignItems: "center",
gap: 6,
},
searchInput: {
flex: 1,
height: 34,
paddingVertical: 0,
paddingHorizontal: 0,
fontFamily: "DMSans_400Regular",
},
threadList: {
flex: 1,
},
@@ -49,7 +49,6 @@ import {
useThreadGitRightHeaderItems,
} from "./ThreadGitControls";
import { GitOverviewSheet } from "./git/GitOverviewSheet";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
@@ -197,7 +196,6 @@ function ThreadRouteContent(
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const navigation = useNavigation();
const params = props.route.params;
const [drawerVisible, setDrawerVisible] = useState(false);
const environmentIdRaw = firstRouteParam(params.environmentId);
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
const threadId = firstRouteParam(params.threadId);
@@ -326,18 +324,6 @@ function ThreadRouteContent(
);
const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
const handleOpenDrawer = useCallback(() => {
if (!layout.usesSplitView) {
setDrawerVisible(true);
}
}, [layout.usesSplitView]);
useEffect(() => {
if (layout.usesSplitView) {
setDrawerVisible(false);
}
}, [layout.usesSplitView]);
const handleOpenGitInspector = useCallback(() => {
setInspectorSelection({ routeThreadIdentity, mode: "git" });
showAuxiliaryPane("inspector");
@@ -655,6 +641,22 @@ function ThreadRouteContent(
],
[panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
);
// Deep links / cold starts land with Thread as the ONLY route, where the
// native back button does not render. Provide an explicit Home escape for
// that case; when history exists the native back button is used instead.
const canGoBack = navigation.canGoBack();
const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
() => [
withNativeGlassHeaderItem({
accessibilityLabel: "Go to threads list",
icon: { name: "list.bullet", type: "sfSymbol" as const },
identifier: "thread-left-home",
onPress: () => navigation.dispatch(StackActions.replace("Home")),
type: "button" as const,
}),
],
[navigation],
);
if (!environmentId || !threadId) {
return <OpeningThreadLoadingScreen />;
@@ -704,7 +706,6 @@ function ThreadRouteContent(
selectedThreadQueueCount={composer.selectedThreadQueueCount}
layoutVariant={layout.variant}
usesAutomaticContentInsets={usesNativeHeaderGlass}
onOpenDrawer={handleOpenDrawer}
onOpenConnectionEditor={handleOpenConnectionEditor}
onChangeDraftMessage={composer.onChangeDraftMessage}
onPickDraftImages={composer.onPickDraftImages}
@@ -722,23 +723,6 @@ function ThreadRouteContent(
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
onSubmitUserInput={requests.onSubmitUserInput}
/>
{layout.usesSplitView ? null : (
<ThreadNavigationDrawer
visible={drawerVisible}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
navigation.dispatch(
StackActions.replace("Thread", {
environmentId: String(thread.environmentId),
threadId: String(thread.id),
}),
);
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
/>
)}
</View>
</>
);
@@ -757,11 +741,17 @@ function ThreadRouteContent(
: undefined,
title: selectedThread.title,
headerBackVisible: !layout.usesSplitView,
// Compact uses the NATIVE back button (Thread lives flat in the root
// stack now, so a real previous route exists); only split view needs
// custom left items.
// Compact uses the NATIVE back button when a previous route exists;
// deep links / cold starts get an explicit Home button instead.
// Split view always uses its custom left items.
unstable_headerLeftItems:
Platform.OS === "ios" && layout.usesSplitView ? () => splitLeftHeaderItems : undefined,
Platform.OS === "ios"
? layout.usesSplitView
? () => splitLeftHeaderItems
: canGoBack
? undefined
: () => compactHomeHeaderItems
: undefined,
// Search lives in the persistent sidebar, so the split header keeps
// the git controls on the RIGHT (no center items — center space is
// reserved for future breadcrumbs/status).
@@ -3,9 +3,9 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
import { useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { cn } from "../../../lib/cn";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
@@ -27,12 +27,6 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const borderColor = useThemeColor("--color-border");
const inputBorderColor = useThemeColor("--color-input-border");
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const subtleStrongColor = useThemeColor("--color-subtle-strong");
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
? vcsEnvironment.status({
@@ -73,23 +67,14 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
}}
>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-2xs font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
New branch
</Text>
<TextInput
value={newBranchName}
onChangeText={setNewBranchName}
placeholder="feature/mobile-polish"
className="rounded-[18px] px-3.5 py-3 font-sans text-base"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
className="rounded-[18px]"
/>
<SheetActionButton
icon="plus"
@@ -108,35 +93,20 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
</View>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-2xs font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
New worktree
</Text>
<TextInput
value={worktreeBaseBranch}
onChangeText={setWorktreeBaseBranch}
placeholder="main"
className="rounded-[18px] px-3.5 py-3 font-sans text-base"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
className="rounded-[18px]"
/>
<TextInput
value={worktreeBranchName}
onChangeText={setWorktreeBranchName}
placeholder="feature/mobile-thread"
className="rounded-[18px] px-3.5 py-3 font-sans text-base"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
className="rounded-[18px]"
/>
<SheetActionButton
icon="square.split.2x1"
@@ -158,10 +128,7 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
</View>
<View className="gap-2">
<Text
className="text-foreground-secondary text-2xs font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
Existing branches
</Text>
{branchesLoading ? (
@@ -185,12 +152,11 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
return (
<Pressable
key={branch.name}
className="gap-1 rounded-[18px] border px-4 py-3"
className={cn(
"gap-1 rounded-[18px] border px-4 py-3 disabled:opacity-[0.45]",
branch.current ? "border-subtle-strong" : "border-border",
)}
disabled={busy || disabled}
style={{
borderColor: branch.current ? subtleStrongColor : borderColor,
opacity: busy || disabled ? 0.45 : 1,
}}
onPress={() => {
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
navigation.goBack();
@@ -1,10 +1,10 @@
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View, useColorScheme } from "react-native";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { cn } from "../../../lib/cn";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
@@ -21,18 +21,11 @@ type GitCommitSheetProps = StaticScreenProps<{
export function GitCommitSheet(_props: GitCommitSheetProps) {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const { selectedThread } = useThreadSelection();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const borderColor = useThemeColor("--color-border");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const inputBorderColor = useThemeColor("--color-input-border");
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
? vcsEnvironment.status({
@@ -90,10 +83,7 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
</Text>
</View>
{isDefaultRef ? (
<Text
className="text-xs leading-normal"
style={{ color: isDarkMode ? "#fbbf24" : "#b45309" }}
>
<Text className="text-xs leading-normal text-amber-700 dark:text-amber-400">
Warning: this is the default branch.
</Text>
) : null}
@@ -138,12 +128,8 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
<Text className="text-foreground flex-1 text-sm font-medium" numberOfLines={1}>
{file.path}
</Text>
<Text className="text-xs font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-xs font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
<Text className="text-xs font-t3-bold text-emerald-500">+{file.insertions}</Text>
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
</View>
))}
{selectedFiles.length > selectedFilePreview.length ? (
@@ -159,10 +145,10 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
return (
<Pressable
key={file.path}
className="rounded-[18px] border px-4 py-3"
style={{
borderColor: included ? borderColor : borderSubtleColor,
}}
className={cn(
"rounded-[18px] border px-4 py-3",
included ? "border-border" : "border-border-subtle",
)}
onPress={() => {
setExcludedFiles((current) => {
const next = new Set(current);
@@ -193,12 +179,10 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
) : null}
</View>
<View className="items-end gap-1">
<Text className="text-xs font-t3-bold" style={{ color: "#10b981" }}>
<Text className="text-xs font-t3-bold text-emerald-500">
+{file.insertions}
</Text>
<Text className="text-xs font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
</View>
</View>
</Pressable>
@@ -216,14 +200,7 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
onChangeText={setDialogCommitMessage}
placeholder="Leave empty to auto-generate"
textAlignVertical="top"
className="min-h-[128px] rounded-[20px] px-4 py-3.5 font-sans text-base"
style={{
minHeight: 128,
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
className="min-h-[128px] rounded-[20px] px-4 py-3.5"
/>
</View>
@@ -101,13 +101,10 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) {
return (
<View collapsable={false} className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="min-h-4 pt-2" />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
Confirm
</Text>
<Text className="text-center text-3xl font-t3-bold">
@@ -118,10 +115,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) {
</Text>
</View>
<View
className="gap-3 px-5"
style={{ paddingBottom: Math.max(insets.bottom, 18) + 8, paddingTop: 8 }}
>
<View className="gap-3 px-5 pt-2" style={{ paddingBottom: Math.max(insets.bottom, 18) + 8 }}>
<SheetActionButton
icon="arrow.right.circle"
label={copy?.continueLabel ?? "Continue"}
@@ -47,7 +47,6 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
const gitActions = useSelectedThreadGitActions();
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
const foregroundColor = String(useThemeColor("--color-foreground"));
const sheetColor = String(useThemeColor("--color-sheet"));
@@ -205,9 +204,9 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
const content = (
<ScrollView
className="flex-1 bg-screen"
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
style={{ flex: 1, backgroundColor: sheetColor }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: isInspector ? 12 : 20,
@@ -227,9 +226,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
>
{sheetMenuItems.map(({ item, disabledReason }, index) => (
<View key={`${item.id}-${item.label}`}>
{index > 0 ? (
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
) : null}
{index > 0 ? <View className="ml-12 h-px bg-border" /> : null}
<SheetListRow
icon={menuItemIconName(item.icon)}
title={item.label}
@@ -241,7 +238,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
))}
{behindCount > 0 ? (
<>
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<View className="ml-12 h-px bg-border" />
<SheetListRow
icon="arrow.down.circle"
title="Pull latest"
@@ -251,7 +248,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
/>
</>
) : null}
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<View className="ml-12 h-px bg-border" />
<SheetListRow
icon="text.bubble"
title="Review changes"
@@ -259,7 +256,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
disabled={busy || !isRepo}
onPress={() => navigation.navigate("ThreadReview", { environmentId, threadId })}
/>
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<View className="ml-12 h-px bg-border" />
<SheetListRow
icon="point.topleft.down.curvedto.point.bottomright.up"
title="Branches & worktrees"
@@ -365,8 +362,11 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
}
>
<Pressable
className="absolute right-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1, opacity: busy ? 0.45 : 1 }}
className={
busy
? "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle opacity-[0.45]"
: "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle"
}
disabled={busy}
onPress={() => void gitActions.refreshSelectedThreadGitStatus()}
>
@@ -378,10 +378,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
weight="medium"
/>
</Pressable>
<Text
className="text-xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
{isInspector ? "Repository" : "Branch"}
</Text>
<Text className={isInspector ? "pr-10 text-xl font-t3-bold" : "text-3xl font-t3-bold"}>
@@ -3,6 +3,7 @@ import type { ComponentProps } from "react";
import { Pressable, View } from "react-native";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText";
import { cn } from "../../../lib/cn";
/* ─── Shared sheet components ──────────────────────────────────────── */
@@ -13,51 +14,36 @@ export function SheetActionButton(props: {
readonly tone?: "primary" | "secondary" | "danger";
readonly onPress: () => void;
}) {
const primaryBg = useThemeColor("--color-primary");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerBg = useThemeColor("--color-danger");
const dangerBorder = useThemeColor("--color-danger-border");
const dangerFg = useThemeColor("--color-danger-foreground");
const secondaryBg = useThemeColor("--color-secondary");
const secondaryBorder = useThemeColor("--color-secondary-border");
const secondaryFg = useThemeColor("--color-secondary-foreground");
const tone = props.tone ?? "secondary";
const colors =
tone === "primary"
? {
backgroundColor: primaryBg,
borderColor: "transparent",
textColor: primaryFg,
}
: tone === "danger"
? {
backgroundColor: dangerBg,
borderColor: dangerBorder,
textColor: dangerFg,
}
: {
backgroundColor: secondaryBg,
borderColor: secondaryBorder,
textColor: secondaryFg,
};
const textColor = tone === "primary" ? primaryFg : tone === "danger" ? dangerFg : secondaryFg;
return (
<Pressable
className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-[18px] px-4 py-3"
className={cn(
"min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-[18px] px-4 py-3 disabled:opacity-[0.45]",
tone === "primary"
? "bg-primary"
: tone === "danger"
? "border border-danger-border bg-danger"
: "border border-secondary-border bg-secondary",
)}
disabled={props.disabled}
style={{
backgroundColor: colors.backgroundColor,
borderWidth: tone === "primary" ? 0 : 1,
borderColor: colors.borderColor,
opacity: props.disabled ? 0.45 : 1,
}}
onPress={props.onPress}
>
<SymbolView name={props.icon} size={16} tintColor={colors.textColor} type="monochrome" />
<SymbolView name={props.icon} size={16} tintColor={textColor} type="monochrome" />
<Text
className="text-xs font-t3-bold uppercase"
style={{ color: colors.textColor, letterSpacing: 0.9 }}
className={cn(
"text-xs font-t3-bold tracking-[0.9px] uppercase",
tone === "primary"
? "text-primary-foreground"
: tone === "danger"
? "text-danger-foreground"
: "text-secondary-foreground",
)}
>
{props.label}
</Text>
@@ -68,10 +54,7 @@ export function SheetActionButton(props: {
export function MetaCard(props: { readonly label: string; readonly value: string }) {
return (
<View className="rounded-[18px] border border-border bg-card px-4 py-3">
<Text
className="text-foreground-muted text-2xs font-t3-bold uppercase"
style={{ letterSpacing: 0.9 }}
>
<Text className="text-foreground-muted text-2xs font-t3-bold tracking-[0.9px] uppercase">
{props.label}
</Text>
<Text selectable className="text-foreground text-sm font-medium" numberOfLines={1}>
@@ -93,9 +76,8 @@ export function SheetListRow(props: {
return (
<Pressable
className="flex-row items-center gap-3 px-1 py-3"
className="flex-row items-center gap-3 px-1 py-3 disabled:opacity-[0.45]"
disabled={props.disabled}
style={{ opacity: props.disabled ? 0.45 : 1 }}
onPress={props.onPress}
>
<View className="bg-subtle h-9 w-9 items-center justify-center rounded-full">
@@ -231,40 +231,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}
}, []);
const environments = useMemo(
() =>
pipe(
[
...new Set(
pipe(
projects,
Arr.map((project) => project.environmentId),
),
),
],
Arr.map((environmentId) => {
const environment = savedConnectionsById[environmentId];
if (!environment) {
return null;
}
return {
environmentId,
environmentLabel: environment.environmentLabel,
};
}),
Arr.filter(
(
entry,
): entry is {
readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
} => entry !== null,
),
),
[projects, savedConnectionsById],
);
const projectsForEnvironment = useMemo(
() =>
pipe(
@@ -310,6 +276,62 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id)
? editingPendingProject
: (projectsForEnvironment[0] ?? null));
// Only offer machines that actually host the currently selected repository, so
// switching computers moves the same repo across machines instead of jumping to
// whatever unrelated project happens to be first on the other machine. Repository
// identity is the primary signal; projects that haven't reported one yet (still
// indexing) fall back to workspace basename / title so a valid host isn't hidden.
const selectedRepositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null;
// `|| null` (not `??`): a pending-task placeholder project can have an empty
// workspaceRoot, and an "" basename would reject every real host below.
const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
const selectedProjectTitle = selectedProject?.title ?? null;
const environments = useMemo(() => {
const seen = new Set<EnvironmentId>();
const result: Array<{
readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
}> = [];
const hostsSelectedRepository = (project: EnvironmentProject) => {
if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) {
return true;
}
const projectKey = project.repositoryIdentity?.canonicalKey ?? null;
if (selectedRepositoryKey !== null && projectKey !== null) {
return projectKey === selectedRepositoryKey;
}
return (
project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename ||
(selectedProjectTitle !== null && project.title === selectedProjectTitle)
);
};
for (const project of projects) {
if (!hostsSelectedRepository(project)) {
continue;
}
if (seen.has(project.environmentId)) {
continue;
}
const environment = savedConnectionsById[project.environmentId];
if (!environment) {
continue;
}
seen.add(project.environmentId);
result.push({
environmentId: project.environmentId,
environmentLabel: environment.environmentLabel,
});
}
return result;
}, [
projects,
savedConnectionsById,
selectedRepositoryKey,
selectedWorkspaceBasename,
selectedProjectTitle,
]);
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
);
@@ -480,10 +502,36 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSelectedProjectKey(nextProjectKey);
}, []);
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(null);
}, []);
const selectEnvironment = useCallback(
(environmentId: EnvironmentId) => {
const projectsOnTarget = projects.filter(
(project) => project.environmentId === environmentId,
);
const repositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null;
// Prefer the repository identity; projects without one (e.g. not yet
// indexed) fall back to workspace basename, then title, so switching
// computers still follows the same repo instead of resetting to
// whatever project is first on the target machine.
const workspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
const match =
(repositoryKey !== null
? projectsOnTarget.find(
(project) => (project.repositoryIdentity?.canonicalKey ?? null) === repositoryKey,
)
: undefined) ??
(workspaceBasename !== null
? projectsOnTarget.find(
(project) => project.workspaceRoot.split("/").at(-1) === workspaceBasename,
)
: undefined) ??
(selectedProject !== null
? projectsOnTarget.find((project) => project.title === selectedProject.title)
: undefined);
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
},
[projects, selectedProject],
);
const setWorkspaceMode = useCallback(
(mode: WorkspaceMode) => {
@@ -22,16 +22,17 @@ export function SidebarFilterButton(props: {
return (
<Pressable
className="h-11 w-[50px] cursor-pointer items-center justify-center rounded-[22px]"
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
hitSlop={4}
style={({ pressed }) => [
styles.button,
props.grouped
? { backgroundColor: pressed ? pressedBackgroundColor : "transparent", borderWidth: 0 }
: {
backgroundColor: pressed ? pressedBackgroundColor : idleBackgroundColor,
borderColor,
borderWidth: StyleSheet.hairlineWidth,
},
]}
>
@@ -39,17 +40,3 @@ export function SidebarFilterButton(props: {
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
// Match the native glass UIBarButtonItem group metrics (~50pt slots,
// 44pt bar height, label-colored ~20pt glyphs).
width: 50,
height: 44,
borderRadius: 22,
borderWidth: StyleSheet.hairlineWidth,
alignItems: "center",
justifyContent: "center",
cursor: "pointer",
},
});
@@ -24,17 +24,18 @@ function FallbackHeaderButton(props: {
return (
<Pressable
className="h-11 w-[50px] items-center justify-center rounded-[22px]"
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
hitSlop={4}
onPress={props.onPress}
style={({ pressed }) => [
styles.button,
props.grouped
? { backgroundColor: pressed ? pressedBackgroundColor : "transparent", borderWidth: 0 }
: {
backgroundColor: pressed ? pressedBackgroundColor : idleBackgroundColor,
borderColor,
borderWidth: StyleSheet.hairlineWidth,
},
]}
>
@@ -45,7 +46,7 @@ function FallbackHeaderButton(props: {
export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
return (
<View style={styles.actions}>
<View className="flex-row items-center gap-0.5">
<FallbackHeaderButton
accessibilityLabel="Open settings"
grouped={props.grouped}
@@ -55,20 +56,3 @@ export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
</View>
);
}
const styles = StyleSheet.create({
actions: {
flexDirection: "row",
alignItems: "center",
gap: 2,
},
button: {
// Match the native glass UIBarButtonItem group metrics.
width: 50,
height: 44,
borderRadius: 22,
borderWidth: StyleSheet.hairlineWidth,
alignItems: "center",
justifyContent: "center",
},
});
@@ -75,7 +75,7 @@ export function ThreadInspectorContentStack(props: {
const Route = props.Route;
return (
<View style={{ flex: 1 }}>
<View className="flex-1">
<InspectorContentPane
mounted={mountedModes.has("files") || props.mode === "files"}
visible={props.mode === "files"}
@@ -6,16 +6,18 @@ import type {
import type { MenuAction } from "@react-native-menu/menu";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useMemo, type ComponentProps } from "react";
import { Pressable, useWindowDimensions, View } from "react-native";
import { Pressable, useColorScheme, useWindowDimensions, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import Svg, { Circle, Path } from "react-native-svg";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { cn } from "../../lib/cn";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadStatus } from "./threadPresentation";
@@ -32,6 +34,41 @@ export type ThreadListVariant = "compact" | "sidebar";
export const THREAD_LIST_COMPACT_INSET = 20;
const SIDEBAR_ROW_RADIUS = 12;
function pullRequestTintColor(
state: ThreadPr["state"],
colorScheme: ReturnType<typeof useColorScheme>,
) {
const dark = colorScheme === "dark";
switch (state) {
case "open":
return dark ? "#34d399" : "#059669";
case "merged":
return dark ? "#a78bfa" : "#7c3aed";
case "closed":
return dark ? "#a1a1aa" : "#71717a";
}
}
function PullRequestIcon(props: { readonly size: number; readonly color: string }) {
return (
<Svg
width={props.size}
height={props.size}
viewBox="0 0 24 24"
fill="none"
stroke={props.color}
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
>
<Circle cx={18} cy={18} r={3} />
<Circle cx={6} cy={6} r={3} />
<Path d="M13 6h3a2 2 0 0 1 2 2v7" />
<Path d="M6 9v12" />
</Svg>
);
}
/* ─── Project group header ───────────────────────────────────────────── */
export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props: {
@@ -43,31 +80,54 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
readonly isFirst: boolean;
readonly groupKey: string;
readonly onGroupAction: (key: string, action: HomeGroupDisplayAction) => void;
/** Project a quick new thread should target; null hides the button. */
readonly newThreadTarget?: EnvironmentProject | null;
readonly onNewThread?: (project: EnvironmentProject) => void;
}) {
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const { groupKey, onGroupAction } = props;
const iconMutedColor = useThemeColor("--color-icon-muted");
const { groupKey, onGroupAction, onNewThread } = props;
const newThreadTarget = props.newThreadTarget ?? null;
const compact = props.variant === "compact";
const handleToggle = useCallback(
() => onGroupAction(groupKey, "toggle-collapsed"),
[groupKey, onGroupAction],
);
const handleNewThread = useCallback(() => {
if (newThreadTarget) {
onNewThread?.(newThreadTarget);
}
}, [newThreadTarget, onNewThread]);
const showNewThreadButton = onNewThread !== undefined && newThreadTarget !== null;
// The new-thread button is a SIBLING of the collapse toggle, not a child:
// nested touchables are unreachable to VoiceOver/TalkBack (the parent
// swallows focus). Row padding lives on the container (explicit styles —
// dynamic padding classes on Pressable did not apply reliably) so both
// children share one centerline; hitSlop restores the padded tap area.
const verticalHitSlop = { top: props.isFirst ? 8 : 24, bottom: 12 };
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: !props.collapsed }}
accessibilityLabel={`${props.title}, ${props.threadCount} threads`}
accessibilityHint={props.collapsed ? "Expands the project" : "Collapses the project"}
className={compact ? "bg-screen" : undefined}
onPress={handleToggle}
<View
className={compact ? "flex-row items-center bg-screen" : "flex-row items-center"}
style={{
minHeight: compact ? 44 : 36,
paddingLeft: compact ? 20 : 12,
// Compact right padding centers the 20pt plus glyph on the thread
// rows' trailing chevron column (18 + 13/2 ≈ 24.5 from the edge).
paddingRight: compact ? 14 : 12,
paddingBottom: compact ? 12 : 8,
paddingTop: props.isFirst ? (compact ? 8 : 4) : compact ? 24 : 20,
}}
>
<View
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: !props.collapsed }}
accessibilityLabel={`${props.title}, ${props.threadCount} threads`}
accessibilityHint={props.collapsed ? "Expands the project" : "Collapses the project"}
className={
compact
? `flex-row items-center gap-2.5 px-5 pb-3 ${props.isFirst ? "pt-2" : "pt-6"}`
: `flex-row items-center gap-2 px-3 pb-2 ${props.isFirst ? "pt-1" : "pt-5"}`
compact ? "flex-1 flex-row items-center gap-2.5" : "flex-1 flex-row items-center gap-2"
}
style={{ minHeight: compact ? 44 : 36 }}
hitSlop={{ ...verticalHitSlop, left: compact ? 20 : 12 }}
onPress={handleToggle}
>
<ProjectFavicon
environmentId={props.project.environmentId}
@@ -78,10 +138,9 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
<Text
className={
compact
? "flex-shrink text-base font-t3-bold text-foreground-muted"
: "flex-shrink text-sm font-t3-bold text-foreground-muted"
? "flex-shrink text-base font-t3-bold tracking-[0.2px] text-foreground-muted"
: "flex-shrink text-sm font-t3-bold tracking-[0.2px] text-foreground-muted"
}
style={{ letterSpacing: 0.2 }}
numberOfLines={1}
>
{props.title}
@@ -95,15 +154,25 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
>
{props.threadCount}
</Text>
<SymbolView
name={props.collapsed ? "chevron.right" : "chevron.down"}
size={compact ? 13 : 11}
tintColor={iconSubtleColor}
type="monochrome"
weight="semibold"
/>
</View>
</Pressable>
</Pressable>
{showNewThreadButton ? (
<Pressable
accessibilityLabel={`Create new thread in ${props.title}`}
accessibilityRole="button"
hitSlop={{ ...verticalHitSlop, left: 10, right: 14 }}
onPress={handleNewThread}
style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1, paddingLeft: 12 })}
>
<SymbolView
name="plus"
size={compact ? 20 : 16}
tintColor={iconMutedColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
</View>
);
});
@@ -203,7 +272,6 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
const compact = props.variant === "compact";
const separatorColor = useThemeColor("--color-separator");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const foregroundColor = useThemeColor("--color-foreground");
const mutedColor = useThemeColor("--color-foreground-muted");
const pressedBackgroundColor = useThemeColor("--color-subtle");
@@ -221,17 +289,14 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
);
const statusPill = (
<View
className="bg-zinc-500/12 dark:bg-zinc-500/16"
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<View className="rounded-full bg-zinc-500/12 px-1.5 py-0.5 dark:bg-zinc-500/16">
<Text className="text-3xs font-t3-bold text-zinc-600 dark:text-zinc-300">Pending</Text>
</View>
);
const subtitleRow =
subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<View className="mt-px flex-row items-center gap-1.5">
<SymbolView
name="tray.and.arrow.up"
size={10}
@@ -239,9 +304,12 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
type="monochrome"
/>
<Text
className={compact ? "text-sm text-foreground-muted" : "text-xs"}
className={
compact
? "shrink text-sm text-foreground-muted"
: "shrink text-xs text-foreground-muted"
}
numberOfLines={1}
style={compact ? { flexShrink: 1 } : { flexShrink: 1, color: mutedColor }}
>
{subtitleParts.join(" · ")}
</Text>
@@ -278,12 +346,7 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text
className="text-base text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
<Text className="text-base tabular-nums text-foreground-tertiary">{timestamp}</Text>
<SymbolView
name="chevron.right"
size={13}
@@ -312,22 +375,14 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
paddingVertical: 10,
})}
>
<View style={{ gap: 3 }}>
<View className="gap-[3px]">
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-base font-t3-medium"
numberOfLines={1}
style={{ color: foregroundColor }}
>
<Text className="flex-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
{pendingTask.title}
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text
className="text-xs"
numberOfLines={1}
style={{ color: mutedColor, fontVariant: ["tabular-nums"] }}
>
<Text className="text-xs tabular-nums text-foreground-muted" numberOfLines={1}>
{timestamp}
</Text>
</View>
@@ -375,6 +430,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
>["simultaneousWithExternalGesture"];
}) {
const { width: windowWidth } = useWindowDimensions();
const colorScheme = useColorScheme();
const compact = props.variant === "compact";
const selected = props.selected === true;
// Recycling-safe: resets when the list container is reused for another
@@ -385,12 +441,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const screenColor = useThemeColor("--color-screen");
const drawerColor = useThemeColor("--color-drawer");
const foregroundColor = useThemeColor("--color-foreground");
const mutedColor = useThemeColor("--color-foreground-muted");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const selectedForegroundColor = useThemeColor("--color-user-bubble-foreground");
const selectedMutedColor = useThemeColor("--color-user-bubble-foreground-muted");
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const status = resolveThreadStatus(thread);
@@ -398,13 +450,12 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const timestamp = relativeTime(
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
);
const threadAccessibilityLabel = pr ? `${thread.title}, ${pr.accessibilityLabel}` : thread.title;
const subtitleParts = [props.environmentLabel, thread.branch].filter((part): part is string =>
Boolean(part),
);
const backgroundColor = compact ? screenColor : drawerColor;
const effectiveForeground = selected ? selectedForegroundColor : foregroundColor;
const effectiveMuted = selected ? selectedMutedColor : mutedColor;
const effectivePressedBackground = selected ? "rgba(255,255,255,0.16)" : pressedBackgroundColor;
const effectiveStatus =
selected && status
@@ -431,10 +482,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
);
const statusPill = effectiveStatus ? (
<View
className={effectiveStatus.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<View className={`${effectiveStatus.pillClassName} rounded-full px-1.5 py-0.5`}>
<Text className={`text-3xs font-t3-bold ${effectiveStatus.textClassName}`}>
{effectiveStatus.label}
</Text>
@@ -443,32 +491,36 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const subtitleRow =
subtitleParts.length > 0 || pr !== null ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<View className="mt-px flex-row items-center gap-1.5">
{subtitleParts.length > 0 ? (
<>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={compact ? iconSubtleColor : effectiveMuted}
type="monochrome"
/>
<Text
className={compact ? "text-sm text-foreground-muted" : "text-xs"}
className={cn(
"shrink",
compact ? "text-sm text-foreground-muted" : "text-xs",
!compact &&
(selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted"),
)}
numberOfLines={1}
style={compact ? { flexShrink: 1 } : { flexShrink: 1, color: effectiveMuted }}
>
{subtitleParts.join(" · ")}
</Text>
</>
) : null}
{pr !== null ? (
<Text
className={`${compact ? "text-sm" : "text-xs"} font-t3-medium ${
selected ? "text-white" : pr.textClassName
}`}
>
{pr.label}
</Text>
<View className="flex-row items-center gap-0.5">
<PullRequestIcon
size={compact ? 13 : 11}
color={selected ? "#ffffff" : pullRequestTintColor(pr.state, colorScheme)}
/>
<Text
className={`${compact ? "text-sm" : "text-xs"} font-t3-medium ${
selected ? "text-white" : pr.textClassName
}`}
>
{pr.label}
</Text>
</View>
) : null}
</View>
) : null;
@@ -477,7 +529,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
compact ? (
<Pressable
accessibilityHint="Swipe left for archive and delete actions"
accessibilityLabel={thread.title}
accessibilityLabel={threadAccessibilityLabel}
accessibilityRole="button"
className="bg-screen"
onPress={() => {
@@ -507,12 +559,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text
className="text-base text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
<Text className="text-base tabular-nums text-foreground-tertiary">{timestamp}</Text>
<SymbolView
name="chevron.right"
size={13}
@@ -528,7 +575,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
) : (
<Pressable
accessibilityHint="Opens the thread"
accessibilityLabel={thread.title}
accessibilityLabel={threadAccessibilityLabel}
accessibilityRole="button"
accessibilityState={{ selected }}
onHoverIn={() => setHovered(true)}
@@ -551,21 +598,25 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
paddingVertical: 10,
})}
>
<View style={{ gap: 3 }}>
<View className="gap-[3px]">
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-base font-t3-medium"
className={cn(
"flex-1 text-base font-t3-medium",
selected ? "text-user-bubble-foreground" : "text-foreground",
)}
numberOfLines={1}
style={{ color: effectiveForeground }}
>
{thread.title}
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text
className="text-xs"
className={cn(
"text-xs tabular-nums",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
numberOfLines={1}
style={{ color: effectiveMuted, fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff. Show more