diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index dded6b0acd..43aa362c43 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -11,6 +11,7 @@
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
+ "apps/mobile/uniwind-types.d.ts"
"*.icon/**"
],
"sortPackageJson": {}
diff --git a/.oxlintrc.json b/.oxlintrc.json
index 8ea8fbf2b8..e99dbb4c4d 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -6,7 +6,8 @@
"node_modules",
"bun.lock",
"*.tsbuildinfo",
- "**/routeTree.gen.ts"
+ "**/routeTree.gen.ts",
+ "apps/mobile/uniwind-types.d.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
@@ -15,6 +16,7 @@
"perf": "warn"
},
"rules": {
+ "unicorn/no-array-sort": "off",
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
diff --git a/apps/mobile/.gitignore b/apps/mobile/.gitignore
new file mode 100644
index 0000000000..d914c328fe
--- /dev/null
+++ b/apps/mobile/.gitignore
@@ -0,0 +1,41 @@
+# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
+
+# dependencies
+node_modules/
+
+# Expo
+.expo/
+dist/
+web-build/
+expo-env.d.ts
+
+# Native
+.kotlin/
+*.orig.*
+*.jks
+*.p8
+*.p12
+*.key
+*.mobileprovision
+
+# Metro
+.metro-health-check*
+
+# debug
+npm-debug.*
+yarn-debug.*
+yarn-error.*
+
+# macOS
+.DS_Store
+*.pem
+
+# local env files
+.env*.local
+
+# typescript
+*.tsbuildinfo
+
+# generated native folders
+/ios
+/android
diff --git a/apps/mobile/README.md b/apps/mobile/README.md
new file mode 100644
index 0000000000..c1bf5b4064
--- /dev/null
+++ b/apps/mobile/README.md
@@ -0,0 +1,65 @@
+# T3 Code Mobile
+
+> [!WARNING]
+> T3 Code Mobile is currently in development and is not distributed yet. If you want to try it out, you can build it from source.
+
+## Quickstart
+
+> [!NOTE]
+> Uses native modules so using Expo Go is not supported. You need to use the Expo Dev Client.
+
+This app has three variants:
+
+- `development`: Expo dev client, installable side-by-side as `T3 Code Dev`
+- `preview`: persistent internal preview build, installable side-by-side as `T3 Code Preview`
+- `production`: store/release build as `T3 Code`
+
+Run commands from `apps/mobile`.
+
+## Development
+
+Start Metro for the dev client:
+
+```bash
+bun run dev:client
+```
+
+Build and run the local iOS dev client:
+
+```bash
+bun run ios:dev
+```
+
+Build and run the local iOS preview app:
+
+```bash
+bun run ios:preview
+```
+
+Inspect the resolved Expo config for a variant:
+
+```bash
+bun run config:dev
+bun run config:preview
+```
+
+## EAS Builds
+
+Create a cloud dev-client build:
+
+```bash
+bun run eas:ios:dev
+```
+
+Create a persistent preview build:
+
+```bash
+bun run eas:ios:preview
+```
+
+Android equivalents:
+
+```bash
+bun run eas:android:dev
+bun run eas:android:preview
+```
diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts
new file mode 100644
index 0000000000..00a667391e
--- /dev/null
+++ b/apps/mobile/app.config.ts
@@ -0,0 +1,130 @@
+import type { ExpoConfig } from "expo/config";
+
+type AppVariant = "development" | "preview" | "production";
+
+const APP_VARIANT = resolveAppVariant(process.env.APP_VARIANT);
+
+const VARIANT_CONFIG: Record<
+ AppVariant,
+ {
+ readonly appName: string;
+ readonly iosIcon: string;
+ readonly iosBundleIdentifier: string;
+ readonly androidPackage: string;
+ }
+> = {
+ development: {
+ appName: "T3 Code Dev",
+ iosIcon: "./assets/icon-composer-dev.icon",
+ iosBundleIdentifier: "com.t3tools.t3code.dev",
+ androidPackage: "com.t3tools.t3code.dev",
+ },
+ preview: {
+ appName: "T3 Code Preview",
+ iosIcon: "./assets/icon-composer-prod.icon",
+ iosBundleIdentifier: "com.t3tools.t3code.preview",
+ androidPackage: "com.t3tools.t3code.preview",
+ },
+ production: {
+ appName: "T3 Code",
+ iosIcon: "./assets/icon-composer-prod.icon",
+ iosBundleIdentifier: "com.t3tools.t3code",
+ androidPackage: "com.t3tools.t3code",
+ },
+};
+
+function resolveAppVariant(value: string | undefined): AppVariant {
+ switch (value) {
+ case "development":
+ case "preview":
+ case "production":
+ return value;
+ default:
+ return "production";
+ }
+}
+
+const variant = VARIANT_CONFIG[APP_VARIANT];
+
+const config: ExpoConfig = {
+ name: variant.appName,
+ slug: "t3-code",
+ scheme: "t3code",
+ version: "0.1.0",
+ runtimeVersion: {
+ policy: "appVersion",
+ },
+ orientation: "portrait",
+ icon: "./assets/icon.png",
+ userInterfaceStyle: "automatic",
+ updates: {
+ enabled: true,
+ url: "https://u.expo.dev/d763fcb8-d37c-41ea-a773-b54a0ab4a454",
+ checkAutomatically: "ON_LOAD",
+ fallbackToCacheTimeout: 0,
+ },
+ splash: {
+ image: "./assets/splash-icon.png",
+ resizeMode: "contain",
+ backgroundColor: "#ffffff",
+ },
+ ios: {
+ icon: variant.iosIcon,
+ supportsTablet: true,
+ bundleIdentifier: variant.iosBundleIdentifier,
+ infoPlist: {
+ NSAppTransportSecurity: {
+ NSAllowsArbitraryLoads: true,
+ },
+ ITSAppUsesNonExemptEncryption: false,
+ },
+ },
+ android: {
+ icon: "./assets/icon.png",
+ package: variant.androidPackage,
+ adaptiveIcon: {
+ backgroundColor: "#E6F4FE",
+ foregroundImage: "./assets/android-icon-foreground.png",
+ backgroundImage: "./assets/android-icon-background.png",
+ monochromeImage: "./assets/android-icon-monochrome.png",
+ },
+ predictiveBackGestureEnabled: false,
+ },
+ web: {
+ favicon: "./assets/favicon.png",
+ },
+ plugins: [
+ [
+ "expo-camera",
+ {
+ cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
+ barcodeScannerEnabled: true,
+ },
+ ],
+ [
+ "expo-splash-screen",
+ {
+ image: "./assets/splash-icon.png",
+ resizeMode: "contain",
+ backgroundColor: "#ffffff",
+ imageWidth: 220,
+ dark: {
+ image: "./assets/splash-icon.png",
+ backgroundColor: "#0a0a0a",
+ },
+ },
+ ],
+ "expo-secure-store",
+ "expo-router",
+ "./plugins/withAndroidCleartextTraffic.cjs",
+ ],
+ extra: {
+ appVariant: APP_VARIANT,
+ eas: {
+ projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
+ },
+ },
+ owner: "pingdotgg",
+};
+
+export default config;
diff --git a/apps/mobile/assets/android-icon-background.png b/apps/mobile/assets/android-icon-background.png
new file mode 100644
index 0000000000..b33d7978d7
Binary files /dev/null and b/apps/mobile/assets/android-icon-background.png differ
diff --git a/apps/mobile/assets/android-icon-foreground.png b/apps/mobile/assets/android-icon-foreground.png
new file mode 100644
index 0000000000..b33d7978d7
Binary files /dev/null and b/apps/mobile/assets/android-icon-foreground.png differ
diff --git a/apps/mobile/assets/android-icon-monochrome.png b/apps/mobile/assets/android-icon-monochrome.png
new file mode 100644
index 0000000000..b33d7978d7
Binary files /dev/null and b/apps/mobile/assets/android-icon-monochrome.png differ
diff --git a/apps/mobile/assets/favicon.png b/apps/mobile/assets/favicon.png
new file mode 100644
index 0000000000..e0e1b9659b
Binary files /dev/null and b/apps/mobile/assets/favicon.png differ
diff --git a/apps/mobile/assets/icon-composer-dev.icon/Assets/T3.svg b/apps/mobile/assets/icon-composer-dev.icon/Assets/T3.svg
new file mode 100644
index 0000000000..b12706fdfc
--- /dev/null
+++ b/apps/mobile/assets/icon-composer-dev.icon/Assets/T3.svg
@@ -0,0 +1,3 @@
+
diff --git a/apps/mobile/assets/icon-composer-dev.icon/Assets/Texturelabs_Paper_381XL.jpg b/apps/mobile/assets/icon-composer-dev.icon/Assets/Texturelabs_Paper_381XL.jpg
new file mode 100644
index 0000000000..d98c41a4e3
Binary files /dev/null and b/apps/mobile/assets/icon-composer-dev.icon/Assets/Texturelabs_Paper_381XL.jpg differ
diff --git a/apps/mobile/assets/icon-composer-dev.icon/Assets/gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png b/apps/mobile/assets/icon-composer-dev.icon/Assets/gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png
new file mode 100644
index 0000000000..de5a82d8c4
Binary files /dev/null and b/apps/mobile/assets/icon-composer-dev.icon/Assets/gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png differ
diff --git a/apps/mobile/assets/icon-composer-dev.icon/icon.json b/apps/mobile/assets/icon-composer-dev.icon/icon.json
new file mode 100644
index 0000000000..fd3fb6819a
--- /dev/null
+++ b/apps/mobile/assets/icon-composer-dev.icon/icon.json
@@ -0,0 +1,45 @@
+{
+ "fill": {
+ "solid": "display-p3:0.00000,0.00000,0.00000,1.00000"
+ },
+ "groups": [
+ {
+ "layers": [
+ {
+ "hidden": false,
+ "image-name": "gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png",
+ "name": "gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr",
+ "position": {
+ "scale": 1.1,
+ "translation-in-points": [0, 0]
+ }
+ },
+ {
+ "image-name": "T3.svg",
+ "name": "T3",
+ "position": {
+ "scale": 10,
+ "translation-in-points": [0, 0]
+ }
+ },
+ {
+ "hidden": true,
+ "image-name": "Texturelabs_Paper_381XL.jpg",
+ "name": "Texturelabs_Paper_381XL"
+ }
+ ],
+ "shadow": {
+ "kind": "neutral",
+ "opacity": 0.5
+ },
+ "translucency": {
+ "enabled": true,
+ "value": 0.5
+ }
+ }
+ ],
+ "supported-platforms": {
+ "circles": ["watchOS"],
+ "squares": "shared"
+ }
+}
diff --git a/apps/mobile/assets/icon-composer-prod.icon/Assets/T3.svg b/apps/mobile/assets/icon-composer-prod.icon/Assets/T3.svg
new file mode 100644
index 0000000000..b12706fdfc
--- /dev/null
+++ b/apps/mobile/assets/icon-composer-prod.icon/Assets/T3.svg
@@ -0,0 +1,3 @@
+
diff --git a/apps/mobile/assets/icon-composer-prod.icon/icon.json b/apps/mobile/assets/icon-composer-prod.icon/icon.json
new file mode 100644
index 0000000000..8f7579311f
--- /dev/null
+++ b/apps/mobile/assets/icon-composer-prod.icon/icon.json
@@ -0,0 +1,31 @@
+{
+ "fill": {
+ "solid": "display-p3:0.00000,0.00000,0.00000,1.00000"
+ },
+ "groups": [
+ {
+ "layers": [
+ {
+ "image-name": "T3.svg",
+ "name": "T3",
+ "position": {
+ "scale": 10,
+ "translation-in-points": [0, 0]
+ }
+ }
+ ],
+ "shadow": {
+ "kind": "neutral",
+ "opacity": 0.5
+ },
+ "translucency": {
+ "enabled": true,
+ "value": 0.5
+ }
+ }
+ ],
+ "supported-platforms": {
+ "circles": ["watchOS"],
+ "squares": "shared"
+ }
+}
diff --git a/apps/mobile/assets/icon.png b/apps/mobile/assets/icon.png
new file mode 100644
index 0000000000..b33d6f337b
Binary files /dev/null and b/apps/mobile/assets/icon.png differ
diff --git a/apps/mobile/assets/splash-icon.png b/apps/mobile/assets/splash-icon.png
new file mode 100644
index 0000000000..b33d6f337b
Binary files /dev/null and b/apps/mobile/assets/splash-icon.png differ
diff --git a/apps/mobile/babel.config.js b/apps/mobile/babel.config.js
new file mode 100644
index 0000000000..5c85f81242
--- /dev/null
+++ b/apps/mobile/babel.config.js
@@ -0,0 +1,6 @@
+module.exports = function (api) {
+ api.cache(true);
+ return {
+ presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]],
+ };
+};
diff --git a/apps/mobile/eas.json b/apps/mobile/eas.json
new file mode 100644
index 0000000000..cb0075613b
--- /dev/null
+++ b/apps/mobile/eas.json
@@ -0,0 +1,37 @@
+{
+ "cli": {
+ "version": ">= 18.4.0",
+ "appVersionSource": "remote"
+ },
+ "build": {
+ "development": {
+ "env": {
+ "APP_VARIANT": "development"
+ },
+ "channel": "development",
+ "developmentClient": true,
+ "distribution": "internal"
+ },
+ "preview": {
+ "env": {
+ "APP_VARIANT": "preview"
+ },
+ "channel": "preview",
+ "distribution": "internal"
+ },
+ "production": {
+ "env": {
+ "APP_VARIANT": "production"
+ },
+ "channel": "production",
+ "autoIncrement": true
+ }
+ },
+ "submit": {
+ "production": {
+ "ios": {
+ "ascAppId": "6761315631"
+ }
+ }
+ }
+}
diff --git a/apps/mobile/global.css b/apps/mobile/global.css
new file mode 100644
index 0000000000..387f6b51bd
--- /dev/null
+++ b/apps/mobile/global.css
@@ -0,0 +1,192 @@
+@import "tailwindcss";
+@import "uniwind";
+
+/* ─── Theme tokens ──────────────────────────────────────────────────── */
+@layer theme {
+ :root {
+ @variant light {
+ /* Page backgrounds */
+ --color-screen: #f2f2f7;
+ --color-sheet: rgba(242, 242, 247, 0.98);
+
+ /* Card / surface */
+ --color-card: #ffffff;
+ --color-card-alt: #f5f5f5;
+ --color-card-translucent: rgba(255, 255, 255, 0.94);
+
+ /* Text */
+ --color-foreground: #262626;
+ --color-foreground-secondary: #525252;
+ --color-foreground-muted: #737373;
+ --color-foreground-tertiary: #a3a3a3;
+
+ /* Borders & separators */
+ --color-border: rgba(0, 0, 0, 0.08);
+ --color-border-subtle: rgba(0, 0, 0, 0.06);
+ --color-separator: rgba(0, 0, 0, 0.04);
+
+ /* Subtle backgrounds (badges, pills, overlays) */
+ --color-subtle: rgba(0, 0, 0, 0.04);
+ --color-subtle-strong: rgba(0, 0, 0, 0.08);
+
+ /* Primary action */
+ --color-primary: #262626;
+ --color-primary-foreground: #ffffff;
+ --color-primary-shadow: rgba(0, 0, 0, 0.18);
+
+ /* Secondary action */
+ --color-secondary: #ffffff;
+ --color-secondary-foreground: #262626;
+ --color-secondary-border: rgba(0, 0, 0, 0.08);
+
+ /* Danger */
+ --color-danger: #fef2f2;
+ --color-danger-border: rgba(239, 68, 68, 0.12);
+ --color-danger-foreground: #dc2626;
+
+ /* Inputs */
+ --color-input: #ffffff;
+ --color-input-border: rgba(0, 0, 0, 0.1);
+ --color-placeholder: #a3a3a3;
+
+ /* Icons */
+ --color-icon: #262626;
+ --color-icon-muted: #525252;
+ --color-icon-subtle: #a3a3a3;
+
+ /* Header / glass chrome */
+ --color-header: rgba(255, 255, 255, 0.97);
+ --color-header-border: rgba(0, 0, 0, 0.06);
+
+ /* StatusBar */
+ --color-status-bar: #f2f2f7;
+
+ /* Markdown */
+ --color-md-body: #262626;
+ --color-md-strong: #171717;
+ --color-md-link: #2563eb;
+ --color-md-blockquote-border: rgba(0, 0, 0, 0.08);
+ --color-md-blockquote-bg: rgba(0, 0, 0, 0.02);
+ --color-md-code-bg: rgba(0, 0, 0, 0.04);
+ --color-md-code-text: #262626;
+ --color-md-user-code-bg: rgba(255, 255, 255, 0.55);
+ --color-md-user-code-text: #262626;
+ --color-md-user-fence-bg: rgba(0, 0, 0, 0.04);
+ --color-md-user-fence-text: #1e3a5f;
+ --color-md-hr: rgba(0, 0, 0, 0.08);
+
+ /* Drawer / modal backdrop */
+ --color-backdrop: rgba(0, 0, 0, 0.22);
+ --color-drawer: rgba(255, 255, 255, 0.99);
+ --color-drawer-shadow: rgba(0, 0, 0, 0.12);
+
+ /* Misc */
+ --color-dot-separator: rgba(0, 0, 0, 0.2);
+ --color-wordmark: #262626;
+ --color-chevron: rgba(0, 0, 0, 0.2);
+ }
+
+ @variant dark {
+ /* Page backgrounds */
+ --color-screen: #0a0a0a;
+ --color-sheet: rgba(14, 14, 14, 0.98);
+
+ /* Card / surface */
+ --color-card: #171717;
+ --color-card-alt: #1c1c1c;
+ --color-card-translucent: rgba(17, 17, 17, 0.94);
+
+ /* Text */
+ --color-foreground: #f5f5f5;
+ --color-foreground-secondary: #a3a3a3;
+ --color-foreground-muted: #737373;
+ --color-foreground-tertiary: #525252;
+
+ /* Borders & separators */
+ --color-border: rgba(255, 255, 255, 0.06);
+ --color-border-subtle: rgba(255, 255, 255, 0.04);
+ --color-separator: rgba(255, 255, 255, 0.03);
+
+ /* Subtle backgrounds (badges, pills, overlays) */
+ --color-subtle: rgba(255, 255, 255, 0.04);
+ --color-subtle-strong: rgba(255, 255, 255, 0.08);
+
+ /* Primary action */
+ --color-primary: #f5f5f5;
+ --color-primary-foreground: #0a0a0a;
+ --color-primary-shadow: rgba(0, 0, 0, 0.22);
+
+ /* Secondary action */
+ --color-secondary: rgba(255, 255, 255, 0.04);
+ --color-secondary-foreground: #f5f5f5;
+ --color-secondary-border: rgba(255, 255, 255, 0.06);
+
+ /* Danger */
+ --color-danger: rgba(239, 68, 68, 0.14);
+ --color-danger-border: rgba(248, 113, 113, 0.18);
+ --color-danger-foreground: #fca5a5;
+
+ /* Inputs */
+ --color-input: #141414;
+ --color-input-border: rgba(255, 255, 255, 0.08);
+ --color-placeholder: #737373;
+
+ /* Icons */
+ --color-icon: #f5f5f5;
+ --color-icon-muted: #a3a3a3;
+ --color-icon-subtle: #737373;
+
+ /* Header / glass chrome */
+ --color-header: rgba(10, 10, 10, 0.97);
+ --color-header-border: rgba(255, 255, 255, 0.06);
+
+ /* StatusBar */
+ --color-status-bar: #0a0a0a;
+
+ /* Markdown */
+ --color-md-body: #e5e5e5;
+ --color-md-strong: #f5f5f5;
+ --color-md-link: #60a5fa;
+ --color-md-blockquote-border: rgba(255, 255, 255, 0.1);
+ --color-md-blockquote-bg: rgba(255, 255, 255, 0.03);
+ --color-md-code-bg: rgba(255, 255, 255, 0.06);
+ --color-md-code-text: #e5e5e5;
+ --color-md-user-code-bg: rgba(255, 255, 255, 0.1);
+ --color-md-user-code-text: #e5e5e5;
+ --color-md-user-fence-bg: rgba(255, 255, 255, 0.08);
+ --color-md-user-fence-text: #e5e5e5;
+ --color-md-hr: rgba(255, 255, 255, 0.08);
+
+ /* Drawer / modal backdrop */
+ --color-backdrop: rgba(0, 0, 0, 0.48);
+ --color-drawer: rgba(14, 14, 14, 0.99);
+ --color-drawer-shadow: rgba(0, 0, 0, 0.32);
+
+ /* Misc */
+ --color-dot-separator: rgba(255, 255, 255, 0.2);
+ --color-wordmark: #f5f5f5;
+ --color-chevron: rgba(255, 255, 255, 0.2);
+ }
+ }
+}
+
+/* ─── Font family ───────────────────────────────────────────────────── */
+@theme {
+ --font-sans: "DMSans_400Regular";
+ --font-medium: "DMSans_500Medium";
+ --font-bold: "DMSans_700Bold";
+}
+
+/* ─── Custom utilities ──────────────────────────────────────────────── */
+@utility font-t3-medium {
+ font-family: "DMSans_500Medium";
+}
+
+@utility font-t3-bold {
+ font-family: "DMSans_700Bold";
+}
+
+@utility font-t3-extrabold {
+ font-family: "DMSans_700Bold";
+ font-weight: 800;
+}
diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts
new file mode 100644
index 0000000000..642e1b77be
--- /dev/null
+++ b/apps/mobile/index.ts
@@ -0,0 +1,2 @@
+import "react-native-gesture-handler";
+import "expo-router/entry";
diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js
new file mode 100644
index 0000000000..126250e02e
--- /dev/null
+++ b/apps/mobile/metro.config.js
@@ -0,0 +1,14 @@
+const path = require("node:path");
+const { getDefaultConfig } = require("expo/metro-config");
+const { withUniwindConfig } = require("uniwind/metro");
+
+/** @type {import("expo/metro-config").MetroConfig} */
+const config = getDefaultConfig(__dirname);
+const workspaceRoot = path.resolve(__dirname, "../..");
+
+config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];
+
+module.exports = withUniwindConfig(config, {
+ cssEntryFile: "./global.css",
+ polyfills: { rem: 14 },
+});
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
new file mode 100644
index 0000000000..6d4395f06c
--- /dev/null
+++ b/apps/mobile/package.json
@@ -0,0 +1,88 @@
+{
+ "name": "@t3tools/mobile",
+ "version": "0.0.0",
+ "private": true,
+ "main": "index.ts",
+ "scripts": {
+ "dev": "expo start --clear",
+ "dev:client": "APP_VARIANT=development expo start --dev-client --clear",
+ "start": "expo start",
+ "start:dev": "APP_VARIANT=development expo start",
+ "start:preview": "APP_VARIANT=preview expo start",
+ "start:prod": "APP_VARIANT=production expo start",
+ "android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
+ "android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
+ "android:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
+ "android:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
+ "eas:android:dev": "eas build --profile development -p android",
+ "eas:android:preview": "eas build --profile preview -p android",
+ "eas:android:prod": "eas build --profile production -p android",
+ "ios": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
+ "ios:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
+ "ios:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
+ "ios:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
+ "eas:ios:dev": "eas build --profile development -p ios",
+ "eas:ios:preview": "eas build --profile preview -p ios",
+ "eas:ios:prod": "eas build --profile production -p ios",
+ "eas:dev": "eas build --profile development",
+ "eas:preview": "eas build --profile preview",
+ "eas:prod": "eas build --profile production",
+ "config:dev": "APP_VARIANT=development expo config",
+ "config:preview": "APP_VARIANT=preview expo config",
+ "config:prod": "APP_VARIANT=production expo config",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@callstack/liquid-glass": "^0.7.1",
+ "@effect/atom-react": "catalog:",
+ "@expo-google-fonts/dm-sans": "^0.4.2",
+ "@legendapp/list": "3.0.0-beta.44",
+ "@pierre/diffs": "^1.1.0-beta.16",
+ "@react-native-menu/menu": "^2.0.0",
+ "@t3tools/client-runtime": "workspace:*",
+ "@t3tools/contracts": "workspace:*",
+ "@t3tools/shared": "workspace:*",
+ "clsx": "^2.1.1",
+ "effect": "catalog:",
+ "expo": "~55.0.14",
+ "expo-camera": "~55.0.15",
+ "expo-clipboard": "~55.0.9",
+ "expo-constants": "^55.0.9",
+ "expo-dev-client": "~55.0.26",
+ "expo-file-system": "~55.0.16",
+ "expo-font": "^55.0.4",
+ "expo-glass-effect": "~55.0.8",
+ "expo-haptics": "^55.0.9",
+ "expo-image-picker": "~55.0.14",
+ "expo-linking": "~55.0.12",
+ "expo-paste-input": "^0.1.15",
+ "expo-router": "~55.0.12",
+ "expo-secure-store": "~55.0.9",
+ "expo-splash-screen": "~55.0.13",
+ "expo-symbols": "~55.0.5",
+ "expo-updates": "~55.0.16",
+ "punycode": "^2.3.1",
+ "react": "19.2.5",
+ "react-dom": "19.2.5",
+ "react-native": "0.83.4",
+ "react-native-gesture-handler": "~2.30.0",
+ "react-native-image-viewing": "^0.2.2",
+ "react-native-keyboard-controller": "1.20.7",
+ "react-native-nitro-markdown": "^0.5.3",
+ "react-native-nitro-modules": "^0.35.4",
+ "react-native-reanimated": "4.2.1",
+ "react-native-safe-area-context": "~5.6.2",
+ "react-native-screens": "~4.23.0",
+ "react-native-svg": "15.15.3",
+ "react-native-worklets": "0.7.2",
+ "shiki": "^4.0.2",
+ "tailwind-merge": "^3.5.0",
+ "uniwind": "^1.6.2"
+ },
+ "devDependencies": {
+ "@types/react": "~19.2.0",
+ "babel-preset-expo": "~55.0.8",
+ "tailwindcss": "^4.0.0",
+ "typescript": "catalog:"
+ }
+}
diff --git a/apps/mobile/plugins/withAndroidCleartextTraffic.cjs b/apps/mobile/plugins/withAndroidCleartextTraffic.cjs
new file mode 100644
index 0000000000..f612f751e9
--- /dev/null
+++ b/apps/mobile/plugins/withAndroidCleartextTraffic.cjs
@@ -0,0 +1,18 @@
+const { withAndroidManifest } = require("expo/config-plugins");
+
+module.exports = function withAndroidCleartextTraffic(config) {
+ return withAndroidManifest(config, (nextConfig) => {
+ const application = nextConfig.modResults.manifest.application?.[0];
+
+ if (application == null) {
+ throw new Error(
+ "AndroidManifest.xml is missing the application element required for cleartext traffic configuration.",
+ );
+ }
+
+ application.$ ??= {};
+ application.$["android:usesCleartextTraffic"] = "true";
+
+ return nextConfig;
+ });
+};
diff --git a/apps/mobile/src/app/+not-found.tsx b/apps/mobile/src/app/+not-found.tsx
new file mode 100644
index 0000000000..124077b090
--- /dev/null
+++ b/apps/mobile/src/app/+not-found.tsx
@@ -0,0 +1,43 @@
+import { Link } from "expo-router";
+import { Pressable, ScrollView, StyleSheet } from "react-native";
+import { useResolveClassNames } from "uniwind";
+
+import { AppText as Text } from "../components/AppText";
+
+export default function NotFoundRoute() {
+ const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
+ const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
+
+ return (
+
+
+ Route not found
+
+
+
+ Return home
+
+
+
+ );
+}
diff --git a/apps/mobile/src/app/_layout.tsx b/apps/mobile/src/app/_layout.tsx
new file mode 100644
index 0000000000..15ff31339f
--- /dev/null
+++ b/apps/mobile/src/app/_layout.tsx
@@ -0,0 +1,104 @@
+import "../../global.css";
+import {
+ DMSans_400Regular,
+ DMSans_500Medium,
+ DMSans_700Bold,
+ useFonts,
+} from "@expo-google-fonts/dm-sans";
+import Stack from "expo-router/stack";
+import { StatusBar, useColorScheme } from "react-native";
+import { GestureHandlerRootView } from "react-native-gesture-handler";
+import { KeyboardProvider } from "react-native-keyboard-controller";
+import { SafeAreaProvider } from "react-native-safe-area-context";
+import { useCSSVariable, useResolveClassNames } from "uniwind";
+
+import { LoadingScreen } from "../components/LoadingScreen";
+
+import {
+ useRemoteEnvironmentBootstrap,
+ useRemoteEnvironmentState,
+} from "../state/use-remote-environment-registry";
+import { RegistryContext } from "@effect/atom-react";
+import { appAtomRegistry } from "../state/atom-registry";
+
+function AppNavigator() {
+ const { isLoadingSavedConnection } = useRemoteEnvironmentState();
+ const colorScheme = useColorScheme();
+ const statusBarBg = useCSSVariable("--color-status-bar");
+ const sheetStyle = useResolveClassNames("bg-sheet");
+
+ const newTaskScreenOptions = {
+ contentStyle: sheetStyle,
+ gestureEnabled: true,
+ headerShown: false,
+ presentation: "formSheet" as const,
+ sheetAllowedDetents: [0.92],
+ sheetGrabberVisible: true,
+ };
+
+ const connectionSheetScreenOptions = {
+ contentStyle: sheetStyle,
+ gestureEnabled: true,
+ headerShown: false,
+ presentation: "formSheet" as const,
+ sheetAllowedDetents: [0.55, 0.7],
+ sheetGrabberVisible: true,
+ };
+
+ if (isLoadingSavedConnection) {
+ return ;
+ }
+
+ return (
+ <>
+
+
+
+
+
+
+
+ >
+ );
+}
+
+export default function RootLayout() {
+ const [fontsLoaded] = useFonts({
+ DMSans_400Regular,
+ DMSans_500Medium,
+ DMSans_700Bold,
+ });
+ useRemoteEnvironmentBootstrap();
+
+ return (
+
+
+
+
+ {fontsLoaded ? : }
+
+
+
+
+ );
+}
diff --git a/apps/mobile/src/app/connections/_layout.tsx b/apps/mobile/src/app/connections/_layout.tsx
new file mode 100644
index 0000000000..38ec4c11ed
--- /dev/null
+++ b/apps/mobile/src/app/connections/_layout.tsx
@@ -0,0 +1,30 @@
+import Stack from "expo-router/stack";
+import { useResolveClassNames } from "uniwind";
+
+import { useThemeColor } from "../../lib/useThemeColor";
+
+export const unstable_settings = {
+ anchor: "index",
+};
+
+export default function ConnectionsLayout() {
+ const contentStyle = useResolveClassNames("bg-sheet");
+ const connSheetBg = String(useThemeColor("--color-sheet"));
+ const headerTint = String(useThemeColor("--color-icon"));
+
+ return (
+
+
+
+
+ );
+}
diff --git a/apps/mobile/src/app/connections/index.tsx b/apps/mobile/src/app/connections/index.tsx
new file mode 100644
index 0000000000..a191d35781
--- /dev/null
+++ b/apps/mobile/src/app/connections/index.tsx
@@ -0,0 +1,102 @@
+import { Link, Stack } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useCallback, 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 } from "../../components/AppText";
+import { cn } from "../../lib/cn";
+import { useRemoteConnections } from "../../state/use-remote-environment-registry";
+import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
+
+export default function ConnectionsRouteScreen() {
+ const {
+ connectedEnvironments,
+ onReconnectEnvironment,
+ onRemoveEnvironmentPress,
+ onUpdateEnvironment,
+ } = useRemoteConnections();
+ const insets = useSafeAreaInsets();
+ const hasEnvironments = connectedEnvironments.length > 0;
+ const [expandedId, setExpandedId] = useState(null);
+
+ const primaryFg = useThemeColor("--color-primary-foreground");
+ const accentColor = useThemeColor("--color-icon-muted");
+
+ const handleToggle = useCallback((environmentId: string) => {
+ setExpandedId((prev) => (prev === environmentId ? null : environmentId));
+ }, []);
+
+ return (
+
+ (
+
+
+
+
+
+ ),
+ }}
+ />
+
+ {hasEnvironments ? (
+
+ {connectedEnvironments.map((environment, index) => (
+
+ handleToggle(environment.environmentId)}
+ onReconnect={onReconnectEnvironment}
+ onRemove={onRemoveEnvironmentPress}
+ onUpdate={onUpdateEnvironment}
+ />
+
+ ))}
+
+ ) : (
+
+
+
+
+
+ No backends connected yet.{"\n"}Tap{" "}
+ + to add one.
+
+
+ )}
+
+
+ );
+}
diff --git a/apps/mobile/src/app/connections/new.tsx b/apps/mobile/src/app/connections/new.tsx
new file mode 100644
index 0000000000..1a05ea40c5
--- /dev/null
+++ b/apps/mobile/src/app/connections/new.tsx
@@ -0,0 +1,253 @@
+import { CameraView, useCameraPermissions } from "expo-camera";
+import { Stack, useLocalSearchParams, useRouter } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useCallback, useEffect, useState } from "react";
+import { Alert, Pressable, ScrollView, View } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useThemeColor } from "../../lib/useThemeColor";
+
+import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
+import { ErrorBanner } from "../../components/ErrorBanner";
+import { dismissRoute } from "../../lib/routes";
+import { ConnectionSheetButton } from "../../features/connection/ConnectionSheetButton";
+import { extractPairingUrlFromQrPayload } from "../../features/connection/pairing";
+import { useRemoteConnections } from "../../state/use-remote-environment-registry";
+import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pairing";
+
+export default function ConnectionsNewRouteScreen() {
+ const {
+ connectionError,
+ connectionPairingUrl,
+ connectionState,
+ onChangeConnectionPairingUrl,
+ onConnectPress,
+ } = useRemoteConnections();
+ const router = useRouter();
+ const params = useLocalSearchParams<{ mode?: string }>();
+ const insets = useSafeAreaInsets();
+ const [hostInput, setHostInput] = useState("");
+ const [codeInput, setCodeInput] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
+ const [cameraPermission, requestCameraPermission] = useCameraPermissions();
+ const [scannerLocked, setScannerLocked] = useState(false);
+
+ const textColor = useThemeColor("--color-icon");
+ const placeholderColor = useThemeColor("--color-placeholder");
+
+ const connectDisabled =
+ isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
+
+ useEffect(() => {
+ const { host, code } = parsePairingUrl(connectionPairingUrl);
+ setHostInput(host);
+ setCodeInput(code);
+ }, [connectionPairingUrl]);
+
+ useEffect(() => {
+ if (connectionError) {
+ setIsSubmitting(false);
+ }
+ }, [connectionError]);
+
+ const handleHostChange = useCallback((value: string) => {
+ setHostInput(value);
+ }, []);
+
+ const handleCodeChange = useCallback((value: string) => {
+ setCodeInput(value);
+ }, []);
+
+ const openScanner = useCallback(async () => {
+ if (cameraPermission?.granted) {
+ setScannerLocked(false);
+ setShowScanner(true);
+ return;
+ }
+
+ const permission = await requestCameraPermission();
+ if (permission.granted) {
+ setScannerLocked(false);
+ setShowScanner(true);
+ return;
+ }
+
+ Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
+ }, [cameraPermission?.granted, requestCameraPermission]);
+
+ const closeScanner = useCallback(() => {
+ setShowScanner(false);
+ setScannerLocked(false);
+ }, []);
+
+ const handleQrScan = useCallback(
+ ({ data }: { readonly data: string }) => {
+ if (scannerLocked) {
+ return;
+ }
+
+ setScannerLocked(true);
+
+ try {
+ const pairingUrl = extractPairingUrlFromQrPayload(data);
+ const { host, code } = parsePairingUrl(pairingUrl);
+ setHostInput(host);
+ setCodeInput(code);
+ onChangeConnectionPairingUrl(pairingUrl);
+ setShowScanner(false);
+ } catch (error) {
+ Alert.alert(
+ "Invalid QR code",
+ error instanceof Error ? error.message : "Scanned QR code was not recognized.",
+ );
+ } finally {
+ setTimeout(() => {
+ setScannerLocked(false);
+ }, 600);
+ }
+ },
+ [onChangeConnectionPairingUrl, scannerLocked],
+ );
+
+ const handleSubmit = useCallback(async () => {
+ setIsSubmitting(true);
+
+ try {
+ const pairingUrl = buildPairingUrl(hostInput, codeInput);
+ onChangeConnectionPairingUrl(pairingUrl);
+ await onConnectPress(pairingUrl);
+ dismissRoute(router);
+ } catch {
+ setIsSubmitting(false);
+ }
+ }, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
+
+ return (
+
+ (
+ {
+ if (showScanner) {
+ closeScanner();
+ } else {
+ void openScanner();
+ }
+ }}
+ >
+
+
+ ),
+ }}
+ />
+
+
+
+ {showScanner ? (
+ cameraPermission?.granted ? (
+
+
+
+ ) : (
+
+
+ Camera permission is required to scan a QR code.
+
+ {
+ void openScanner();
+ }}
+ />
+
+ )
+ ) : (
+
+
+
+ Host
+
+
+
+
+
+
+ Pairing code
+
+
+
+
+ {connectionError ? : null}
+
+ {
+ void handleSubmit();
+ }}
+ />
+
+ )}
+
+
+
+ );
+}
diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx
new file mode 100644
index 0000000000..f153db7013
--- /dev/null
+++ b/apps/mobile/src/app/index.tsx
@@ -0,0 +1,139 @@
+import { Stack, useRouter } from "expo-router";
+import { useState } from "react";
+import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
+import { useThemeColor } from "../lib/useThemeColor";
+
+import { buildThreadRoutePath } from "../lib/routes";
+import { ConnectionStatusDot } from "../features/connection/ConnectionStatusDot";
+import { useRemoteCatalog } from "../state/use-remote-catalog";
+import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
+import { HomeScreen } from "../features/home/HomeScreen";
+import { EnvironmentConnectionState } from "@t3tools/client-runtime";
+
+/* ─── Connection pill label ──────────────────────────────────────────── */
+
+const CONNECTION_LABEL: Record = {
+ ready: "Connected",
+ connecting: "Connecting",
+ reconnecting: "Reconnecting",
+ disconnected: "Offline",
+ idle: "No backends",
+};
+
+/* ─── Route screen ───────────────────────────────────────────────────── */
+
+export default function HomeRouteScreen() {
+ const { connectionState, hasRemoteActivity, projects, threads } = useRemoteCatalog();
+ const { savedConnectionsById } = useRemoteEnvironmentState();
+ const router = useRouter();
+ const [searchQuery, setSearchQuery] = useState("");
+
+ const isDark = useColorScheme() === "dark";
+ const iconColor = String(useThemeColor("--color-icon"));
+ const secondaryFg = isDark ? "#a3a3a3" : "#525252";
+
+ return (
+ <>
+ (
+ router.push("/connections")}
+ hitSlop={8}
+ style={{
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 8,
+ paddingHorizontal: 4,
+ paddingVertical: 4,
+ }}
+ >
+
+
+ {CONNECTION_LABEL[connectionState]}
+
+
+ ),
+ headerSearchBarOptions: {
+ placeholder: "Search threads",
+ onChangeText: (event) => {
+ setSearchQuery(event.nativeEvent.text);
+ },
+ allowToolbarIntegration: true,
+ },
+ }}
+ />
+
+ {/* Header left: plain text, no Liquid Glass button chrome */}
+
+
+
+
+ T3 Code
+
+
+
+ Alpha
+
+
+
+
+
+
+ {/* Bottom toolbar: search + compose, visually split like iMessage */}
+
+
+
+ router.push("/new")}
+ separateBackground
+ />
+
+
+ {
+ router.push(buildThreadRoutePath(thread));
+ }}
+ />
+ >
+ );
+}
diff --git a/apps/mobile/src/app/new/_layout.tsx b/apps/mobile/src/app/new/_layout.tsx
new file mode 100644
index 0000000000..7205e74509
--- /dev/null
+++ b/apps/mobile/src/app/new/_layout.tsx
@@ -0,0 +1,25 @@
+import Stack from "expo-router/stack";
+import { useResolveClassNames } from "uniwind";
+
+import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
+
+export const unstable_settings = {
+ anchor: "index",
+};
+
+export default function NewTaskLayout() {
+ const sheetStyle = useResolveClassNames("bg-sheet");
+
+ return (
+
+
+
+
+
+
+ );
+}
diff --git a/apps/mobile/src/app/new/draft.tsx b/apps/mobile/src/app/new/draft.tsx
new file mode 100644
index 0000000000..b2f1f24e76
--- /dev/null
+++ b/apps/mobile/src/app/new/draft.tsx
@@ -0,0 +1,24 @@
+import { Stack, useLocalSearchParams } from "expo-router";
+
+import { NewTaskDraftScreen } from "../../features/threads/NewTaskDraftScreen";
+
+export default function NewTaskDraftRoute() {
+ const params = useLocalSearchParams<{
+ environmentId?: string | string[];
+ projectId?: string | string[];
+ }>();
+
+ return (
+ <>
+
+
+ >
+ );
+}
diff --git a/apps/mobile/src/app/new/index.tsx b/apps/mobile/src/app/new/index.tsx
new file mode 100644
index 0000000000..cd87abd1cf
--- /dev/null
+++ b/apps/mobile/src/app/new/index.tsx
@@ -0,0 +1,135 @@
+import { Link, Stack } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useMemo } 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 } from "../../components/AppText";
+import { ProjectFavicon } from "../../components/ProjectFavicon";
+import { groupProjectsByRepository } from "../../lib/repositoryGroups";
+import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
+
+export default function NewTaskRoute() {
+ const { projects, threads } = useRemoteCatalog();
+ const { savedConnectionsById } = useRemoteEnvironmentState();
+ const insets = useSafeAreaInsets();
+ const chevronColor = useThemeColor("--color-chevron");
+ const borderSubtleColor = useThemeColor("--color-border-subtle");
+ const repositoryGroups = useMemo(
+ () => groupProjectsByRepository({ projects, threads }),
+ [projects, threads],
+ );
+ const items = useMemo(
+ () =>
+ repositoryGroups
+ .map((group) => {
+ const project = group.projects[0]?.project;
+ if (!project) {
+ return null;
+ }
+
+ return {
+ environmentId: project.environmentId,
+ id: project.id,
+ key: group.key,
+ title: project.title,
+ workspaceRoot: project.workspaceRoot,
+ };
+ })
+ .filter((entry) => entry !== null),
+ [repositoryGroups],
+ );
+
+ return (
+
+
+
+
+
+
+
+ New task
+
+ Choose project
+
+
+
+ {items.length === 0 ? (
+
+
+ Loading projects...
+
+
+ ) : (
+
+ {items.map((item, index) => {
+ const isFirst = index === 0;
+ const isLast = index === items.length - 1;
+
+ return (
+
+
+
+
+
+ {item.title}
+
+
+
+
+
+ );
+ })}
+
+ )}
+
+
+ );
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx
new file mode 100644
index 0000000000..898bebae63
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx
@@ -0,0 +1,69 @@
+import Stack from "expo-router/stack";
+import { StyleSheet } from "react-native";
+import { useResolveClassNames } from "uniwind";
+
+export default function ThreadLayout() {
+ const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
+ const headerBg = {
+ backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
+ };
+
+ return (
+
+
+
+
+
+
+
+ );
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx
new file mode 100644
index 0000000000..3773ce55b2
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx
@@ -0,0 +1,5 @@
+import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
+
+export default function GitConfirmRoute() {
+ return ;
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx
new file mode 100644
index 0000000000..15b10c295f
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx
@@ -0,0 +1,58 @@
+import Stack from "expo-router/stack";
+import { StyleSheet } from "react-native";
+import { useResolveClassNames } from "uniwind";
+
+export const unstable_settings = {
+ anchor: "index",
+};
+
+export default function GitSheetLayout() {
+ const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
+ const headerBg = {
+ backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
+ };
+
+ return (
+
+
+
+
+
+
+ );
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx
new file mode 100644
index 0000000000..955e4febd7
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx
@@ -0,0 +1,5 @@
+import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
+
+export default function GitBranchesRoute() {
+ return ;
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx
new file mode 100644
index 0000000000..4510f81a8c
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx
@@ -0,0 +1,5 @@
+import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
+
+export default function GitCommitRoute() {
+ return ;
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx
new file mode 100644
index 0000000000..dd099d80d2
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx
@@ -0,0 +1,5 @@
+import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
+
+export default function GitRoute() {
+ return ;
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx
new file mode 100644
index 0000000000..dd28795c12
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx
@@ -0,0 +1,17 @@
+import { Redirect, useLocalSearchParams } from "expo-router";
+
+export default function ReviewRoute() {
+ const { environmentId, threadId } = useLocalSearchParams<{
+ environmentId: string;
+ threadId: string;
+ }>();
+
+ return (
+
+ );
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx
new file mode 100644
index 0000000000..4586ee93ca
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx
@@ -0,0 +1,5 @@
+import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
+
+export default function ThreadRoute() {
+ return ;
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx
new file mode 100644
index 0000000000..1e77810270
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx
@@ -0,0 +1,5 @@
+import { ReviewCommentComposerSheet } from "../../../../features/threads/review/ReviewCommentComposerSheet";
+
+export default function ReviewCommentRoute() {
+ return ;
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
new file mode 100644
index 0000000000..193d0e8f47
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
@@ -0,0 +1,5 @@
+import { ReviewSheet } from "../../../../features/threads/review/ReviewSheet";
+
+export default function ReviewRoute() {
+ return ;
+}
diff --git a/apps/mobile/src/components/AppText.tsx b/apps/mobile/src/components/AppText.tsx
new file mode 100644
index 0000000000..ece05b1df4
--- /dev/null
+++ b/apps/mobile/src/components/AppText.tsx
@@ -0,0 +1,40 @@
+import {
+ Text as RNText,
+ TextInput as RNTextInput,
+ type TextInputProps as RNTextInputProps,
+ type TextProps as RNTextProps,
+} from "react-native";
+import { useThemeColor } from "../lib/useThemeColor";
+
+import { cn } from "../lib/cn";
+
+export type AppTextProps = RNTextProps & { readonly className?: string };
+
+/**
+ * Thin wrapper around RN Text with default font-family and foreground color.
+ * Uses Uniwind className — no manual style parsing.
+ */
+export function AppText({ className, ...props }: AppTextProps) {
+ return ;
+}
+
+export type AppTextInputProps = RNTextInputProps & { readonly className?: string };
+
+/**
+ * Thin wrapper around RN TextInput with default input styling.
+ * Uses Uniwind className — no manual style parsing.
+ */
+export function AppTextInput({ className, placeholderTextColor, ...props }: AppTextInputProps) {
+ const placeholderColor = useThemeColor("--color-placeholder");
+
+ return (
+
+ );
+}
diff --git a/apps/mobile/src/components/BrandMark.tsx b/apps/mobile/src/components/BrandMark.tsx
new file mode 100644
index 0000000000..0373cd8932
--- /dev/null
+++ b/apps/mobile/src/components/BrandMark.tsx
@@ -0,0 +1,48 @@
+import { Image, View } from "react-native";
+
+import { AppText as Text } from "./AppText";
+
+const BRAND_MARK_SOURCE = require("../../../../assets/dev/blueprint-ios-1024.png");
+
+export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) {
+ const compact = props.compact ?? false;
+ const iconSize = compact ? 32 : 44;
+ const stageLabel = props.stageLabel ?? "Alpha";
+
+ return (
+
+
+
+
+
+ T3 Code
+
+
+
+ {stageLabel}
+
+
+
+ {!compact ? (
+
+ Mobile control surface for your live coding environments
+
+ ) : null}
+
+
+ );
+}
diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx
new file mode 100644
index 0000000000..239b03010b
--- /dev/null
+++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx
@@ -0,0 +1,85 @@
+import { SymbolView } from "expo-symbols";
+import { Image, Pressable, ScrollView, View } from "react-native";
+import { useThemeColor } from "../lib/useThemeColor";
+
+import type { DraftComposerImageAttachment } from "../lib/composerImages";
+
+export interface ComposerAttachmentStripProps {
+ /** Attachment images to display. */
+ readonly attachments: ReadonlyArray;
+ /** Called when the user taps the remove button on an image. */
+ readonly onRemove: (imageId: string) => void;
+ /** Called when the user taps on an image thumbnail to preview it. */
+ readonly onPressImage?: (previewUri: string) => void;
+ /** Image thumbnail size in points. Defaults to 72. */
+ readonly imageSize?: number;
+ /** Border radius of each image thumbnail. Defaults to 16. */
+ readonly imageBorderRadius?: number;
+}
+
+/**
+ * A horizontally-scrollable strip of image attachment thumbnails with remove
+ * buttons. Used by both the thread composer and the new-task draft screen.
+ */
+export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
+ const subtleBg = useThemeColor("--color-subtle");
+ const size = props.imageSize ?? 72;
+ const radius = props.imageBorderRadius ?? 16;
+
+ if (props.attachments.length === 0) {
+ return null;
+ }
+
+ return (
+
+
+ {props.attachments.map((image) => (
+
+ props.onPressImage!(image.previewUri) : undefined}
+ >
+
+
+ props.onRemove(image.id)}
+ >
+
+
+
+ ))}
+
+
+ );
+}
diff --git a/apps/mobile/src/components/ControlPill.tsx b/apps/mobile/src/components/ControlPill.tsx
new file mode 100644
index 0000000000..fbbba2691e
--- /dev/null
+++ b/apps/mobile/src/components/ControlPill.tsx
@@ -0,0 +1,67 @@
+import type { ComponentProps, ReactNode } from "react";
+import { Pressable, View } from "react-native";
+import { SymbolView } from "expo-symbols";
+import { useThemeColor } from "../lib/useThemeColor";
+
+import { cn } from "../lib/cn";
+import { AppText as Text } from "./AppText";
+
+export function ControlPill(props: {
+ readonly icon?: ComponentProps["name"];
+ readonly iconNode?: ReactNode;
+ readonly label?: string;
+ readonly onPress?: () => void;
+ readonly variant?: "circle" | "pill" | "primary" | "danger";
+ readonly disabled?: boolean;
+}) {
+ const variant = props.variant ?? "circle";
+
+ const iconColor = useThemeColor("--color-icon");
+ const iconSubtle = useThemeColor("--color-icon-subtle");
+ const primaryFg = useThemeColor("--color-primary-foreground");
+ const dangerFg = useThemeColor("--color-danger-foreground");
+ const iconTintColor =
+ variant === "primary"
+ ? props.disabled
+ ? iconSubtle
+ : primaryFg
+ : variant === "danger"
+ ? dangerFg
+ : iconColor;
+
+ const isCircle =
+ variant === "circle" || variant === "danger" || (variant === "primary" && !props.label);
+ const containerClassName = cn(
+ isCircle
+ ? "h-11 w-11 items-center justify-center rounded-full"
+ : variant === "primary"
+ ? "h-11 flex-row items-center justify-center gap-2 rounded-full px-5"
+ : "h-11 flex-row items-center justify-center gap-2 rounded-full px-3.5",
+ variant === "primary"
+ ? props.disabled
+ ? "bg-subtle-strong"
+ : "bg-primary"
+ : variant === "danger"
+ ? "bg-danger"
+ : "bg-subtle",
+ );
+ const labelClassName = cn(
+ "text-center text-[12px] font-t3-bold",
+ variant === "primary"
+ ? props.disabled
+ ? "text-foreground-muted"
+ : "text-primary-foreground"
+ : "",
+ );
+
+ return (
+
+ {props.iconNode ? (
+ {props.iconNode}
+ ) : props.icon ? (
+
+ ) : null}
+ {props.label ? {props.label} : null}
+
+ );
+}
diff --git a/apps/mobile/src/components/EmptyState.tsx b/apps/mobile/src/components/EmptyState.tsx
new file mode 100644
index 0000000000..30ded6045a
--- /dev/null
+++ b/apps/mobile/src/components/EmptyState.tsx
@@ -0,0 +1,14 @@
+import { View } from "react-native";
+
+import { AppText as Text } from "./AppText";
+
+export function EmptyState(props: { readonly title: string; readonly detail: string }) {
+ return (
+
+ {props.title}
+
+ {props.detail}
+
+
+ );
+}
diff --git a/apps/mobile/src/components/ErrorBanner.tsx b/apps/mobile/src/components/ErrorBanner.tsx
new file mode 100644
index 0000000000..3fb8ba5d91
--- /dev/null
+++ b/apps/mobile/src/components/ErrorBanner.tsx
@@ -0,0 +1,12 @@
+import { View } from "react-native";
+
+import { AppText as Text } from "./AppText";
+export function ErrorBanner(props: { readonly message: string }) {
+ return (
+
+
+ {props.message}
+
+
+ );
+}
diff --git a/apps/mobile/src/components/GlassSafeAreaView.tsx b/apps/mobile/src/components/GlassSafeAreaView.tsx
new file mode 100644
index 0000000000..f7cc49c368
--- /dev/null
+++ b/apps/mobile/src/components/GlassSafeAreaView.tsx
@@ -0,0 +1,59 @@
+import type { ReactNode } from "react";
+import { useColorScheme, View, type StyleProp, type ViewStyle } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { GlassSurface } from "./GlassSurface";
+
+export interface GlassSafeAreaViewProps {
+ readonly leftSlot?: ReactNode;
+ readonly centerSlot?: ReactNode;
+ readonly rightSlot?: ReactNode;
+ readonly style?: StyleProp;
+}
+
+export function GlassSafeAreaView({
+ leftSlot,
+ centerSlot,
+ rightSlot,
+ style,
+}: GlassSafeAreaViewProps) {
+ const isDarkMode = useColorScheme() === "dark";
+ const insets = useSafeAreaInsets();
+ const headerPaddingTop = insets.top + 16;
+ const surfaceStyle = {
+ borderRadius: 0,
+ backgroundColor: isDarkMode ? "rgba(10,10,10,0.97)" : "rgba(255,255,255,0.97)",
+ borderBottomWidth: 1,
+ borderBottomColor: isDarkMode ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",
+ } as const;
+
+ return (
+
+
+
+ {leftSlot}
+
+ {centerSlot}
+
+ {rightSlot}
+
+
+
+ );
+}
diff --git a/apps/mobile/src/components/GlassSurface.tsx b/apps/mobile/src/components/GlassSurface.tsx
new file mode 100644
index 0000000000..fba6d8e801
--- /dev/null
+++ b/apps/mobile/src/components/GlassSurface.tsx
@@ -0,0 +1,73 @@
+import { GlassView, isGlassEffectAPIAvailable } from "expo-glass-effect";
+import type { ReactNode } from "react";
+import { Platform, useColorScheme, View, type ViewProps, type ViewStyle } from "react-native";
+
+export interface GlassSurfaceProps extends ViewProps {
+ readonly children: ReactNode;
+ readonly glassEffectStyle?: "clear" | "regular" | "none";
+ readonly tintColor?: string;
+ readonly chrome?: "default" | "none";
+}
+
+export function GlassSurface({
+ children,
+ glassEffectStyle = "regular",
+ chrome = "default",
+ tintColor,
+ style,
+ ...props
+}: GlassSurfaceProps) {
+ const isDarkMode = useColorScheme() === "dark";
+ const supportsGlass = Platform.OS === "ios" && isGlassEffectAPIAvailable();
+ const surfaceStyle: ViewStyle = {
+ borderRadius: 32,
+ overflow: "hidden",
+ borderWidth: chrome === "none" ? 0 : 1,
+ borderColor:
+ chrome === "none"
+ ? "transparent"
+ : isDarkMode
+ ? "rgba(255,255,255,0.08)"
+ : "rgba(226,232,240,0.9)",
+ backgroundColor:
+ chrome === "none"
+ ? "transparent"
+ : isDarkMode
+ ? "rgba(15,23,42,0.78)"
+ : "rgba(255,255,255,0.72)",
+ shadowColor: chrome === "none" ? "transparent" : "#020617",
+ shadowOpacity: chrome === "none" ? 0 : isDarkMode ? 0.22 : 0.08,
+ shadowRadius: chrome === "none" ? 0 : 28,
+ shadowOffset:
+ chrome === "none"
+ ? {
+ width: 0,
+ height: 0,
+ }
+ : {
+ width: 0,
+ height: 14,
+ },
+ elevation: chrome === "none" ? 0 : 12,
+ };
+
+ if (supportsGlass) {
+ return (
+
+ {children}
+
+ );
+ }
+
+ return (
+
+ {children}
+
+ );
+}
diff --git a/apps/mobile/src/components/LoadingScreen.tsx b/apps/mobile/src/components/LoadingScreen.tsx
new file mode 100644
index 0000000000..8b8083832c
--- /dev/null
+++ b/apps/mobile/src/components/LoadingScreen.tsx
@@ -0,0 +1,27 @@
+import { ActivityIndicator, StatusBar, View, useColorScheme } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useThemeColor } from "../lib/useThemeColor";
+
+import { AppText as Text } from "./AppText";
+import { BrandMark } from "./BrandMark";
+
+export function LoadingScreen(props: { readonly message: string }) {
+ const colorScheme = useColorScheme();
+ const screenBg = useThemeColor("--color-screen");
+ const insets = useSafeAreaInsets();
+
+ return (
+
+
+
+
+
+ {props.message}
+
+
+ );
+}
diff --git a/apps/mobile/src/components/ProjectFavicon.tsx b/apps/mobile/src/components/ProjectFavicon.tsx
new file mode 100644
index 0000000000..32297d8d9d
--- /dev/null
+++ b/apps/mobile/src/components/ProjectFavicon.tsx
@@ -0,0 +1,70 @@
+import { SymbolView } from "expo-symbols";
+import { useState } from "react";
+import { Image, View } from "react-native";
+import { useThemeColor } from "../lib/useThemeColor";
+
+/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
+const loadedFaviconUrls = new Set();
+
+/* ─── Component ──────────────────────────────────────────────────────── */
+export function ProjectFavicon(props: {
+ readonly size?: number;
+ readonly projectTitle: string;
+ readonly httpBaseUrl?: string | null;
+ readonly workspaceRoot?: string | null;
+ readonly bearerToken?: string | null;
+}) {
+ const size = props.size ?? 42;
+ const iconMuted = useThemeColor("--color-icon-subtle");
+
+ const faviconUrl =
+ props.httpBaseUrl && props.workspaceRoot
+ ? `${props.httpBaseUrl}/api/project-favicon?cwd=${encodeURIComponent(props.workspaceRoot)}`
+ : null;
+
+ const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
+ faviconUrl && loadedFaviconUrls.has(faviconUrl) ? "loaded" : "loading",
+ );
+
+ const showImage = faviconUrl && status === "loaded";
+
+ return (
+
+ {/* Folder icon fallback (matches web's FolderIcon) */}
+ {!showImage ? (
+
+ ) : null}
+
+ {/* Favicon image (hidden until loaded) */}
+ {faviconUrl ? (
+ {
+ if (faviconUrl) loadedFaviconUrls.add(faviconUrl);
+ setStatus("loaded");
+ }}
+ onError={() => setStatus("error")}
+ />
+ ) : null}
+
+ );
+}
diff --git a/apps/mobile/src/components/ProviderIcon.tsx b/apps/mobile/src/components/ProviderIcon.tsx
new file mode 100644
index 0000000000..d62f8d9a4b
--- /dev/null
+++ b/apps/mobile/src/components/ProviderIcon.tsx
@@ -0,0 +1,32 @@
+import { useColorScheme } from "react-native";
+import { Path, Svg } from "react-native-svg";
+
+type ProviderIconProps = {
+ readonly provider: string | null | undefined;
+ readonly size?: number;
+};
+
+export function ProviderIcon(props: ProviderIconProps) {
+ const isDarkMode = useColorScheme() === "dark";
+ const size = props.size ?? 16;
+
+ if (props.provider === "claudeAgent") {
+ return (
+
+ );
+ }
+
+ return (
+
+ );
+}
diff --git a/apps/mobile/src/components/StatusPill.tsx b/apps/mobile/src/components/StatusPill.tsx
new file mode 100644
index 0000000000..34e6f74b60
--- /dev/null
+++ b/apps/mobile/src/components/StatusPill.tsx
@@ -0,0 +1,37 @@
+import { View } from "react-native";
+
+import { AppText as Text } from "./AppText";
+import { cn } from "../lib/cn";
+
+export interface StatusTone {
+ readonly label: string;
+ readonly pillClassName: string;
+ readonly textClassName: string;
+}
+
+export function StatusPill(
+ props: StatusTone & {
+ readonly size?: "default" | "compact";
+ },
+) {
+ const size = props.size ?? "default";
+ return (
+
+
+ {props.label}
+
+
+ );
+}
diff --git a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx
new file mode 100644
index 0000000000..1c75bff8f8
--- /dev/null
+++ b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx
@@ -0,0 +1,157 @@
+import { SymbolView } from "expo-symbols";
+import { useCallback, useState } from "react";
+import { Pressable, View } from "react-native";
+import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
+import { useThemeColor } from "../../lib/useThemeColor";
+
+import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
+import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
+import { ConnectionStatusDot } from "./ConnectionStatusDot";
+
+export function ConnectionEnvironmentRow(props: {
+ readonly environment: ConnectedEnvironmentSummary;
+ readonly expanded: boolean;
+ readonly onToggle: () => void;
+ readonly onReconnect: (environmentId: string) => void;
+ readonly onRemove: (environmentId: string) => void;
+ readonly onUpdate: (
+ environmentId: string,
+ updates: { readonly label: string; readonly displayUrl: string },
+ ) => void;
+}) {
+ const [label, setLabel] = useState(props.environment.environmentLabel);
+ 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 handleSave = useCallback(() => {
+ props.onUpdate(props.environment.environmentId, {
+ label: label.trim(),
+ displayUrl: url.trim(),
+ });
+ props.onToggle();
+ }, [label, url, props]);
+
+ return (
+
+
+
+
+
+
+ {props.environment.environmentLabel}
+
+
+ {props.environment.displayUrl}
+
+ {props.environment.connectionError ? (
+
+ {props.environment.connectionError}
+
+ ) : null}
+
+
+
+
+
+ {props.expanded ? (
+
+
+
+ Label
+
+
+
+
+
+
+ URL
+
+
+
+
+
+
+
+
+ Save
+
+
+
+ props.onReconnect(props.environment.environmentId)}
+ >
+
+
+
+ props.onRemove(props.environment.environmentId)}
+ >
+
+
+
+
+ ) : null}
+
+ );
+}
diff --git a/apps/mobile/src/features/connection/ConnectionSheetButton.tsx b/apps/mobile/src/features/connection/ConnectionSheetButton.tsx
new file mode 100644
index 0000000000..1a03061e23
--- /dev/null
+++ b/apps/mobile/src/features/connection/ConnectionSheetButton.tsx
@@ -0,0 +1,114 @@
+import { SymbolView } from "expo-symbols";
+import { Platform, Pressable } from "react-native";
+import { useThemeColor } from "../../lib/useThemeColor";
+
+import { AppText as Text } from "../../components/AppText";
+import { cn } from "../../lib/cn";
+
+const CARD_SHADOW = Platform.select({
+ ios: {
+ shadowColor: "rgba(23,23,23,0.08)",
+ shadowOffset: { width: 0, height: 4 },
+ shadowOpacity: 1,
+ shadowRadius: 16,
+ },
+ android: { elevation: 3 },
+});
+
+const CARD_SHADOW_DARK = Platform.select({
+ ios: {
+ shadowColor: "#000",
+ shadowOffset: { width: 0, height: 2 },
+ shadowOpacity: 0.18,
+ shadowRadius: 8,
+ },
+ android: { elevation: 4 },
+});
+
+export { CARD_SHADOW, CARD_SHADOW_DARK };
+
+export function ConnectionSheetButton(props: {
+ readonly icon: React.ComponentProps["name"];
+ readonly label: string;
+ readonly disabled?: boolean;
+ readonly tone?: "primary" | "secondary" | "danger";
+ readonly compact?: boolean;
+ readonly onPress: () => void;
+}) {
+ 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 primaryShadow =
+ tone === "primary"
+ ? Platform.select({
+ ios: {
+ shadowColor: "#000",
+ shadowOffset: { width: 0, height: 3 },
+ shadowOpacity: 0.14,
+ shadowRadius: 6,
+ },
+ android: { elevation: 3 },
+ })
+ : undefined;
+
+ return (
+
+
+
+ {props.label}
+
+
+ );
+}
diff --git a/apps/mobile/src/features/connection/ConnectionStatusDot.tsx b/apps/mobile/src/features/connection/ConnectionStatusDot.tsx
new file mode 100644
index 0000000000..60d86e0118
--- /dev/null
+++ b/apps/mobile/src/features/connection/ConnectionStatusDot.tsx
@@ -0,0 +1,112 @@
+import { useEffect } from "react";
+import { View } from "react-native";
+import Animated, {
+ cancelAnimation,
+ Easing,
+ useAnimatedStyle,
+ useSharedValue,
+ withRepeat,
+ withTiming,
+} from "react-native-reanimated";
+
+import type { RemoteClientConnectionState } from "../../lib/connection";
+
+function statusDotTone(state: RemoteClientConnectionState): {
+ readonly dotColor: string;
+ readonly haloColor: string;
+} {
+ switch (state) {
+ case "ready":
+ return {
+ dotColor: "#34d399",
+ haloColor: "rgba(52,211,153,0.48)",
+ };
+ case "connecting":
+ case "reconnecting":
+ return {
+ dotColor: "#f59e0b",
+ haloColor: "rgba(245,158,11,0.5)",
+ };
+ case "idle":
+ case "disconnected":
+ return {
+ dotColor: "#ef4444",
+ haloColor: "rgba(239,68,68,0.48)",
+ };
+ }
+}
+
+function usePulseAnimation(pulse: boolean) {
+ const pulseProgress = useSharedValue(0);
+
+ useEffect(() => {
+ if (pulse) {
+ pulseProgress.value = withRepeat(
+ withTiming(1, {
+ duration: 1100,
+ easing: Easing.out(Easing.cubic),
+ }),
+ -1,
+ false,
+ );
+ return;
+ }
+
+ cancelAnimation(pulseProgress);
+ pulseProgress.value = withTiming(0, {
+ duration: 180,
+ easing: Easing.out(Easing.quad),
+ });
+ }, [pulse, pulseProgress]);
+
+ return pulseProgress;
+}
+
+export function ConnectionStatusDot(props: {
+ readonly state: RemoteClientConnectionState;
+ readonly pulse: boolean;
+ readonly size?: number;
+}) {
+ const pulseProgress = usePulseAnimation(props.pulse);
+ const tone = statusDotTone(props.state);
+ const dotSize = props.size ?? 10;
+ const haloSize = dotSize + 4;
+ const containerSize = haloSize + 4;
+
+ const haloStyle = useAnimatedStyle(() => ({
+ opacity: props.pulse ? 0.14 + (1 - pulseProgress.value) * 0.3 : 0,
+ transform: [{ scale: 0.78 + pulseProgress.value * 1.16 }],
+ }));
+
+ return (
+
+
+
+
+ );
+}
diff --git a/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx b/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx
new file mode 100644
index 0000000000..85a7e587e2
--- /dev/null
+++ b/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx
@@ -0,0 +1,253 @@
+import { CameraView, useCameraPermissions } from "expo-camera";
+import { Stack, useLocalSearchParams, useRouter } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useCallback, useEffect, useState } from "react";
+import { Alert, Pressable, ScrollView, View } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useThemeColor } from "../../lib/useThemeColor";
+
+import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
+import { ErrorBanner } from "../../components/ErrorBanner";
+import { dismissRoute } from "../../lib/routes";
+import { ConnectionSheetButton } from "./ConnectionSheetButton";
+import { extractPairingUrlFromQrPayload } from "./pairing";
+import { useRemoteConnections } from "../../state/use-remote-environment-registry";
+import { buildPairingUrl, parsePairingUrl } from "./pairing";
+
+export function NewConnectionRouteScreen() {
+ const {
+ connectionError,
+ connectionPairingUrl,
+ connectionState,
+ onChangeConnectionPairingUrl,
+ onConnectPress,
+ } = useRemoteConnections();
+ const router = useRouter();
+ const params = useLocalSearchParams<{ mode?: string }>();
+ const insets = useSafeAreaInsets();
+ const [hostInput, setHostInput] = useState("");
+ const [codeInput, setCodeInput] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
+ const [cameraPermission, requestCameraPermission] = useCameraPermissions();
+ const [scannerLocked, setScannerLocked] = useState(false);
+
+ const textColor = useThemeColor("--color-icon");
+ const placeholderColor = useThemeColor("--color-placeholder");
+
+ const connectDisabled =
+ isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
+
+ useEffect(() => {
+ const { host, code } = parsePairingUrl(connectionPairingUrl);
+ setHostInput(host);
+ setCodeInput(code);
+ }, [connectionPairingUrl]);
+
+ useEffect(() => {
+ if (connectionError) {
+ setIsSubmitting(false);
+ }
+ }, [connectionError]);
+
+ const handleHostChange = useCallback((value: string) => {
+ setHostInput(value);
+ }, []);
+
+ const handleCodeChange = useCallback((value: string) => {
+ setCodeInput(value);
+ }, []);
+
+ const openScanner = useCallback(async () => {
+ if (cameraPermission?.granted) {
+ setScannerLocked(false);
+ setShowScanner(true);
+ return;
+ }
+
+ const permission = await requestCameraPermission();
+ if (permission.granted) {
+ setScannerLocked(false);
+ setShowScanner(true);
+ return;
+ }
+
+ Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
+ }, [cameraPermission?.granted, requestCameraPermission]);
+
+ const closeScanner = useCallback(() => {
+ setShowScanner(false);
+ setScannerLocked(false);
+ }, []);
+
+ const handleQrScan = useCallback(
+ ({ data }: { readonly data: string }) => {
+ if (scannerLocked) {
+ return;
+ }
+
+ setScannerLocked(true);
+
+ try {
+ const pairingUrl = extractPairingUrlFromQrPayload(data);
+ const { host, code } = parsePairingUrl(pairingUrl);
+ setHostInput(host);
+ setCodeInput(code);
+ onChangeConnectionPairingUrl(pairingUrl);
+ setShowScanner(false);
+ } catch (error) {
+ Alert.alert(
+ "Invalid QR code",
+ error instanceof Error ? error.message : "Scanned QR code was not recognized.",
+ );
+ } finally {
+ setTimeout(() => {
+ setScannerLocked(false);
+ }, 600);
+ }
+ },
+ [onChangeConnectionPairingUrl, scannerLocked],
+ );
+
+ const handleSubmit = useCallback(async () => {
+ setIsSubmitting(true);
+
+ try {
+ const pairingUrl = buildPairingUrl(hostInput, codeInput);
+ onChangeConnectionPairingUrl(pairingUrl);
+ await onConnectPress(pairingUrl);
+ dismissRoute(router);
+ } catch {
+ setIsSubmitting(false);
+ }
+ }, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
+
+ return (
+
+ (
+ {
+ if (showScanner) {
+ closeScanner();
+ } else {
+ void openScanner();
+ }
+ }}
+ >
+
+
+ ),
+ }}
+ />
+
+
+
+ {showScanner ? (
+ cameraPermission?.granted ? (
+
+
+
+ ) : (
+
+
+ Camera permission is required to scan a QR code.
+
+ {
+ void openScanner();
+ }}
+ />
+
+ )
+ ) : (
+
+
+
+ Host
+
+
+
+
+
+
+ Pairing code
+
+
+
+
+ {connectionError ? : null}
+
+ {
+ void handleSubmit();
+ }}
+ />
+
+ )}
+
+
+
+ );
+}
diff --git a/apps/mobile/src/features/connection/connectionTone.ts b/apps/mobile/src/features/connection/connectionTone.ts
new file mode 100644
index 0000000000..5e17b469de
--- /dev/null
+++ b/apps/mobile/src/features/connection/connectionTone.ts
@@ -0,0 +1,37 @@
+import type { StatusTone } from "../../components/StatusPill";
+import type { RemoteClientConnectionState } from "../../lib/connection";
+
+export function connectionTone(state: RemoteClientConnectionState): StatusTone {
+ switch (state) {
+ case "ready":
+ return {
+ label: "Connected",
+ pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16",
+ textClassName: "text-emerald-700 dark:text-emerald-300",
+ };
+ case "reconnecting":
+ return {
+ label: "Reconnecting",
+ pillClassName: "bg-amber-500/12 dark:bg-amber-500/16",
+ textClassName: "text-amber-700 dark:text-amber-300",
+ };
+ case "connecting":
+ return {
+ label: "Connecting",
+ pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
+ textClassName: "text-sky-700 dark:text-sky-300",
+ };
+ case "disconnected":
+ return {
+ label: "Disconnected",
+ pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
+ textClassName: "text-rose-700 dark:text-rose-300",
+ };
+ case "idle":
+ return {
+ label: "Idle",
+ pillClassName: "bg-neutral-500/10 dark:bg-neutral-500/16",
+ textClassName: "text-neutral-600 dark:text-neutral-300",
+ };
+ }
+}
diff --git a/apps/mobile/src/features/connection/pairing.test.ts b/apps/mobile/src/features/connection/pairing.test.ts
new file mode 100644
index 0000000000..d1b45f03ac
--- /dev/null
+++ b/apps/mobile/src/features/connection/pairing.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+
+import { extractPairingUrlFromQrPayload } from "./pairing";
+
+describe("extractPairingUrlFromQrPayload", () => {
+ it("trims raw pairing urls from qr payloads", () => {
+ expect(
+ extractPairingUrlFromQrPayload(" https://remote.example.com/pair#token=pairing-token "),
+ ).toBe("https://remote.example.com/pair#token=pairing-token");
+ });
+
+ it("unwraps mobile deep links that carry an encoded pairing url", () => {
+ expect(
+ extractPairingUrlFromQrPayload(
+ "t3code://pair?pairingUrl=https%3A%2F%2Fremote.example.com%2Fpair%23token%3Dpairing-token",
+ ),
+ ).toBe("https://remote.example.com/pair#token=pairing-token");
+ });
+
+ it("rejects empty qr payloads", () => {
+ expect(() => extractPairingUrlFromQrPayload(" ")).toThrow(
+ "Scanned QR code did not contain a pairing URL.",
+ );
+ });
+});
diff --git a/apps/mobile/src/features/connection/pairing.ts b/apps/mobile/src/features/connection/pairing.ts
new file mode 100644
index 0000000000..2b4fa273d8
--- /dev/null
+++ b/apps/mobile/src/features/connection/pairing.ts
@@ -0,0 +1,57 @@
+const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
+
+export function buildPairingUrl(host: string, code: string): string {
+ const h = host.trim();
+ const c = code.trim();
+ if (!h) return "";
+ if (!c) return h;
+
+ try {
+ const url = new URL(h.includes("://") ? h : `https://${h}`);
+ url.hash = new URLSearchParams([["token", c]]).toString();
+ return url.toString();
+ } catch {
+ return `${h}#token=${c}`;
+ }
+}
+
+export function parsePairingUrl(url: string): { host: string; code: string } {
+ const trimmed = url.trim();
+ if (!trimmed) return { host: "", code: "" };
+
+ try {
+ const parsed = new URL(trimmed);
+ const hashParams = new URLSearchParams(parsed.hash.slice(1));
+ const hashToken = hashParams.get("token");
+ const queryToken = parsed.searchParams.get("token");
+ const code = hashToken || queryToken || "";
+
+ parsed.hash = "";
+ parsed.search = "";
+ parsed.pathname = "/";
+ return { host: parsed.toString().replace(/\/$/, ""), code };
+ } catch {
+ return { host: trimmed, code: "" };
+ }
+}
+
+export function extractPairingUrlFromQrPayload(payload: string): string {
+ const trimmed = payload.trim();
+ if (!trimmed) {
+ throw new Error("Scanned QR code did not contain a pairing URL.");
+ }
+
+ try {
+ const url = new URL(trimmed);
+ if (url.protocol === "t3code:") {
+ const pairingUrl = url.searchParams.get(MOBILE_PAIRING_URL_PARAM)?.trim() ?? "";
+ if (pairingUrl.length > 0) {
+ return pairingUrl;
+ }
+ }
+ } catch {
+ // Treat non-URL payloads as raw pairing-url text so the normal input validation can decide.
+ }
+
+ return trimmed;
+}
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
new file mode 100644
index 0000000000..e333293431
--- /dev/null
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -0,0 +1,346 @@
+import type {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+ GitStatusState,
+} from "@t3tools/client-runtime";
+import { SymbolView } from "expo-symbols";
+import { useCallback, useMemo, useState } from "react";
+import { Pressable, ScrollView, View } from "react-native";
+import { useThemeColor } from "../../lib/useThemeColor";
+
+import { AppText as Text } from "../../components/AppText";
+import { EmptyState } from "../../components/EmptyState";
+import { ProjectFavicon } from "../../components/ProjectFavicon";
+import type { SavedRemoteConnection } from "../../lib/connection";
+import { scopedProjectKey } from "../../lib/scopedEntities";
+import { relativeTime } from "../../lib/time";
+import { useGitStatus } from "../../state/use-git-status";
+import { threadStatusTone } from "../threads/threadPresentation";
+
+/* ─── Types ──────────────────────────────────────────────────────────── */
+
+interface HomeScreenProps {
+ readonly projects: ReadonlyArray;
+ readonly threads: ReadonlyArray;
+ readonly savedConnectionsById: Readonly>;
+ readonly searchQuery: string;
+ readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
+}
+
+interface ProjectGroup {
+ readonly key: string;
+ readonly project: EnvironmentScopedProjectShell;
+ readonly threads: ReadonlyArray;
+}
+
+/* ─── Status indicator colors ────────────────────────────────────────── */
+
+function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: string } {
+ switch (thread.session?.status) {
+ case "running":
+ return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
+ case "ready":
+ return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
+ case "starting":
+ return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
+ case "error":
+ return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
+ default:
+ return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
+ }
+}
+
+const COLLAPSED_THREAD_LIMIT = 6;
+
+/* ─── Project group header ───────────────────────────────────────────── */
+
+function ProjectGroupLabel(props: {
+ readonly project: EnvironmentScopedProjectShell;
+ readonly totalThreadCount: number;
+ readonly httpBaseUrl: string | null;
+ readonly bearerToken: string | null;
+ readonly isExpanded: boolean;
+ readonly onToggleExpand: () => void;
+}) {
+ const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
+
+ return (
+
+
+
+ {props.project.title}
+
+
+ {hiddenCount > 0 ? (
+
+
+ {props.isExpanded ? "Show less" : `${hiddenCount} more`}
+
+
+ ) : null}
+
+ );
+}
+
+/* ─── Git summary line ──────────────────────────────────────────────── */
+
+function gitSummaryParts(gitStatus: GitStatusState): ReadonlyArray {
+ if (!gitStatus.data) return [];
+ const { data } = gitStatus;
+ const parts: string[] = [];
+ if (data.hasWorkingTreeChanges) {
+ parts.push(`${data.workingTree.files.length} changed`);
+ }
+ if (data.aheadCount > 0) parts.push(`${data.aheadCount} ahead`);
+ if (data.behindCount > 0) parts.push(`${data.behindCount} behind`);
+ if (data.pr?.state === "open") parts.push(`PR #${data.pr.number}`);
+ return parts;
+}
+
+/* ─── Thread row ─────────────────────────────────────────────────────── */
+
+function ThreadRow(props: {
+ readonly thread: EnvironmentScopedThreadShell;
+ readonly projectCwd: string | null;
+ readonly onPress: () => void;
+ readonly isLast: boolean;
+}) {
+ const separatorColor = useThemeColor("--color-separator");
+ const { bg, fg } = statusColors(props.thread);
+ const tone = threadStatusTone(props.thread);
+ const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
+ const branch = props.thread.branch;
+
+ // Subscribe to live git status — only when thread has a branch set.
+ // Threads sharing the same cwd share one WS subscription via ref-counting.
+ const cwd = branch ? (props.thread.worktreePath ?? props.projectCwd) : null;
+ const gitStatus = useGitStatus({
+ environmentId: cwd ? props.thread.environmentId : null,
+ cwd,
+ });
+ const gitParts = gitSummaryParts(gitStatus);
+
+ return (
+ ({ opacity: pressed ? 0.7 : 1 })}>
+
+ {/* Git status indicator */}
+
+
+
+
+ {/* Content */}
+
+ {/* Title + Status + Timestamp */}
+
+
+ {props.thread.title}
+
+
+
+
+ {tone.label}
+
+
+
+ {timestamp}
+
+
+
+
+ {/* Branch + git info */}
+ {branch ? (
+
+
+
+ {branch}
+
+ {gitParts.length > 0 ? (
+
+ {" · " + gitParts.join(" · ")}
+
+ ) : null}
+
+ ) : null}
+
+
+
+ );
+}
+
+/* ─── Main screen ────────────────────────────────────────────────────── */
+
+export function HomeScreen(props: HomeScreenProps) {
+ const [expandedProjects, setExpandedProjects] = useState>(() => new Set());
+
+ const toggleExpanded = useCallback((key: string) => {
+ setExpandedProjects((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ }, []);
+
+ /* Build project title lookup for search */
+ const projectTitleByKey = useMemo(() => {
+ const map = new Map();
+ for (const p of props.projects) {
+ map.set(scopedProjectKey(p.environmentId, p.id), p.title);
+ }
+ return map;
+ }, [props.projects]);
+
+ /* Filter threads by search query */
+ const filteredThreads = useMemo(() => {
+ const q = props.searchQuery.trim().toLowerCase();
+ if (!q) return props.threads;
+ return props.threads.filter((t) => {
+ if (t.title.toLowerCase().includes(q)) return true;
+ const key = scopedProjectKey(t.environmentId, t.projectId);
+ return projectTitleByKey.get(key)?.toLowerCase().includes(q) ?? false;
+ });
+ }, [props.threads, props.searchQuery, projectTitleByKey]);
+
+ /* Group filtered threads by project */
+ const projectGroups = useMemo>(() => {
+ const byProject = new Map();
+ for (const thread of filteredThreads) {
+ const key = scopedProjectKey(thread.environmentId, thread.projectId);
+ const existing = byProject.get(key);
+ if (existing) existing.push(thread);
+ else byProject.set(key, [thread]);
+ }
+
+ const groups: ProjectGroup[] = [];
+ for (const project of props.projects) {
+ const key = scopedProjectKey(project.environmentId, project.id);
+ const threads = byProject.get(key);
+ if (threads && threads.length > 0) {
+ groups.push({ key, project, threads });
+ }
+ }
+
+ groups.sort((a, b) => {
+ const aTime = new Date(a.threads[0]!.updatedAt ?? a.threads[0]!.createdAt).getTime();
+ const bTime = new Date(b.threads[0]!.updatedAt ?? b.threads[0]!.createdAt).getTime();
+ return bTime - aTime;
+ });
+
+ return groups;
+ }, [props.projects, filteredThreads]);
+
+ /* Empty states */
+ const hasAnyThreads = props.threads.length > 0;
+ const hasResults = filteredThreads.length > 0;
+
+ return (
+
+ {!hasAnyThreads ? (
+
+ ) : !hasResults ? (
+
+ ) : (
+ projectGroups.map((group) => {
+ const connection = props.savedConnectionsById[group.project.environmentId];
+ const isExpanded = expandedProjects.has(group.key);
+ const visibleThreads = isExpanded
+ ? group.threads
+ : group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
+
+ return (
+
+ toggleExpanded(group.key)}
+ />
+
+ {visibleThreads.map((thread, i) => (
+ props.onSelectThread(thread)}
+ isLast={i === visibleThreads.length - 1}
+ />
+ ))}
+
+
+ );
+ })
+ )}
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx
new file mode 100644
index 0000000000..08746eb74e
--- /dev/null
+++ b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx
@@ -0,0 +1,211 @@
+import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
+import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger";
+import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts";
+import { SymbolView } from "expo-symbols";
+import { memo } from "react";
+import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native";
+
+import { AppText as Text } from "../../components/AppText";
+
+export type ComposerCommandItem =
+ | {
+ readonly id: string;
+ readonly type: "path";
+ readonly path: string;
+ readonly kind: "file" | "directory";
+ readonly label: string;
+ readonly description: string;
+ }
+ | {
+ readonly id: string;
+ readonly type: "slash-command";
+ readonly command: string;
+ readonly label: string;
+ readonly description: string;
+ }
+ | {
+ readonly id: string;
+ readonly type: "provider-slash-command";
+ readonly command: ServerProviderSlashCommand;
+ readonly label: string;
+ readonly description: string;
+ }
+ | {
+ readonly id: string;
+ readonly type: "skill";
+ readonly skill: ServerProviderSkill;
+ readonly label: string;
+ readonly description: string;
+ };
+
+interface ComposerCommandPopoverProps {
+ readonly items: ReadonlyArray;
+ readonly triggerKind: ComposerTriggerKind | null;
+ readonly isLoading: boolean;
+ readonly onSelect: (item: ComposerCommandItem) => void;
+}
+
+function PopoverSurface(props: {
+ readonly children: React.ReactNode;
+ readonly isDarkMode: boolean;
+ readonly style?: ViewStyle;
+}) {
+ const baseStyle: ViewStyle = {
+ borderRadius: 16,
+ overflow: "hidden",
+ ...props.style,
+ };
+
+ if (isLiquidGlassSupported) {
+ return (
+
+ {props.children}
+
+ );
+ }
+
+ return (
+
+ {props.children}
+
+ );
+}
+
+function itemIcon(item: ComposerCommandItem) {
+ switch (item.type) {
+ case "path":
+ return item.kind === "directory" ? ("folder" as const) : ("doc" as const);
+ case "slash-command":
+ case "provider-slash-command":
+ return "terminal" as const;
+ case "skill":
+ return "cube" as const;
+ }
+}
+
+function groupLabel(triggerKind: ComposerTriggerKind | null): string | null {
+ switch (triggerKind) {
+ case "slash-command":
+ return "Commands";
+ case "skill":
+ return "Skills";
+ case "path":
+ return "Files";
+ default:
+ return null;
+ }
+}
+
+function emptyText(triggerKind: ComposerTriggerKind | null, isLoading: boolean): string {
+ if (isLoading) {
+ return triggerKind === "path" ? "Searching files…" : "Loading…";
+ }
+ switch (triggerKind) {
+ case "path":
+ return "No matching files or folders.";
+ case "skill":
+ return "No skills found.";
+ case "slash-command":
+ return "No matching commands.";
+ default:
+ return "No results.";
+ }
+}
+
+const CommandRow = memo(function CommandRow(props: {
+ readonly item: ComposerCommandItem;
+ readonly onPress: () => void;
+ readonly isLast: boolean;
+}) {
+ const iconName = itemIcon(props.item);
+ const iconColor = "#a1a1aa";
+
+ return (
+ ({
+ flexDirection: "row",
+ alignItems: "center",
+ paddingHorizontal: 14,
+ paddingVertical: 10,
+ gap: 10,
+ opacity: pressed ? 0.6 : 1,
+ borderBottomWidth: props.isLast ? 0 : 0.5,
+ borderBottomColor: "rgba(255,255,255,0.1)",
+ })}
+ >
+
+
+ {props.item.label}
+
+ {props.item.description ? (
+
+ {props.item.description}
+
+ ) : null}
+
+ );
+});
+
+export const ComposerCommandPopover = memo(function ComposerCommandPopover(
+ props: ComposerCommandPopoverProps,
+) {
+ const isDarkMode = useColorScheme() === "dark";
+ const label = groupLabel(props.triggerKind);
+
+ return (
+
+ {label ? (
+
+
+ {label}
+
+
+ ) : null}
+ {props.items.length > 0 ? (
+
+ {props.items.map((item, index) => (
+ props.onSelect(item)}
+ isLast={index === props.items.length - 1}
+ />
+ ))}
+
+ ) : (
+
+
+ {emptyText(props.triggerKind, props.isLoading)}
+
+
+ )}
+
+ );
+});
diff --git a/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx b/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx
new file mode 100644
index 0000000000..30c1531a29
--- /dev/null
+++ b/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx
@@ -0,0 +1,121 @@
+import * as Haptics from "expo-haptics";
+import { SymbolView } from "expo-symbols";
+import { useCallback, useEffect, useRef } from "react";
+import { ActivityIndicator, Linking, Pressable, View } from "react-native";
+import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { AppText as Text } from "../../components/AppText";
+import { useThemeColor } from "../../lib/useThemeColor";
+import type { GitActionProgress } from "../../state/use-git-action-state";
+
+export function GitActionProgressOverlay(props: {
+ readonly progress: GitActionProgress;
+ readonly onDismiss: () => void;
+}) {
+ const { progress, onDismiss } = props;
+ const insets = useSafeAreaInsets();
+ const prevPhaseRef = useRef(progress.phase);
+
+ useEffect(() => {
+ const prev = prevPhaseRef.current;
+ prevPhaseRef.current = progress.phase;
+
+ if (prev === "running" && progress.phase === "success") {
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
+ } else if (prev === "running" && progress.phase === "error") {
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
+ }
+ }, [progress.phase]);
+
+ const handlePress = useCallback(() => {
+ if (progress.prUrl) {
+ void Linking.openURL(progress.prUrl);
+ return;
+ }
+ if (progress.phase === "success" || progress.phase === "error") {
+ onDismiss();
+ }
+ }, [onDismiss, progress.phase, progress.prUrl]);
+
+ if (progress.phase === "idle") {
+ return null;
+ }
+
+ return (
+
+
+
+
+
+ );
+}
+
+function OverlayContent(props: { readonly progress: GitActionProgress }) {
+ const { progress } = props;
+ const iconColor = useThemeColor("--color-icon");
+
+ const bgClass =
+ progress.phase === "error"
+ ? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800"
+ : "bg-card border-border";
+
+ return (
+
+
+
+
+ {progress.label ? (
+
+ {progress.label}
+
+ ) : null}
+ {progress.description ? (
+
+ {progress.description}
+
+ ) : null}
+
+
+ {progress.prUrl ? (
+
+ ) : null}
+
+ );
+}
+
+function OverlayIcon(props: {
+ readonly phase: GitActionProgress["phase"];
+ readonly iconColor: ReturnType;
+}) {
+ switch (props.phase) {
+ case "running":
+ return ;
+ case "success":
+ return (
+
+
+
+ );
+ case "error":
+ return (
+
+
+
+ );
+ default:
+ return null;
+ }
+}
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
new file mode 100644
index 0000000000..21f9daa4d1
--- /dev/null
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -0,0 +1,514 @@
+import { MenuView } from "@react-native-menu/menu";
+import { useRouter } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { TextInputWrapper } from "expo-paste-input";
+import { useCallback, useEffect, useMemo } from "react";
+import { Pressable, View, useColorScheme } from "react-native";
+import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useThemeColor } from "../../lib/useThemeColor";
+
+import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
+import { CLAUDE_CODE_EFFORT_OPTIONS } from "@t3tools/contracts";
+
+import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
+import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
+import { ControlPill } from "../../components/ControlPill";
+import { ProviderIcon } from "../../components/ProviderIcon";
+
+import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
+import { buildThreadRoutePath } from "../../lib/routes";
+import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import { useNativePaste } from "../../hooks/useNativePaste";
+import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
+import { useProjectActions } from "./use-project-actions";
+
+export function NewTaskDraftScreen(props: {
+ readonly initialProjectRef?: {
+ readonly environmentId?: string;
+ readonly projectId?: string;
+ };
+}) {
+ const { projects } = useRemoteCatalog();
+ const { onCreateThreadWithOptions } = useProjectActions();
+ const flow = useNewTaskFlow();
+ const router = useRouter();
+ const insets = useSafeAreaInsets();
+ const isDarkMode = useColorScheme() === "dark";
+ const keyboard = useAnimatedKeyboard();
+ const containerAnimatedStyle = useAnimatedStyle(() => ({
+ paddingBottom: keyboard.height.value,
+ }));
+ const controlsBottomPadding = useAnimatedStyle(() => ({
+ paddingBottom: keyboard.height.value > 0 ? 4 : Math.max(insets.bottom, 10),
+ }));
+ const { logicalProjects, selectedProject, setProject } = flow;
+
+ const iconColor = useThemeColor("--color-icon");
+ const borderColor = useThemeColor("--color-border");
+
+ useEffect(() => {
+ if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
+ const directProject =
+ projects.find(
+ (project) =>
+ project.environmentId === props.initialProjectRef?.environmentId &&
+ project.id === props.initialProjectRef?.projectId,
+ ) ?? null;
+
+ if (directProject) {
+ setProject(directProject);
+ return;
+ }
+ }
+
+ if (selectedProject) {
+ return;
+ }
+
+ if (logicalProjects.length === 1) {
+ setProject(logicalProjects[0]!.project);
+ return;
+ }
+
+ router.replace("/new");
+ }, [
+ logicalProjects,
+ projects,
+ props.initialProjectRef?.environmentId,
+ props.initialProjectRef?.projectId,
+ router,
+ selectedProject,
+ setProject,
+ ]);
+
+ useEffect(() => {
+ if (!selectedProject) {
+ return;
+ }
+ void flow.loadBranches();
+ }, [flow, selectedProject]);
+
+ const environmentMenuActions = useMemo(
+ () =>
+ flow.environments.map((environment) => ({
+ id: `environment:${environment.environmentId}`,
+ title: environment.environmentLabel,
+ state:
+ flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
+ })),
+ [flow.environments, flow.selectedEnvironmentId],
+ );
+
+ const modelMenuActions = useMemo(
+ () =>
+ flow.providerGroups.map((group) => ({
+ id: `provider:${group.providerKey}`,
+ title: group.providerLabel,
+ subtitle: group.models.find(
+ (model) =>
+ flow.selectedModel &&
+ model.selection.provider === flow.selectedModel.provider &&
+ model.selection.model === flow.selectedModel.model,
+ )?.label,
+ subactions: group.models.map((option) => ({
+ id: `model:${option.key}`,
+ title: option.label,
+ state:
+ flow.selectedModel &&
+ option.selection.provider === flow.selectedModel.provider &&
+ option.selection.model === flow.selectedModel.model
+ ? ("on" as const)
+ : undefined,
+ })),
+ })),
+ [flow.providerGroups, flow.selectedModel],
+ );
+
+ const optionsMenuActions = useMemo(
+ () => [
+ {
+ id: "options-effort",
+ title: "Effort",
+ subtitle: `${flow.effort.charAt(0).toUpperCase()}${flow.effort.slice(1)}`,
+ subactions: CLAUDE_CODE_EFFORT_OPTIONS.map((level) => ({
+ id: `options:effort:${level}`,
+ title: `${level}${level === "high" ? " (default)" : ""}`,
+ state: flow.effort === level ? ("on" as const) : undefined,
+ })),
+ },
+ {
+ id: "options-fast-mode",
+ title: "Fast Mode",
+ subtitle: flow.fastMode ? "On" : "Off",
+ subactions: ([false, true] as const).map((value) => ({
+ id: `options:fast-mode:${value ? "on" : "off"}`,
+ title: value ? "On" : "Off",
+ state: flow.fastMode === value ? ("on" as const) : undefined,
+ })),
+ },
+ {
+ id: "options-context-window",
+ title: "Context Window",
+ subtitle: flow.contextWindow,
+ subactions: (["200k", "1M"] as const).map((value) => ({
+ id: `options:context-window:${value}`,
+ title: `${value}${value === "1M" ? " (default)" : ""}`,
+ state: flow.contextWindow === value ? ("on" as const) : undefined,
+ })),
+ },
+ {
+ id: "options-runtime",
+ title: "Runtime",
+ subtitle:
+ flow.runtimeMode === "approval-required"
+ ? "Approve actions"
+ : flow.runtimeMode === "auto-accept-edits"
+ ? "Auto-accept edits"
+ : "Full access",
+ subactions: [
+ { id: "options:runtime:approval-required", title: "Approve actions" },
+ { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
+ { id: "options:runtime:full-access", title: "Full access" },
+ ].map((option) => {
+ const value = option.id.replace("options:runtime:", "");
+ return {
+ id: option.id,
+ title: option.title,
+ state: flow.runtimeMode === value ? ("on" as const) : undefined,
+ };
+ }),
+ },
+ {
+ id: "options-interaction",
+ title: "Interaction",
+ subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
+ subactions: [
+ { id: "options:interaction:default", title: "Default" },
+ { id: "options:interaction:plan", title: "Plan" },
+ ].map((option) => {
+ const value = option.id.replace("options:interaction:", "");
+ return {
+ id: option.id,
+ title: option.title,
+ state: flow.interactionMode === value ? ("on" as const) : undefined,
+ };
+ }),
+ },
+ ],
+ [flow.contextWindow, flow.effort, flow.fastMode, flow.interactionMode, flow.runtimeMode],
+ );
+
+ const workspaceMenuActions = useMemo(() => {
+ const branchActions =
+ flow.availableBranches.length === 0
+ ? [
+ {
+ id: "workspace:branch:none",
+ title: flow.branchesLoading ? "Loading branches…" : "No branches available",
+ attributes: { disabled: true },
+ },
+ ]
+ : flow.availableBranches.slice(0, 12).map((branch) => {
+ const badge = branchBadgeLabel({
+ branch,
+ project: flow.selectedProject,
+ });
+
+ return {
+ id: `workspace:branch:${branch.name}`,
+ title: branch.name,
+ subtitle: badge ? badge.toUpperCase() : undefined,
+ state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,
+ };
+ });
+
+ return [
+ {
+ id: "workspace:mode",
+ title: "Mode",
+ subtitle: flow.workspaceMode === "local" ? "Local" : "Worktree",
+ subactions: (["local", "worktree"] as const).map((value) => ({
+ id: `workspace:mode:${value}`,
+ title: value === "local" ? "Local" : "Worktree",
+ state: flow.workspaceMode === value ? ("on" as const) : undefined,
+ })),
+ },
+ {
+ id: "workspace:branch",
+ title: "Branch",
+ subtitle: flow.selectedBranchName ?? "Choose branch",
+ subactions: branchActions,
+ },
+ ];
+ }, [
+ flow.availableBranches,
+ flow.branchesLoading,
+ flow.selectedBranchName,
+ flow.selectedProject,
+ flow.workspaceMode,
+ ]);
+
+ function handleModelMenuAction(event: string) {
+ if (!event.startsWith("model:")) {
+ return;
+ }
+ // Defer state update so the native menu dismiss animation completes
+ // before re-rendering the menu actions (prevents submenu jump).
+ setTimeout(() => {
+ flow.setSelectedModelKey(event.slice("model:".length));
+ }, 150);
+ }
+
+ function handleEnvironmentMenuAction(event: string) {
+ if (!event.startsWith("environment:")) {
+ return;
+ }
+ flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
+ }
+
+ function handleOptionsMenuAction(event: string) {
+ if (event.startsWith("options:effort:")) {
+ flow.setEffort(event.slice("options:effort:".length) as typeof flow.effort);
+ return;
+ }
+ if (event.startsWith("options:fast-mode:")) {
+ flow.setFastMode(event.endsWith(":on"));
+ return;
+ }
+ if (event.startsWith("options:context-window:")) {
+ flow.setContextWindow(event.slice("options:context-window:".length));
+ return;
+ }
+ if (event.startsWith("options:runtime:")) {
+ flow.setRuntimeMode(
+ event.slice("options:runtime:".length) as Parameters[0],
+ );
+ return;
+ }
+ if (event.startsWith("options:interaction:")) {
+ flow.setInteractionMode(
+ event.slice("options:interaction:".length) as Parameters[0],
+ );
+ }
+ }
+
+ function handleWorkspaceMenuAction(event: string) {
+ if (event.startsWith("workspace:mode:")) {
+ flow.setWorkspaceMode(
+ event.slice("workspace:mode:".length) as Parameters[0],
+ );
+ return;
+ }
+ if (event.startsWith("workspace:branch:")) {
+ const branchName = event.slice("workspace:branch:".length);
+ const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
+ if (branch) {
+ flow.selectBranch(branch);
+ }
+ }
+ }
+
+ async function handlePickImages(): Promise {
+ const result = await pickComposerImages({ existingCount: flow.attachments.length });
+ if (result.images.length > 0) {
+ flow.appendAttachments(result.images);
+ }
+ }
+
+ const handleNativePasteImages = useCallback(
+ async (uris: ReadonlyArray) => {
+ try {
+ const images = await convertPastedImagesToAttachments({
+ uris,
+ existingCount: flow.attachments.length,
+ });
+ if (images.length > 0) {
+ flow.appendAttachments(images);
+ }
+ } catch (error) {
+ console.error("[native paste] error converting images", error);
+ }
+ },
+ [flow],
+ );
+
+ const handleNativePaste = useNativePaste((uris) => {
+ void handleNativePasteImages(uris);
+ });
+
+ async function handleStart(): Promise {
+ if (
+ !flow.selectedProject ||
+ !flow.selectedModel ||
+ flow.prompt.trim().length === 0 ||
+ flow.submitting ||
+ (flow.workspaceMode === "worktree" && !flow.selectedBranchName)
+ ) {
+ return;
+ }
+
+ flow.setSubmitting(true);
+ try {
+ const modelWithOptions: ModelSelection =
+ flow.selectedModel.provider === "claudeAgent"
+ ? {
+ ...flow.selectedModel,
+ options: {
+ effort: flow.effort,
+ fastMode: flow.fastMode || undefined,
+ contextWindow: flow.contextWindow,
+ },
+ }
+ : flow.selectedModel.provider === "codex"
+ ? { ...flow.selectedModel, options: { fastMode: flow.fastMode || undefined } }
+ : flow.selectedModel;
+
+ const createdThread = await onCreateThreadWithOptions({
+ project: flow.selectedProject,
+ modelSelection: modelWithOptions,
+ envMode: flow.workspaceMode,
+ branch: flow.selectedBranchName,
+ worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
+ runtimeMode: flow.runtimeMode,
+ interactionMode: flow.interactionMode,
+ initialMessageText: flow.prompt.trim(),
+ initialAttachments: flow.attachments,
+ });
+
+ if (createdThread) {
+ router.replace(buildThreadRoutePath(createdThread));
+ }
+ } finally {
+ flow.setSubmitting(false);
+ }
+ }
+
+ if (!selectedProject) {
+ return (
+
+
+
+
+ New task
+
+ Loading task
+
+
+ );
+ }
+
+ return (
+
+
+
+
+ {flow.logicalProjects.length > 1 ? (
+ router.back()}
+ >
+
+
+ ) : null}
+
+ New task
+
+ {selectedProject.title}
+
+
+
+ void handleNativePaste(payload)}>
+
+
+
+
+
+ {flow.attachments.length > 0 ? (
+
+
+
+ ) : null}
+
+ void handlePickImages()} />
+ handleModelMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+ }
+ />
+
+ handleOptionsMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+
+
+ handleEnvironmentMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+
+
+ handleWorkspaceMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+
+
+ void handleStart()}
+ variant="primary"
+ disabled={
+ !flow.selectedProject ||
+ !flow.selectedModel ||
+ flow.prompt.trim().length === 0 ||
+ flow.submitting ||
+ (flow.workspaceMode === "worktree" && !flow.selectedBranchName)
+ }
+ />
+
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/PendingApprovalCard.tsx b/apps/mobile/src/features/threads/PendingApprovalCard.tsx
new file mode 100644
index 0000000000..eb9e929ed1
--- /dev/null
+++ b/apps/mobile/src/features/threads/PendingApprovalCard.tsx
@@ -0,0 +1,57 @@
+import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
+import { Pressable, View } from "react-native";
+
+import { AppText as Text } from "../../components/AppText";
+import type { PendingApproval } from "../../lib/threadActivity";
+
+export interface PendingApprovalCardProps {
+ readonly approval: PendingApproval;
+ readonly respondingApprovalId: ApprovalRequestId | null;
+ readonly onRespond: (
+ requestId: ApprovalRequestId,
+ decision: ProviderApprovalDecision,
+ ) => Promise;
+}
+
+export function PendingApprovalCard(props: PendingApprovalCardProps) {
+ return (
+
+
+ Approval needed
+
+
+ {props.approval.requestKind}
+
+ {props.approval.detail ? (
+
+ {props.approval.detail}
+
+ ) : null}
+
+ void props.onRespond(props.approval.requestId, "accept")}
+ >
+ Allow once
+
+ void props.onRespond(props.approval.requestId, "acceptForSession")}
+ >
+
+ Allow session
+
+
+ void props.onRespond(props.approval.requestId, "decline")}
+ >
+ Decline
+
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx
new file mode 100644
index 0000000000..af77ff2922
--- /dev/null
+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx
@@ -0,0 +1,101 @@
+import type { ApprovalRequestId } from "@t3tools/contracts";
+import { Pressable, View } from "react-native";
+
+import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
+import { cn } from "../../lib/cn";
+import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
+
+export interface PendingUserInputCardProps {
+ readonly pendingUserInput: PendingUserInput;
+ readonly drafts: Record;
+ readonly answers: Record | null;
+ readonly respondingUserInputId: ApprovalRequestId | null;
+ readonly onSelectOption: (requestId: string, questionId: string, label: string) => void;
+ readonly onChangeCustomAnswer: (
+ requestId: string,
+ questionId: string,
+ customAnswer: string,
+ ) => void;
+ readonly onSubmit: () => Promise;
+}
+
+export function PendingUserInputCard(props: PendingUserInputCardProps) {
+ return (
+
+
+ User input needed
+
+
+ Fill in the pending answers
+
+ {props.pendingUserInput.questions.map((question) => {
+ const draft = props.drafts[question.id];
+ return (
+
+
+ {question.header}
+
+
+ {question.question}
+
+
+ {question.options.map((option) => {
+ const selected =
+ draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
+ return (
+
+ props.onSelectOption(
+ props.pendingUserInput.requestId,
+ question.id,
+ option.label,
+ )
+ }
+ >
+
+ {option.label}
+
+
+ );
+ })}
+
+
+ props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
+ }
+ placeholder="Or type a custom answer"
+ className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-[15px] text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
+ />
+
+ );
+ })}
+ void props.onSubmit()}
+ >
+ Submit answers
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
new file mode 100644
index 0000000000..32c10bcfd7
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -0,0 +1,853 @@
+import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
+import { MenuView } from "@react-native-menu/menu";
+import type {
+ ModelSelection,
+ OrchestrationThread,
+ ProviderInteractionMode,
+ RuntimeMode,
+ ServerConfig as T3ServerConfig,
+} from "@t3tools/contracts";
+import { CLAUDE_CODE_EFFORT_OPTIONS } from "@t3tools/contracts";
+import {
+ detectComposerTrigger,
+ replaceTextRange,
+ type ComposerTrigger,
+} from "@t3tools/shared/composerTrigger";
+import { TextInputWrapper } from "expo-paste-input";
+import type { ReactNode } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ Image,
+ Pressable,
+ TextInput as RNTextInput,
+ useColorScheme,
+ View,
+ type NativeSyntheticEvent,
+ type TextInputSelectionChangeEventData,
+ type ViewStyle,
+} from "react-native";
+import ImageViewing from "react-native-image-viewing";
+import { useThemeColor } from "../../lib/useThemeColor";
+
+import { AppText as Text } from "../../components/AppText";
+import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
+import { ControlPill } from "../../components/ControlPill";
+import { ProviderIcon } from "../../components/ProviderIcon";
+import type { DraftComposerImageAttachment } from "../../lib/composerImages";
+import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
+import type { RemoteClientConnectionState } from "../../lib/connection";
+import { useNativePaste } from "../../hooks/useNativePaste";
+import {
+ insertRankedSearchResult,
+ normalizeSearchQuery,
+ scoreQueryMatch,
+} from "@t3tools/shared/searchRanking";
+import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
+import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
+
+/**
+ * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
+ * Exported so the parent can compute feed overlap / content insets.
+ */
+export const COMPOSER_COLLAPSED_CHROME = 68;
+
+/**
+ * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
+ * Used by the parent to compute the larger feed bottom inset when the composer is focused.
+ */
+export const COMPOSER_EXPANDED_CHROME = 174;
+
+export interface ThreadComposerProps {
+ readonly draftMessage: string;
+ readonly draftAttachments: ReadonlyArray;
+ readonly placeholder: string;
+ readonly bottomInset?: number;
+ readonly connectionState: RemoteClientConnectionState;
+ readonly selectedThread: OrchestrationThread;
+ readonly serverConfig: T3ServerConfig | null;
+ readonly queueCount: number;
+ readonly activeThreadBusy: boolean;
+ readonly environmentId: string;
+ readonly projectCwd: string | null;
+ readonly onChangeDraftMessage: (value: string) => void;
+ readonly onPickDraftImages: () => Promise;
+ readonly onNativePasteImages: (uris: ReadonlyArray) => Promise;
+ readonly onRemoveDraftImage: (imageId: string) => void;
+ readonly onRefresh: () => Promise;
+ readonly onStopThread: () => Promise;
+ readonly onSendMessage: () => void;
+ readonly onUpdateModelSelection: (modelSelection: ModelSelection) => Promise;
+ readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => Promise;
+ readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => Promise;
+ readonly onExpandedChange?: (expanded: boolean) => void;
+}
+
+/**
+ * The pill / card container — renders as LiquidGlassView on supported
+ * iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
+ */
+function ComposerSurface(props: {
+ readonly children: ReactNode;
+ readonly style: ViewStyle;
+ readonly isDarkMode: boolean;
+}) {
+ if (isLiquidGlassSupported) {
+ return (
+
+ {props.children}
+
+ );
+ }
+
+ return (
+
+ {props.children}
+
+ );
+}
+
+export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
+ const isDarkMode = useColorScheme() === "dark";
+ const themePlaceholderColor = useThemeColor("--color-placeholder");
+ const placeholderColor = isDarkMode ? "#a1a1aa" : themePlaceholderColor;
+ const foregroundColor = useThemeColor("--color-foreground");
+ const inputRef = useRef(null);
+ const [isFocused, setIsFocused] = useState(false);
+ const wasExpandedBeforePreviewRef = useRef(false);
+ const { onExpandedChange } = props;
+
+ const [previewImageUri, setPreviewImageUri] = useState(null);
+ const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
+ const isExpanded = isFocused;
+ const canSend = props.connectionState === "ready" && hasContent;
+
+ const onPressImage = useCallback(
+ (uri: string) => {
+ wasExpandedBeforePreviewRef.current = isFocused;
+ setPreviewImageUri(uri);
+ },
+ [isFocused],
+ );
+
+ const closePreview = useCallback(() => {
+ setPreviewImageUri(null);
+ if (wasExpandedBeforePreviewRef.current) {
+ setTimeout(() => inputRef.current?.focus(), 100);
+ }
+ }, []);
+
+ useEffect(() => {
+ onExpandedChange?.(isExpanded);
+ }, [isExpanded, onExpandedChange]);
+ const showStopAction =
+ props.selectedThread.session?.status === "running" ||
+ props.selectedThread.session?.status === "starting" ||
+ props.queueCount > 0;
+
+ const sendLabel = props.activeThreadBusy || props.queueCount > 0 ? "Queue" : "Send";
+ const modelProvider = props.selectedThread.modelSelection?.provider ?? null;
+ const currentModelSelection = props.selectedThread.modelSelection;
+ const currentRuntimeMode = props.selectedThread.runtimeMode;
+ const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
+
+ // Extract current model options (effort, fastMode, contextWindow)
+ const currentEffort =
+ currentModelSelection.provider === "claudeAgent"
+ ? (currentModelSelection.options?.effort ?? "high")
+ : "high";
+ const currentFastMode =
+ currentModelSelection.options && "fastMode" in currentModelSelection.options
+ ? (currentModelSelection.options.fastMode ?? false)
+ : false;
+ const currentContextWindow =
+ currentModelSelection.provider === "claudeAgent"
+ ? (currentModelSelection.options?.contextWindow ?? "1M")
+ : "1M";
+
+ const handleNativePaste = useNativePaste((uris) => {
+ void props.onNativePasteImages(uris);
+ });
+
+ // ── Trigger detection ────────────────────────────────────
+ const [cursorPosition, setCursorPosition] = useState(0);
+ const [composerTrigger, setComposerTrigger] = useState(null);
+ const [pathSearchResults, setPathSearchResults] = useState<
+ ReadonlyArray<{ path: string; kind: "file" | "directory" }>
+ >([]);
+ const [pathSearchLoading, setPathSearchLoading] = useState(false);
+ const pathSearchTimerRef = useRef | null>(null);
+
+ const handleSelectionChange = useCallback(
+ (event: NativeSyntheticEvent) => {
+ const { start } = event.nativeEvent.selection;
+ setCursorPosition(start);
+ },
+ [],
+ );
+
+ useEffect(() => {
+ const trigger = detectComposerTrigger(props.draftMessage, cursorPosition);
+ setComposerTrigger(trigger);
+ }, [props.draftMessage, cursorPosition]);
+
+ // ── File search (debounced) ──────────────────────────────
+ useEffect(() => {
+ if (pathSearchTimerRef.current) {
+ clearTimeout(pathSearchTimerRef.current);
+ pathSearchTimerRef.current = null;
+ }
+
+ if (composerTrigger?.kind !== "path" || !composerTrigger.query || !props.projectCwd) {
+ setPathSearchResults([]);
+ setPathSearchLoading(false);
+ return;
+ }
+
+ setPathSearchLoading(true);
+ const query = composerTrigger.query;
+ const cwd = props.projectCwd;
+ const envId = props.environmentId;
+
+ pathSearchTimerRef.current = setTimeout(() => {
+ const client = getEnvironmentClient(envId);
+ if (!client) {
+ setPathSearchLoading(false);
+ return;
+ }
+
+ void client.projects
+ .searchEntries({ cwd, query, limit: 20 })
+ .then((result) => {
+ setPathSearchResults(
+ result.entries.map((entry) => ({
+ path: entry.path,
+ kind: entry.kind === "directory" ? ("directory" as const) : ("file" as const),
+ })),
+ );
+ })
+ .catch(() => {
+ setPathSearchResults([]);
+ })
+ .finally(() => {
+ setPathSearchLoading(false);
+ });
+ }, 200);
+
+ return () => {
+ if (pathSearchTimerRef.current) {
+ clearTimeout(pathSearchTimerRef.current);
+ }
+ };
+ }, [composerTrigger?.kind, composerTrigger?.query, props.projectCwd, props.environmentId]);
+
+ // ── Build menu items ─────────────────────────────────────
+ const selectedProviderStatus = useMemo(() => {
+ if (!props.serverConfig) return null;
+ return (
+ props.serverConfig.providers.find(
+ (p) => p.provider === props.selectedThread.modelSelection.provider,
+ ) ?? null
+ );
+ }, [props.serverConfig, props.selectedThread.modelSelection.provider]);
+
+ const composerMenuItems: ComposerCommandItem[] = useMemo(() => {
+ if (!composerTrigger) return [];
+
+ if (composerTrigger.kind === "slash-command") {
+ const q = composerTrigger.query.toLowerCase();
+ const allBuiltIn = [
+ {
+ id: "cmd:model",
+ type: "slash-command" as const,
+ command: "model",
+ label: "/model",
+ description: "Switch model",
+ },
+ {
+ id: "cmd:plan",
+ type: "slash-command" as const,
+ command: "plan",
+ label: "/plan",
+ description: "Switch to plan mode",
+ },
+ {
+ id: "cmd:default",
+ type: "slash-command" as const,
+ command: "default",
+ label: "/default",
+ description: "Switch to default mode",
+ },
+ ];
+ const builtIn = allBuiltIn.filter((item) => item.command.includes(q));
+
+ const providerCommands: ComposerCommandItem[] = (selectedProviderStatus?.slashCommands ?? [])
+ .filter((cmd) => cmd.name.toLowerCase().includes(q))
+ .map((cmd) => ({
+ id: `pcmd:${cmd.name}`,
+ type: "provider-slash-command" as const,
+ command: cmd,
+ label: `/${cmd.name}`,
+ description: cmd.description ?? "",
+ }));
+
+ return [...builtIn, ...providerCommands];
+ }
+
+ if (composerTrigger.kind === "skill") {
+ const enabledSkills = (selectedProviderStatus?.skills ?? []).filter((s) => s.enabled);
+ const normalizedQuery = normalizeSearchQuery(composerTrigger.query, {
+ trimLeadingPattern: /^\$+/,
+ });
+
+ if (!normalizedQuery) {
+ return enabledSkills.slice(0, 20).map((skill) => ({
+ id: `skill:${skill.name}`,
+ type: "skill" as const,
+ skill,
+ label: skill.displayName ?? skill.name,
+ description: skill.shortDescription ?? skill.description ?? "",
+ }));
+ }
+
+ const ranked: Array<{
+ item: (typeof enabledSkills)[number];
+ score: number;
+ tieBreaker: string;
+ }> = [];
+ for (const skill of enabledSkills) {
+ const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
+ const scores = [
+ scoreQueryMatch({
+ value: skill.name.toLowerCase(),
+ query: normalizedQuery,
+ exactBase: 0,
+ prefixBase: 2,
+ boundaryBase: 4,
+ includesBase: 6,
+ fuzzyBase: 100,
+ boundaryMarkers: ["-", "_", "/"],
+ }),
+ scoreQueryMatch({
+ value: displayLabel,
+ query: normalizedQuery,
+ exactBase: 1,
+ prefixBase: 3,
+ boundaryBase: 5,
+ includesBase: 7,
+ fuzzyBase: 110,
+ }),
+ scoreQueryMatch({
+ value: skill.shortDescription?.toLowerCase() ?? "",
+ query: normalizedQuery,
+ exactBase: 20,
+ prefixBase: 22,
+ boundaryBase: 24,
+ includesBase: 26,
+ }),
+ scoreQueryMatch({
+ value: skill.description?.toLowerCase() ?? "",
+ query: normalizedQuery,
+ exactBase: 30,
+ prefixBase: 32,
+ boundaryBase: 34,
+ includesBase: 36,
+ }),
+ ].filter((s): s is number => s !== null);
+
+ if (scores.length > 0) {
+ insertRankedSearchResult(
+ ranked,
+ {
+ item: skill,
+ score: Math.min(...scores),
+ tieBreaker: `${displayLabel}\u0000${skill.name}`,
+ },
+ 20,
+ );
+ }
+ }
+
+ return ranked.map(({ item: skill }) => ({
+ id: `skill:${skill.name}`,
+ type: "skill" as const,
+ skill,
+ label: skill.displayName ?? skill.name,
+ description: skill.shortDescription ?? skill.description ?? "",
+ }));
+ }
+
+ if (composerTrigger.kind === "path") {
+ return pathSearchResults.map((entry) => {
+ const parts = entry.path.split("/");
+ return {
+ id: `path:${entry.path}`,
+ type: "path" as const,
+ path: entry.path,
+ kind: entry.kind,
+ label: parts[parts.length - 1] ?? entry.path,
+ description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
+ };
+ });
+ }
+
+ return [];
+ }, [composerTrigger, selectedProviderStatus, pathSearchResults]);
+
+ // ── Handle command selection ──────────────────────────────
+ const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
+
+ const handleSend = useCallback(() => {
+ onSendMessage();
+ inputRef.current?.blur();
+ }, [onSendMessage]);
+ const handleCommandSelect = useCallback(
+ (item: ComposerCommandItem) => {
+ if (!composerTrigger) return;
+
+ if (
+ item.type === "slash-command" &&
+ (item.command === "plan" || item.command === "default")
+ ) {
+ const result = replaceTextRange(
+ draftMessage,
+ composerTrigger.rangeStart,
+ composerTrigger.rangeEnd,
+ "",
+ );
+ setCursorPosition(result.cursor);
+ onChangeDraftMessage(result.text);
+ void onUpdateInteractionMode(item.command);
+ return;
+ }
+
+ let replacement = "";
+ if (item.type === "path") {
+ replacement = `@${item.path} `;
+ } else if (item.type === "skill") {
+ replacement = `$${item.skill.name} `;
+ } else if (item.type === "slash-command") {
+ replacement = `/${item.command} `;
+ } else if (item.type === "provider-slash-command") {
+ replacement = `/${item.command.name} `;
+ }
+
+ const result = replaceTextRange(
+ draftMessage,
+ composerTrigger.rangeStart,
+ composerTrigger.rangeEnd,
+ replacement,
+ );
+ setCursorPosition(result.cursor);
+ onChangeDraftMessage(result.text);
+ },
+ [composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode],
+ );
+
+ // ── Model menu ───────────────────────────────────────────
+ const providerGroups = useMemo(() => {
+ const options = buildModelOptions(props.serverConfig, currentModelSelection);
+ return groupByProvider(options);
+ }, [props.serverConfig, currentModelSelection]);
+
+ const modelMenuActions = useMemo(
+ () =>
+ providerGroups.map((group) => ({
+ id: `provider:${group.providerKey}`,
+ title: group.providerLabel,
+ subtitle: group.models.find(
+ (model) =>
+ model.selection.provider === currentModelSelection.provider &&
+ model.selection.model === currentModelSelection.model,
+ )?.label,
+ subactions: group.models.map((option) => ({
+ id: `model:${option.key}`,
+ title: option.label,
+ state:
+ option.selection.provider === currentModelSelection.provider &&
+ option.selection.model === currentModelSelection.model
+ ? ("on" as const)
+ : undefined,
+ })),
+ })),
+ [providerGroups, currentModelSelection],
+ );
+
+ // ── Options menu ─────────────────────────────────────────
+ const optionsMenuActions = useMemo(
+ () => [
+ {
+ id: "options-effort",
+ title: "Effort",
+ subtitle: `${currentEffort.charAt(0).toUpperCase()}${currentEffort.slice(1)}`,
+ subactions: CLAUDE_CODE_EFFORT_OPTIONS.map((level) => ({
+ id: `options:effort:${level}`,
+ title: `${level}${level === "high" ? " (default)" : ""}`,
+ state: currentEffort === level ? ("on" as const) : undefined,
+ })),
+ },
+ {
+ id: "options-fast-mode",
+ title: "Fast Mode",
+ subtitle: currentFastMode ? "On" : "Off",
+ subactions: ([false, true] as const).map((value) => ({
+ id: `options:fast-mode:${value ? "on" : "off"}`,
+ title: value ? "On" : "Off",
+ state: currentFastMode === value ? ("on" as const) : undefined,
+ })),
+ },
+ {
+ id: "options-context-window",
+ title: "Context Window",
+ subtitle: currentContextWindow,
+ subactions: (["200k", "1M"] as const).map((value) => ({
+ id: `options:context-window:${value}`,
+ title: `${value}${value === "1M" ? " (default)" : ""}`,
+ state: currentContextWindow === value ? ("on" as const) : undefined,
+ })),
+ },
+ {
+ id: "options-runtime",
+ title: "Runtime",
+ subtitle:
+ currentRuntimeMode === "approval-required"
+ ? "Approve actions"
+ : currentRuntimeMode === "auto-accept-edits"
+ ? "Auto-accept edits"
+ : "Full access",
+ subactions: [
+ { id: "options:runtime:approval-required", title: "Approve actions" },
+ { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
+ { id: "options:runtime:full-access", title: "Full access" },
+ ].map((option) => {
+ const value = option.id.replace("options:runtime:", "");
+ return {
+ id: option.id,
+ title: option.title,
+ state: currentRuntimeMode === value ? ("on" as const) : undefined,
+ };
+ }),
+ },
+ {
+ id: "options-interaction",
+ title: "Interaction",
+ subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
+ subactions: [
+ { id: "options:interaction:default", title: "Default" },
+ { id: "options:interaction:plan", title: "Plan" },
+ ].map((option) => {
+ const value = option.id.replace("options:interaction:", "");
+ return {
+ id: option.id,
+ title: option.title,
+ state: currentInteractionMode === value ? ("on" as const) : undefined,
+ };
+ }),
+ },
+ ],
+ [
+ currentEffort,
+ currentFastMode,
+ currentContextWindow,
+ currentRuntimeMode,
+ currentInteractionMode,
+ ],
+ );
+
+ // ── Menu handlers ────────────────────────────────────────
+ function handleModelMenuAction(event: string) {
+ if (!event.startsWith("model:")) {
+ return;
+ }
+ const modelKey = event.slice("model:".length);
+ const options = buildModelOptions(props.serverConfig, currentModelSelection);
+ const option = options.find((o) => o.key === modelKey);
+ if (option) {
+ void props.onUpdateModelSelection(option.selection);
+ }
+ }
+
+ function handleOptionsMenuAction(event: string) {
+ if (event.startsWith("options:effort:")) {
+ const effort = event.slice("options:effort:".length);
+ const updated: ModelSelection =
+ currentModelSelection.provider === "claudeAgent"
+ ? {
+ ...currentModelSelection,
+ options: { ...currentModelSelection.options, effort: effort as typeof currentEffort },
+ }
+ : currentModelSelection;
+ void props.onUpdateModelSelection(updated);
+ return;
+ }
+ if (event.startsWith("options:fast-mode:")) {
+ const fastMode = event.endsWith(":on");
+ const updated: ModelSelection = {
+ ...currentModelSelection,
+ options: { ...currentModelSelection.options, fastMode: fastMode || undefined },
+ };
+ void props.onUpdateModelSelection(updated);
+ return;
+ }
+ if (event.startsWith("options:context-window:")) {
+ const contextWindow = event.slice("options:context-window:".length);
+ const updated: ModelSelection =
+ currentModelSelection.provider === "claudeAgent"
+ ? {
+ ...currentModelSelection,
+ options: { ...currentModelSelection.options, contextWindow },
+ }
+ : currentModelSelection;
+ void props.onUpdateModelSelection(updated);
+ return;
+ }
+ if (event.startsWith("options:runtime:")) {
+ const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
+ void props.onUpdateRuntimeMode(runtimeMode);
+ return;
+ }
+ if (event.startsWith("options:interaction:")) {
+ const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
+ void props.onUpdateInteractionMode(interactionMode);
+ }
+ }
+
+ return (
+
+
+ {composerTrigger && composerMenuItems.length > 0 ? (
+
+
+
+ ) : null}
+
+
+ {/* Attachment strip — inside the card, above the text input */}
+ {isExpanded ? (
+ 0 ? 10 : 0 }}>
+
+
+ ) : null}
+
+
+
+ setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ textAlignVertical={isExpanded ? "top" : "center"}
+ style={
+ isExpanded
+ ? {
+ minHeight: 80,
+ maxHeight: 160,
+ paddingHorizontal: 4,
+ paddingVertical: 4,
+ fontSize: 15,
+ lineHeight: 22,
+ color: foregroundColor,
+ fontFamily: "DMSans_400Regular",
+ }
+ : {
+ maxHeight: 36,
+ paddingVertical: 6,
+ fontSize: 15,
+ lineHeight: 20,
+ color: foregroundColor,
+ fontFamily: "DMSans_400Regular",
+ }
+ }
+ />
+
+
+ {!isExpanded && props.draftAttachments.length > 0 ? (
+
+ {props.draftAttachments.slice(0, 3).map((image) => (
+ onPressImage(image.previewUri)}>
+
+
+ ))}
+ {props.draftAttachments.length > 3 ? (
+
+
+ +{props.draftAttachments.length - 3}
+
+
+ ) : null}
+
+ ) : null}
+ {!isExpanded ? (
+ showStopAction ? (
+ void props.onStopThread()}
+ />
+ ) : (
+
+ )
+ ) : null}
+
+
+ {/* Toolbar row — matches draft page layout (expanded only) */}
+ {isExpanded ? (
+
+ void props.onPickDraftImages()} />
+ handleModelMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+ } />
+
+ handleOptionsMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+
+
+ void props.onRefresh()} />
+ {showStopAction ? (
+ void props.onStopThread()}
+ />
+ ) : null}
+
+
+ ) : null}
+
+ {/* Queue count */}
+ {props.queueCount > 0 ? (
+
+ {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
+ automatically.
+
+ ) : null}
+
+
+
+
+ );
+});
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
new file mode 100644
index 0000000000..94e8074c3e
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -0,0 +1,338 @@
+import type {
+ ApprovalRequestId,
+ ModelSelection,
+ OrchestrationThread,
+ ProviderApprovalDecision,
+ ProviderInteractionMode,
+ RuntimeMode,
+ ServerConfig as T3ServerConfig,
+} from "@t3tools/contracts";
+import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
+import * as Haptics from "expo-haptics";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { View, type LayoutChangeEvent } from "react-native";
+import { Gesture, GestureDetector } from "react-native-gesture-handler";
+import { KeyboardStickyView } from "react-native-keyboard-controller";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { runOnJS } from "react-native-reanimated";
+
+import { AppText as Text } from "../../components/AppText";
+import type { StatusTone } from "../../components/StatusPill";
+import type { DraftComposerImageAttachment } from "../../lib/composerImages";
+import type { MobileLayoutVariant } from "../../lib/mobileLayout";
+import type {
+ PendingApproval,
+ PendingUserInput,
+ PendingUserInputDraftAnswer,
+ ThreadFeedEntry,
+} from "../../lib/threadActivity";
+import { PendingApprovalCard } from "./PendingApprovalCard";
+import { PendingUserInputCard } from "./PendingUserInputCard";
+import {
+ COMPOSER_COLLAPSED_CHROME,
+ COMPOSER_EXPANDED_CHROME,
+ ThreadComposer,
+} from "./ThreadComposer";
+import { ThreadFeed } from "./ThreadFeed";
+
+export interface ThreadDetailScreenProps {
+ readonly selectedThread: OrchestrationThread;
+ readonly screenTone: StatusTone;
+ readonly connectionError: string | null;
+ readonly httpBaseUrl: string | null;
+ readonly bearerToken: string | null;
+ readonly selectedThreadFeed: ReadonlyArray;
+ readonly activeWorkStartedAt: string | null;
+ readonly activePendingApproval: PendingApproval | null;
+ readonly respondingApprovalId: ApprovalRequestId | null;
+ readonly activePendingUserInput: PendingUserInput | null;
+ readonly activePendingUserInputDrafts: Record;
+ readonly activePendingUserInputAnswers: Record | null;
+ readonly respondingUserInputId: ApprovalRequestId | null;
+ readonly draftMessage: string;
+ readonly draftAttachments: ReadonlyArray;
+ readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle";
+ readonly activeThreadBusy: boolean;
+ readonly environmentId: string;
+ readonly projectWorkspaceRoot: string | null;
+ readonly selectedThreadQueueCount: number;
+ readonly serverConfig: T3ServerConfig | null;
+ readonly layoutVariant?: MobileLayoutVariant;
+ readonly onOpenDrawer: () => void;
+ readonly onOpenConnectionEditor: () => void;
+ readonly onChangeDraftMessage: (value: string) => void;
+ readonly onPickDraftImages: () => Promise;
+ readonly onNativePasteImages: (uris: ReadonlyArray) => Promise;
+ readonly onRemoveDraftImage: (imageId: string) => void;
+ readonly onRefresh: () => Promise;
+ readonly onStopThread: () => Promise;
+ readonly onSendMessage: () => void;
+ readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise;
+ readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => Promise;
+ readonly onUpdateThreadInteractionMode: (
+ interactionMode: ProviderInteractionMode,
+ ) => Promise;
+ readonly onRespondToApproval: (
+ requestId: ApprovalRequestId,
+ decision: ProviderApprovalDecision,
+ ) => Promise;
+ readonly onSelectUserInputOption: (requestId: string, questionId: string, label: string) => void;
+ readonly onChangeUserInputCustomAnswer: (
+ requestId: string,
+ questionId: string,
+ customAnswer: string,
+ ) => void;
+ readonly onSubmitUserInput: () => Promise;
+ readonly showContent?: boolean;
+}
+
+function latestStreamingAssistantMessage(
+ feed: ReadonlyArray,
+): { readonly id: string; readonly textLength: number } | null {
+ for (let index = feed.length - 1; index >= 0; index -= 1) {
+ const entry = feed[index];
+ if (entry?.type !== "message") {
+ continue;
+ }
+ if (entry.message.role !== "assistant" || !entry.message.streaming) {
+ continue;
+ }
+ return {
+ id: entry.message.id,
+ textLength: entry.message.text.length,
+ };
+ }
+
+ return null;
+}
+
+function useStreamingHaptics(threadId: string, feed: ReadonlyArray) {
+ const lastStreamingAssistantRef = useRef<{
+ readonly id: string;
+ readonly textLength: number;
+ } | null>(null);
+ const lastStreamHapticAtRef = useRef(0);
+ const hydratedRef = useRef(false);
+ const previousThreadIdRef = useRef(threadId);
+
+ useEffect(() => {
+ if (previousThreadIdRef.current !== threadId) {
+ previousThreadIdRef.current = threadId;
+ hydratedRef.current = false;
+ }
+
+ const latestStreamingMessage = latestStreamingAssistantMessage(feed);
+
+ if (!hydratedRef.current) {
+ hydratedRef.current = true;
+ lastStreamingAssistantRef.current = latestStreamingMessage;
+ return;
+ }
+
+ if (!latestStreamingMessage) {
+ lastStreamingAssistantRef.current = null;
+ return;
+ }
+
+ const previousStreamingMessage = lastStreamingAssistantRef.current;
+ lastStreamingAssistantRef.current = latestStreamingMessage;
+
+ const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
+ const textGrew =
+ previousStreamingMessage?.id === latestStreamingMessage.id &&
+ latestStreamingMessage.textLength > previousStreamingMessage.textLength;
+
+ if (!isNewStream && !textGrew) {
+ return;
+ }
+
+ const now = Date.now();
+ if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
+ return;
+ }
+
+ lastStreamHapticAtRef.current = now;
+ void Haptics.selectionAsync();
+ }, [threadId, feed]);
+}
+
+const WORKING_INDICATOR_HEIGHT = 44;
+
+const WorkingDurationPill = memo(function WorkingDurationPill(props: {
+ readonly startedAt: string;
+}) {
+ const [nowMs, setNowMs] = useState(() => Date.now());
+
+ useEffect(() => {
+ const intervalId = setInterval(() => {
+ setNowMs(Date.now());
+ }, 1_000);
+ return () => clearInterval(intervalId);
+ }, [props.startedAt]);
+
+ const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
+
+ return (
+
+
+
+
+
+
+
+
+
+ Working for {durationLabel}
+
+
+
+
+ );
+});
+
+export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
+ const { onOpenDrawer, onRefresh } = props;
+
+ const insets = useSafeAreaInsets();
+ const agentLabel = `${props.selectedThread.modelSelection.provider} agent`;
+ const composerBottomInset = Math.max(insets.bottom, 12);
+ const [composerExpanded, setComposerExpanded] = useState(false);
+ const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
+ const composerOverlapHeight = composerChrome + composerBottomInset;
+ const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
+ const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
+ const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
+ const [refreshing, setRefreshing] = useState(false);
+ const showContent = props.showContent ?? true;
+ const layoutVariant = props.layoutVariant ?? "compact";
+ const isSplitLayout = layoutVariant === "split";
+ useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
+ const feedBottomInset = Math.max(estimatedOverlayHeight, measuredOverlayHeight) + 8;
+
+ const completeDrawerGesture = useCallback(() => {
+ void Haptics.selectionAsync();
+ onOpenDrawer();
+ }, [onOpenDrawer]);
+
+ const handleRefresh = useCallback(async (): Promise => {
+ if (refreshing) {
+ return;
+ }
+
+ setRefreshing(true);
+ try {
+ await onRefresh();
+ } finally {
+ setRefreshing(false);
+ }
+ }, [onRefresh, refreshing]);
+
+ 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],
+ );
+
+ const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
+ const nextHeight = Math.ceil(event.nativeEvent.layout.height);
+ setMeasuredOverlayHeight((current) =>
+ Math.abs(current - nextHeight) > 1 ? nextHeight : current,
+ );
+ }, []);
+
+ return (
+
+
+ {showContent ? (
+
+ ) : (
+
+ )}
+
+ {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
+ {showContent ? (
+
+
+ {props.activeWorkStartedAt ? (
+
+ ) : null}
+
+ {props.activePendingApproval || props.activePendingUserInput ? (
+
+ {props.activePendingApproval ? (
+
+ ) : null}
+ {props.activePendingUserInput ? (
+
+ ) : null}
+
+ ) : null}
+
+
+
+
+ ) : null}
+
+
+ );
+});
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
new file mode 100644
index 0000000000..430480483a
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -0,0 +1,685 @@
+import * as Clipboard from "expo-clipboard";
+import * as Haptics from "expo-haptics";
+import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
+import { type LegendListRef } from "@legendapp/list/react-native";
+import { SymbolView } from "expo-symbols";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ Markdown,
+ type CustomRenderers,
+ type NodeStyleOverrides,
+ type PartialMarkdownTheme,
+} from "react-native-nitro-markdown";
+import {
+ Image,
+ Pressable,
+ ScrollView,
+ Text as NativeText,
+ type ColorValue,
+ View,
+} from "react-native";
+import { TouchableOpacity } from "react-native-gesture-handler";
+import ImageViewing from "react-native-image-viewing";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useThemeColor } from "../../lib/useThemeColor";
+
+import { AppText as Text } from "../../components/AppText";
+import { EmptyState } from "../../components/EmptyState";
+import { cn } from "../../lib/cn";
+import type { MobileLayoutVariant } from "../../lib/mobileLayout";
+import type { ThreadFeedEntry } from "../../lib/threadActivity";
+import { relativeTime } from "../../lib/time";
+import { messageImageUrl } from "./threadPresentation";
+
+export interface ThreadFeedProps {
+ readonly threadId: string;
+ readonly feed: ReadonlyArray;
+ readonly httpBaseUrl: string | null;
+ readonly bearerToken: string | null;
+ readonly agentLabel: string;
+ readonly contentBottomInset?: number;
+ readonly refreshing?: boolean;
+ readonly onRefresh?: () => void;
+ readonly layoutVariant?: MobileLayoutVariant;
+ readonly composerExpanded?: boolean;
+}
+
+function stripShellWrapper(value: string): string {
+ const trimmed = value.trim();
+ const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
+ return (match?.[1] ?? trimmed).trim();
+}
+
+function compactActivityDetail(detail: string | null): string | null {
+ if (!detail) {
+ return null;
+ }
+
+ const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
+ return cleaned.length > 0 ? cleaned : null;
+}
+
+function buildActivityRows(
+ activities: ReadonlyArray<{
+ readonly id: string;
+ readonly createdAt: string;
+ readonly summary: string;
+ readonly detail: string | null;
+ readonly status: string | null;
+ }>,
+) {
+ return activities.map<{
+ id: string;
+ createdAt: string;
+ summary: string;
+ detail: string | null;
+ status: string | null;
+ }>((activity) => ({
+ id: activity.id,
+ createdAt: activity.createdAt,
+ summary: activity.summary,
+ detail: compactActivityDetail(activity.detail),
+ status: activity.status,
+ }));
+}
+
+const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
+
+function toMarkdownThemeColor(value: ColorValue): string {
+ return value as string;
+}
+
+interface MarkdownStyleSets {
+ readonly user: MarkdownStyleSet;
+ readonly assistant: MarkdownStyleSet;
+}
+
+interface MarkdownStyleSet {
+ readonly theme: PartialMarkdownTheme;
+ readonly styles: NodeStyleOverrides;
+ readonly renderers: CustomRenderers;
+}
+
+function useMarkdownStyles(): MarkdownStyleSets {
+ const bodyColor = useThemeColor("--color-md-body");
+ const strongColor = useThemeColor("--color-md-strong");
+ const linkColor = useThemeColor("--color-md-link");
+ const blockquoteBg = useThemeColor("--color-md-blockquote-bg");
+ const blockquoteBorder = useThemeColor("--color-md-blockquote-border");
+ const codeBg = useThemeColor("--color-md-code-bg");
+ const codeText = useThemeColor("--color-md-code-text");
+ const hrColor = useThemeColor("--color-md-hr");
+ const userCodeBg = useThemeColor("--color-md-user-code-bg");
+ const userCodeText = useThemeColor("--color-md-user-code-text");
+ const userFenceBg = useThemeColor("--color-md-user-fence-bg");
+ const userFenceText = useThemeColor("--color-md-user-fence-text");
+
+ return useMemo(() => {
+ const markdownBodyColor = toMarkdownThemeColor(bodyColor);
+ const markdownStrongColor = toMarkdownThemeColor(strongColor);
+ const markdownLinkColor = toMarkdownThemeColor(linkColor);
+ const markdownBlockquoteBg = toMarkdownThemeColor(blockquoteBg);
+ const markdownBlockquoteBorder = toMarkdownThemeColor(blockquoteBorder);
+ const markdownCodeBg = toMarkdownThemeColor(codeBg);
+ const markdownCodeText = toMarkdownThemeColor(codeText);
+ const markdownHrColor = toMarkdownThemeColor(hrColor);
+ const markdownUserCodeBg = toMarkdownThemeColor(userCodeBg);
+ const markdownUserCodeText = toMarkdownThemeColor(userCodeText);
+ const markdownUserFenceBg = toMarkdownThemeColor(userFenceBg);
+ const markdownUserFenceText = toMarkdownThemeColor(userFenceText);
+
+ const baseTheme: PartialMarkdownTheme = {
+ colors: {
+ text: markdownBodyColor,
+ heading: markdownStrongColor,
+ link: markdownLinkColor,
+ blockquote: markdownBlockquoteBorder,
+ border: markdownHrColor,
+ surfaceLight: markdownBlockquoteBg,
+ accent: markdownLinkColor,
+ tableBorder: markdownHrColor,
+ tableHeader: markdownBlockquoteBg,
+ tableHeaderText: markdownStrongColor,
+ tableRowOdd: "transparent",
+ tableRowEven: "transparent",
+ },
+ spacing: {
+ xs: 4,
+ s: 4,
+ m: 8,
+ l: 8,
+ xl: 16,
+ },
+ fontSizes: {
+ s: 13,
+ m: 15,
+ h1: 22,
+ h2: 19,
+ h3: 17,
+ h4: 15,
+ h5: 15,
+ h6: 15,
+ },
+ fontFamilies: {
+ regular: "DMSans_400Regular",
+ heading: "DMSans_700Bold",
+ mono: "ui-monospace",
+ },
+ headingWeight: "700",
+ borderRadius: {
+ s: 4,
+ m: 8,
+ l: 12,
+ },
+ showCodeLanguage: false,
+ };
+
+ const baseStyles: NodeStyleOverrides = {
+ document: { flexShrink: 1 },
+ paragraph: { marginTop: 0, marginBottom: 8 },
+ list: { marginTop: 4, marginBottom: 4 },
+ list_item: { marginTop: 0, marginBottom: 4 },
+ task_list_item: { marginTop: 0, marginBottom: 4 },
+ bold: { fontWeight: "700", color: markdownStrongColor, fontFamily: "DMSans_700Bold" },
+ italic: { fontStyle: "italic" },
+ link: { color: markdownLinkColor, textDecorationLine: "underline" as const },
+ blockquote: {
+ borderLeftWidth: 3,
+ borderLeftColor: markdownBlockquoteBorder,
+ backgroundColor: markdownBlockquoteBg,
+ paddingLeft: 12,
+ paddingVertical: 6,
+ marginLeft: 0,
+ marginVertical: 4,
+ borderRadius: 4,
+ },
+ heading: {
+ fontFamily: "DMSans_700Bold",
+ color: markdownStrongColor,
+ marginTop: 12,
+ marginBottom: 6,
+ },
+ horizontal_rule: {
+ backgroundColor: markdownHrColor,
+ height: 1,
+ marginVertical: 12,
+ },
+ };
+
+ const createCodeRenderers = (
+ inlineBackgroundColor: string,
+ inlineTextColor: string,
+ blockBackgroundColor: string,
+ blockTextColor: string,
+ ): CustomRenderers => ({
+ code_inline: ({ content }) => (
+
+ {content}
+
+ ),
+ code_block: ({ content }) => (
+
+
+
+ {content}
+
+
+
+ ),
+ });
+
+ const userTheme: PartialMarkdownTheme = {
+ ...baseTheme,
+ colors: {
+ ...baseTheme.colors,
+ code: markdownUserCodeText,
+ codeBackground: markdownUserCodeBg,
+ border: markdownUserFenceBg,
+ },
+ };
+ const userStyles: NodeStyleOverrides = {
+ ...baseStyles,
+ paragraph: { marginTop: 0, marginBottom: 0 },
+ };
+
+ const assistantTheme: PartialMarkdownTheme = {
+ ...baseTheme,
+ colors: {
+ ...baseTheme.colors,
+ code: markdownCodeText,
+ codeBackground: markdownCodeBg,
+ border: markdownCodeBg,
+ },
+ };
+ const assistantStyles: NodeStyleOverrides = {
+ ...baseStyles,
+ };
+
+ return {
+ user: {
+ theme: userTheme,
+ styles: userStyles,
+ renderers: createCodeRenderers(
+ markdownUserCodeBg,
+ markdownUserCodeText,
+ markdownUserFenceBg,
+ markdownUserFenceText,
+ ),
+ },
+ assistant: {
+ theme: assistantTheme,
+ styles: assistantStyles,
+ renderers: createCodeRenderers(
+ markdownCodeBg,
+ markdownCodeText,
+ markdownCodeBg,
+ markdownCodeText,
+ ),
+ },
+ };
+ }, [
+ blockquoteBg,
+ blockquoteBorder,
+ bodyColor,
+ codeBg,
+ codeText,
+ hrColor,
+ linkColor,
+ strongColor,
+ userCodeBg,
+ userCodeText,
+ userFenceBg,
+ userFenceText,
+ ]);
+}
+
+function renderFeedEntry(
+ info: { item: ThreadFeedEntry; index: number },
+ props: Pick & {
+ readonly copiedRowId: string | null;
+ readonly expandedWorkGroups: Record;
+ readonly onCopyWorkRow: (rowId: string, value: string) => void;
+ readonly onToggleWorkGroup: (groupId: string) => void;
+ readonly onPressImage: (uri: string, headers?: Record) => void;
+ readonly iconSubtleColor: string | import("react-native").ColorValue;
+ readonly markdownStyles: MarkdownStyleSets;
+ },
+) {
+ const entry = info.item;
+ const { markdownStyles, iconSubtleColor } = props;
+
+ if (entry.type === "message") {
+ const { message } = entry;
+ const isUser = message.role === "user";
+ const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
+ const timestampLabel = `${relativeTime(message.createdAt)}${message.streaming ? " • live" : ""}`;
+ const attachments = message.attachments ?? [];
+
+ if (isUser) {
+ return (
+
+
+ {message.text.trim().length > 0 ? (
+
+ {message.text}
+
+ ) : null}
+ {attachments.map((attachment) => {
+ const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
+ if (!uri) {
+ return null;
+ }
+ const headers = props.bearerToken
+ ? { Authorization: `Bearer ${props.bearerToken}` }
+ : undefined;
+
+ return (
+ props.onPressImage(uri, headers)}
+ >
+
+
+ );
+ })}
+
+
+ {timestampLabel}
+
+
+ );
+ }
+
+ // Skip empty assistant messages (no text, no attachments) — they would
+ // render as an orphaned timestamp and break adjacent activity-group merging.
+ if (message.text.trim().length === 0 && attachments.length === 0) {
+ return null;
+ }
+
+ return (
+
+ {message.text.trim().length > 0 ? (
+
+ {message.text}
+
+ ) : null}
+ {attachments.map((attachment) => {
+ const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
+ if (!uri) {
+ return null;
+ }
+ const headers = props.bearerToken
+ ? { Authorization: `Bearer ${props.bearerToken}` }
+ : undefined;
+
+ return (
+ props.onPressImage(uri, headers)}
+ >
+
+
+ );
+ })}
+
+ {timestampLabel}
+
+
+ );
+ }
+
+ if (entry.type === "queued-message") {
+ return (
+
+
+
+ {entry.queuedMessage.text}
+
+ {entry.queuedMessage.attachments.length > 0 ? (
+
+ {entry.queuedMessage.attachments.length} image
+ {entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
+
+ ) : null}
+
+
+ {entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
+
+
+ );
+ }
+
+ const rows = buildActivityRows(entry.activities);
+ const isExpanded = props.expandedWorkGroups[entry.id] ?? false;
+ const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
+ const visibleRows = hasOverflow && !isExpanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
+ const hiddenCount = rows.length - visibleRows.length;
+ const showHeader = hasOverflow;
+
+ return (
+
+ {showHeader ? (
+
+
+ Tool calls ({rows.length})
+
+ props.onToggleWorkGroup(entry.id)}>
+
+ {isExpanded ? "Show less" : `Show ${hiddenCount} more`}
+
+
+
+ ) : null}
+ {visibleRows.map((row, index) => (
+ 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]",
+ )}
+ >
+
+
+
+
+ {
+ const copyValue = row.detail ?? row.summary;
+ props.onCopyWorkRow(row.id, copyValue);
+ }}
+ style={{
+ fontFamily: "ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, monospace",
+ }}
+ >
+ {row.detail ? `${row.summary} - ${row.detail}` : row.summary}
+
+
+ {props.copiedRowId === row.id ? (
+
+ Copied
+
+ ) : null}
+
+ ))}
+
+ );
+}
+
+const IOS_NAV_BAR_HEIGHT = 44;
+
+export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
+ const listRef = useRef(null);
+ const copyFeedbackTimeoutRef = useRef | null>(null);
+ const [copiedRowId, setCopiedRowId] = useState(null);
+ const [expandedWorkGroups, setExpandedWorkGroups] = useState>({});
+ const [expandedImage, setExpandedImage] = useState<{
+ uri: string;
+ headers?: Record;
+ } | null>(null);
+ const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
+ const insets = useSafeAreaInsets();
+ const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
+
+ const iconSubtleColor = useThemeColor("--color-icon-subtle");
+ const markdownStyles = useMarkdownStyles();
+
+ useEffect(() => {
+ setCopiedRowId(null);
+ setExpandedWorkGroups({});
+ }, [props.threadId]);
+
+ // Scroll to end when the composer expands (keyboard opens) so the latest
+ // message stays visible above the taller composer + keyboard.
+ useEffect(() => {
+ if (props.composerExpanded && props.feed.length > 0) {
+ // Small delay to let KAV + layout settle before scrolling
+ const timer = setTimeout(() => {
+ void listRef.current?.scrollToEnd({ animated: true });
+ }, 100);
+ return () => clearTimeout(timer);
+ }
+ }, [props.composerExpanded, props.feed.length]);
+
+ useEffect(() => {
+ return () => {
+ if (copyFeedbackTimeoutRef.current) {
+ clearTimeout(copyFeedbackTimeoutRef.current);
+ }
+ };
+ }, []);
+
+ const onCopyWorkRow = useCallback((rowId: string, value: string) => {
+ void Clipboard.setStringAsync(value);
+ void Haptics.selectionAsync();
+ setCopiedRowId(rowId);
+ if (copyFeedbackTimeoutRef.current) {
+ clearTimeout(copyFeedbackTimeoutRef.current);
+ }
+ copyFeedbackTimeoutRef.current = setTimeout(() => {
+ setCopiedRowId((current) => (current === rowId ? null : current));
+ copyFeedbackTimeoutRef.current = null;
+ }, 1200);
+ }, []);
+
+ const onToggleWorkGroup = useCallback((groupId: string) => {
+ setExpandedWorkGroups((current) => ({
+ ...current,
+ [groupId]: !(current[groupId] ?? false),
+ }));
+ }, []);
+
+ const onPressImage = useCallback((uri: string, headers?: Record) => {
+ setExpandedImage({ uri, headers });
+ }, []);
+
+ const renderItem = useCallback(
+ (info: { item: ThreadFeedEntry; index: number }) =>
+ renderFeedEntry(info, {
+ bearerToken: props.bearerToken,
+ copiedRowId,
+ httpBaseUrl: props.httpBaseUrl,
+ expandedWorkGroups,
+ onCopyWorkRow,
+ onToggleWorkGroup,
+ onPressImage,
+ iconSubtleColor,
+ markdownStyles,
+ }),
+ [
+ copiedRowId,
+ expandedWorkGroups,
+ iconSubtleColor,
+ markdownStyles,
+ onCopyWorkRow,
+ onPressImage,
+ onToggleWorkGroup,
+ props.bearerToken,
+ props.httpBaseUrl,
+ ],
+ );
+
+ if (props.feed.length === 0) {
+ return (
+
+
+
+ );
+ }
+
+ return (
+ <>
+ `${entry.type}:${entry.id}`}
+ keyboardShouldPersistTaps="handled"
+ estimatedItemSize={80}
+ initialScrollAtEnd
+ maintainScrollAtEnd={{ on: { layout: true, itemLayout: true, dataChange: true } }}
+ maintainScrollAtEndThreshold={0.1}
+ refreshing={props.refreshing ?? false}
+ onRefresh={props.onRefresh}
+ safeAreaInsetBottom={insets.bottom}
+ contentContainerStyle={{
+ paddingTop: 12,
+ paddingHorizontal: horizontalPadding,
+ paddingBottom: props.contentBottomInset ?? 18,
+ }}
+ />
+
+ setExpandedImage(null)}
+ swipeToCloseEnabled
+ doubleTapToZoomEnabled
+ />
+ >
+ );
+});
diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx
new file mode 100644
index 0000000000..77262e8248
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx
@@ -0,0 +1,210 @@
+import type { GitRunStackedActionResult, GitStatusResult } from "@t3tools/contracts";
+import {
+ type GitActionRequestInput,
+ requiresDefaultBranchConfirmation,
+ resolveQuickAction,
+} from "@t3tools/client-runtime";
+import { useLocalSearchParams, useRouter } from "expo-router";
+import Stack from "expo-router/stack";
+import { useCallback, useMemo } from "react";
+import { Alert, Linking } from "react-native";
+import { buildThreadReviewRoutePath } from "../../lib/routes";
+
+function truncateMiddle(value: string, maxLength: number): string {
+ if (value.length <= maxLength) {
+ return value;
+ }
+
+ const headLength = Math.ceil((maxLength - 1) / 2);
+ const tailLength = Math.floor((maxLength - 1) / 2);
+ return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`;
+}
+
+function compactMenuBranchLabel(branch: string): string {
+ return truncateMiddle(branch, 24);
+}
+
+function compactMenuStatus(gitStatus: GitStatusResult | null): string {
+ if (!gitStatus) {
+ return "Checking status";
+ }
+ if (!gitStatus.isRepo) {
+ return "Not a repo";
+ }
+
+ const parts: string[] = [];
+ if (gitStatus.hasWorkingTreeChanges) {
+ parts.push(`${gitStatus.workingTree.files.length} changed`);
+ } else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) {
+ parts.push("Clean");
+ }
+ if (gitStatus.aheadCount > 0) {
+ parts.push(`${gitStatus.aheadCount} ahead`);
+ }
+ if (gitStatus.behindCount > 0) {
+ parts.push(`${gitStatus.behindCount} behind`);
+ }
+ if (gitStatus.pr?.state === "open") {
+ parts.push(`PR #${gitStatus.pr.number}`);
+ }
+
+ return parts.join(" · ");
+}
+
+export function ThreadGitControls(props: {
+ readonly currentBranch: string | null;
+ readonly gitStatus: GitStatusResult | null;
+ readonly gitOperationLabel: string | null;
+ readonly onPull: () => Promise;
+ readonly onRunAction: (input: GitActionRequestInput) => Promise;
+}) {
+ const router = useRouter();
+ const { environmentId, threadId } = useLocalSearchParams<{
+ environmentId: string;
+ threadId: string;
+ }>();
+ const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
+
+ const currentBranchLabel = gitStatus?.branch ?? props.currentBranch ?? "Detached HEAD";
+ const busy = gitOperationLabel !== null;
+ const isRepo = gitStatus?.isRepo ?? true;
+ const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
+ const isDefaultBranch = gitStatus?.isDefaultBranch ?? false;
+
+ const quickAction = useMemo(
+ () =>
+ isRepo
+ ? resolveQuickAction(gitStatus, busy, isDefaultBranch, hasOriginRemote)
+ : {
+ label: "Git unavailable",
+ disabled: true,
+ kind: "show_hint" as const,
+ hint: "This workspace is not a git repository.",
+ },
+ [busy, gitStatus, hasOriginRemote, isDefaultBranch, isRepo],
+ );
+
+ const quickActionHint = quickAction.disabled
+ ? (quickAction.hint ?? "This action is unavailable.")
+ : null;
+
+ const quickActionIcon = (() => {
+ if (quickAction.kind === "run_pull") return "arrow.down.circle";
+ if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
+ if (quickAction.kind === "run_action") {
+ if (quickAction.action === "commit") return "checkmark.circle";
+ if (quickAction.action === "push" || quickAction.action === "commit_push")
+ return "arrow.up.circle";
+ }
+ return "arrow.up.right.circle";
+ })();
+
+ const openExistingPr = useCallback(async () => {
+ const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
+ if (!prUrl) {
+ Alert.alert("No open PR", "This branch does not have an open pull request.");
+ return;
+ }
+ try {
+ await Linking.openURL(prUrl);
+ } catch (error) {
+ Alert.alert(
+ "Unable to open PR",
+ error instanceof Error ? error.message : "An error occurred.",
+ );
+ }
+ }, [gitStatus]);
+
+ const runActionWithPrompt = useCallback(
+ async (input: GitActionRequestInput) => {
+ const confirmableAction =
+ input.action === "push" ||
+ input.action === "create_pr" ||
+ input.action === "commit_push" ||
+ input.action === "commit_push_pr"
+ ? input.action
+ : null;
+ const branchName = gitStatus?.branch;
+ if (
+ branchName &&
+ confirmableAction &&
+ !input.featureBranch &&
+ requiresDefaultBranchConfirmation(input.action, isDefaultBranch)
+ ) {
+ router.push({
+ pathname: "/threads/[environmentId]/[threadId]/git-confirm",
+ params: {
+ environmentId,
+ threadId,
+ confirmAction: confirmableAction,
+ branchName,
+ includesCommit: String(
+ input.action === "commit_push" || input.action === "commit_push_pr",
+ ),
+ },
+ });
+ return;
+ }
+
+ await onRunAction(input);
+ },
+ [environmentId, gitStatus, isDefaultBranch, onRunAction, router, threadId],
+ );
+
+ const runQuickAction = useCallback(async () => {
+ if (quickAction.kind === "open_pr") {
+ await openExistingPr();
+ return;
+ }
+ if (quickAction.kind === "run_pull") {
+ await onPull();
+ return;
+ }
+ if (quickAction.kind === "run_action" && quickAction.action) {
+ await runActionWithPrompt({ action: quickAction.action });
+ }
+ }, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
+
+ return (
+
+
+ {}}
+ subtitle={compactMenuStatus(gitStatus)}
+ >
+ {compactMenuBranchLabel(currentBranchLabel)}
+
+ void runQuickAction()}
+ subtitle={quickActionHint ?? undefined}
+ >
+ {quickAction.label}
+
+ router.push(buildThreadReviewRoutePath({ environmentId, threadId }))}
+ subtitle="Turn diffs and worktree changes"
+ >
+ Review changes
+
+
+ router.push({
+ pathname: "/threads/[environmentId]/[threadId]/git",
+ params: { environmentId, threadId },
+ })
+ }
+ subtitle="Commit, files, branches"
+ >
+ More
+
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx
new file mode 100644
index 0000000000..c6dbcb47a7
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx
@@ -0,0 +1,254 @@
+import { SymbolView } from "expo-symbols";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { 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 { groupProjectsByRepository } from "../../lib/repositoryGroups";
+import { scopedThreadKey } from "../../lib/scopedEntities";
+import { relativeTime } from "../../lib/time";
+import { threadStatusTone } from "./threadPresentation";
+import {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+} from "@t3tools/client-runtime";
+
+function compareThreadActivity(
+ left: EnvironmentScopedThreadShell,
+ right: EnvironmentScopedThreadShell,
+): number {
+ return (
+ new Date(right.updatedAt ?? right.createdAt).getTime() -
+ new Date(left.updatedAt ?? left.createdAt).getTime() || left.title.localeCompare(right.title)
+ );
+}
+
+export function ThreadNavigationDrawer(props: {
+ readonly visible: boolean;
+ readonly projects: ReadonlyArray;
+ readonly threads: ReadonlyArray;
+ readonly selectedThreadKey: string | null;
+ readonly onClose: () => void;
+ readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => 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");
+
+ const repositoryGroups = useMemo(
+ () => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
+ [props.projects, props.threads],
+ );
+ const groupedThreads = useMemo(
+ () =>
+ repositoryGroups.map((group) => ({
+ key: group.key,
+ title: group.projects[0]?.project.title ?? group.title,
+ threads: group.projects
+ .flatMap((projectGroup) => projectGroup.threads)
+ .sort(compareThreadActivity),
+ })),
+ [repositoryGroups],
+ );
+
+ 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 (
+
+
+
+
+
+
+
+
+ Threads
+ {
+ props.onClose();
+ props.onStartNewTask();
+ }}
+ className="h-11 w-11 items-center justify-center rounded-full bg-primary"
+ >
+
+
+
+
+
+ {groupedThreads.map((group) => (
+
+
+ {group.title}
+
+
+
+ {group.threads.length === 0 ? (
+
+
+ No threads yet
+
+
+ ) : (
+ group.threads.map((thread, index) => {
+ const threadKey = scopedThreadKey(thread.environmentId, thread.id);
+ const selected = props.selectedThreadKey === threadKey;
+
+ return (
+ {
+ props.onSelectThread(thread);
+ props.onClose();
+ }}
+ style={{
+ paddingHorizontal: 16,
+ paddingVertical: 15,
+ borderTopWidth: index === 0 ? 0 : 1,
+ borderTopColor: borderSubtleColor,
+ backgroundColor: selected ? undefined : "transparent",
+ }}
+ className={selected ? "bg-subtle" : undefined}
+ >
+
+
+
+ {thread.title}
+
+
+ {relativeTime(thread.updatedAt ?? thread.createdAt)}
+
+
+
+
+
+ );
+ })
+ )}
+
+
+ ))}
+
+
+
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
new file mode 100644
index 0000000000..05c1b73d13
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -0,0 +1,287 @@
+import { Stack, useLocalSearchParams, useRouter } from "expo-router";
+import { useCallback, useMemo, useState } from "react";
+import * as Arr from "effect/Array";
+import * as Option from "effect/Option";
+import { pipe } from "effect/Function";
+import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
+import { useThemeColor } from "../../lib/useThemeColor";
+import { useGitStatus, gitStatusManager } from "../../state/use-git-status";
+import { dismissGitActionResult, useGitActionProgress } from "../../state/use-git-action-state";
+
+import { EmptyState } from "../../components/EmptyState";
+import { LoadingScreen } from "../../components/LoadingScreen";
+import { buildThreadRoutePath } from "../../lib/routes";
+import { scopedThreadKey } from "../../lib/scopedEntities";
+import { connectionTone } from "../connection/connectionTone";
+
+import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import {
+ useRemoteConnectionStatus,
+ useRemoteEnvironmentState,
+} from "../../state/use-remote-environment-registry";
+import { useSelectedThreadDetail } from "../../state/use-thread-detail";
+import { useThreadSelection } from "../../state/use-thread-selection";
+import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
+import { ThreadDetailScreen } from "./ThreadDetailScreen";
+import { ThreadGitControls } from "./ThreadGitControls";
+import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
+import { useSelectedThreadCommands } from "./use-selected-thread-commands";
+import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "./use-selected-thread-git-state";
+import { useThreadComposerState } from "./use-thread-composer-state";
+
+function firstRouteParam(value: string | string[] | undefined): string | null {
+ if (Array.isArray(value)) {
+ return value[0] ?? null;
+ }
+
+ return value ?? null;
+}
+
+export function ThreadRouteScreen() {
+ const { isLoadingSavedConnection, environmentStateById, pendingConnectionError } =
+ useRemoteEnvironmentState();
+ const { connectionState, connectionError: aggregateConnectionError } =
+ useRemoteConnectionStatus();
+ const { projects, threads } = useRemoteCatalog();
+ const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
+ useThreadSelection();
+ const selectedThreadDetail = useSelectedThreadDetail();
+ const composer = useThreadComposerState();
+ const gitState = useSelectedThreadGitState();
+ const gitActions = useSelectedThreadGitActions();
+ const commands = useSelectedThreadCommands({
+ activePendingUserInput: composer.activePendingUserInput,
+ activePendingUserInputAnswers: composer.activePendingUserInputAnswers,
+ refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus,
+ });
+ const refreshSelectedThread = commands.onRefresh;
+ const router = useRouter();
+ const params = useLocalSearchParams<{
+ environmentId?: string | string[];
+ threadId?: string | string[];
+ }>();
+ const [drawerVisible, setDrawerVisible] = useState(false);
+ const environmentId = firstRouteParam(params.environmentId);
+ const threadId = firstRouteParam(params.threadId);
+ const routeEnvironmentRuntime = environmentId
+ ? (environmentStateById[environmentId] ?? null)
+ : null;
+ const routeConnectionState = routeEnvironmentRuntime?.connectionState ?? connectionState;
+ const routeConnectionError =
+ pendingConnectionError ?? routeEnvironmentRuntime?.connectionError ?? aggregateConnectionError;
+
+ /* ─── Native header theming ──────────────────────────────────────── */
+ const isDark = useColorScheme() === "dark";
+ const iconColor = String(useThemeColor("--color-icon"));
+ const foregroundColor = String(useThemeColor("--color-foreground"));
+ const secondaryFg = isDark ? "#a3a3a3" : "#525252";
+
+ /* ─── Git status for native header trigger ───────────────────────── */
+ const gitStatus = useGitStatus({
+ environmentId: selectedThread?.environmentId ?? "",
+ cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
+ });
+
+ /* ─── Git action progress (for overlay banner) ──────────────────── */
+ const gitActionProgressTarget = useMemo(
+ () => ({
+ environmentId: selectedThread?.environmentId ?? null,
+ cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
+ }),
+ [
+ selectedThread?.environmentId,
+ selectedThread?.worktreePath,
+ selectedThreadProject?.workspaceRoot,
+ ],
+ );
+ const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
+
+ const handleRefreshGitStatus = useCallback(async () => {
+ if (!selectedThread) return;
+ await gitStatusManager.refresh({
+ environmentId: selectedThread.environmentId,
+ cwd: selectedThread.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
+ });
+ }, [selectedThread, selectedThreadProject?.workspaceRoot]);
+
+ /** Wraps thread refresh + git status refresh for pull-to-refresh */
+ const handleRefreshAll = useCallback(async () => {
+ await refreshSelectedThread();
+ await handleRefreshGitStatus();
+ }, [handleRefreshGitStatus, refreshSelectedThread]);
+
+ const handleOpenDrawer = useCallback(() => {
+ setDrawerVisible(true);
+ }, []);
+
+ const handleOpenConnectionEditor = useCallback(() => {
+ void router.push("/connections");
+ }, [router]);
+
+ if (!environmentId || !threadId) {
+ return ;
+ }
+
+ if (!selectedThread) {
+ const stillHydrating =
+ isLoadingSavedConnection ||
+ routeConnectionState === "connecting" ||
+ routeConnectionState === "reconnecting";
+
+ if (stillHydrating) {
+ return ;
+ }
+
+ return (
+
+
+
+ );
+ }
+
+ if (!selectedThreadDetail) {
+ return ;
+ }
+
+ const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
+ const serverConfig =
+ routeEnvironmentRuntime?.serverConfig ??
+ pipe(
+ Object.values(environmentStateById),
+ Arr.map((runtime) => runtime.serverConfig),
+ Arr.findFirst((value) => value !== null),
+ Option.getOrNull,
+ );
+
+ const headerSubtitle = [
+ selectedThreadProject?.title ?? null,
+ selectedEnvironmentConnection?.environmentLabel ?? null,
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
+ return (
+ <>
+ (
+ {
+ // TODO: trigger rename modal
+ }}
+ >
+
+ {selectedThreadDetail.title}
+
+
+ {headerSubtitle}
+
+
+ ),
+ }}
+ />
+
+
+
+
+
+
+
+
+ setDrawerVisible(false)}
+ onSelectThread={(thread) => {
+ router.replace(buildThreadRoutePath(thread));
+ }}
+ onStartNewTask={() => router.push("/new")}
+ />
+
+ >
+ );
+}
diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
new file mode 100644
index 0000000000..020e34c36c
--- /dev/null
+++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
@@ -0,0 +1,203 @@
+import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
+import { useRouter } from "expo-router";
+import { useEffect, 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 { useGitStatus } from "../../../state/use-git-status";
+import { useThreadSelection } from "../../../state/use-thread-selection";
+import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
+import { SheetActionButton } from "./gitSheetComponents";
+
+export function GitBranchesSheet() {
+ const router = useRouter();
+ const insets = useSafeAreaInsets();
+ const { selectedThread, selectedThreadProject } = useThreadSelection();
+ 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 = useGitStatus({
+ environmentId: selectedThread?.environmentId ?? "",
+ cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
+ });
+
+ const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD";
+ const currentWorktreePath = selectedThread?.worktreePath ?? null;
+ const availableBranches = gitState.selectedThreadBranches;
+ const branchesLoading = gitState.selectedThreadBranchesLoading;
+ const busy = gitState.gitOperationLabel !== null;
+
+ const [newBranchName, setNewBranchName] = useState("");
+ const [worktreeBaseBranch, setWorktreeBaseBranch] = useState(
+ currentBranchLabel === "Detached HEAD" ? "main" : currentBranchLabel,
+ );
+ const [worktreeBranchName, setWorktreeBranchName] = useState("");
+
+ const disabledExistingBranches = new Set(
+ availableBranches
+ .filter(
+ (branch) => branch.worktreePath !== null && branch.worktreePath !== currentWorktreePath,
+ )
+ .map((branch) => branch.name),
+ );
+
+ useEffect(() => {
+ void gitActions.refreshSelectedThreadBranches();
+ }, [gitActions]);
+
+ return (
+
+
+
+ New branch
+
+
+ {
+ const branch = sanitizeFeatureBranchName(newBranchName.trim());
+ if (branch.length === 0) return;
+ void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
+ setNewBranchName("");
+ router.dismiss();
+ });
+ }}
+ />
+
+
+
+
+ New worktree
+
+
+
+ {
+ const baseBranch = worktreeBaseBranch.trim();
+ const newBranch = worktreeBranchName.trim();
+ if (baseBranch.length === 0 || newBranch.length === 0) return;
+ void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
+ setWorktreeBranchName("");
+ router.dismiss();
+ });
+ }}
+ />
+
+
+
+
+ Existing branches
+
+ {branchesLoading ? (
+
+ Loading branches...
+
+ ) : null}
+ {!branchesLoading && availableBranches.length === 0 ? (
+
+ No local branches found.
+
+ ) : null}
+ {availableBranches.map((branch) => {
+ const disabled = disabledExistingBranches.has(branch.name);
+ const subtitle = branch.worktreePath
+ ? branch.worktreePath === currentWorktreePath
+ ? "Checked out in this thread"
+ : "Checked out in another worktree"
+ : branch.isDefault
+ ? "Default branch"
+ : "Local branch";
+
+ return (
+ {
+ void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
+ router.dismiss();
+ });
+ }}
+ >
+
+ {branch.name}
+ {subtitle}
+
+ );
+ })}
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
new file mode 100644
index 0000000000..fc9195b5af
--- /dev/null
+++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
@@ -0,0 +1,239 @@
+import { useRouter } from "expo-router";
+import { useCallback, useState } from "react";
+import { Pressable, ScrollView, View, useColorScheme } 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 { useGitStatus } from "../../../state/use-git-status";
+import { useThreadSelection } from "../../../state/use-thread-selection";
+import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
+import { SheetActionButton } from "./gitSheetComponents";
+
+export function GitCommitSheet() {
+ const router = useRouter();
+ const insets = useSafeAreaInsets();
+ const isDarkMode = useColorScheme() === "dark";
+ const { selectedThread, selectedThreadProject } = useThreadSelection();
+ 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 = useGitStatus({
+ environmentId: selectedThread?.environmentId ?? "",
+ cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
+ });
+
+ const busy = gitState.gitOperationLabel !== null;
+ const isDefaultBranch = gitStatus.data?.isDefaultBranch ?? false;
+ const allFiles = gitStatus.data?.workingTree?.files ?? [];
+
+ const [dialogCommitMessage, setDialogCommitMessage] = useState("");
+ const [excludedFiles, setExcludedFiles] = useState>(new Set());
+ const [isEditingFiles, setIsEditingFiles] = useState(false);
+
+ const selectedFiles = allFiles.filter((file) => !excludedFiles.has(file.path));
+ const allSelected = excludedFiles.size === 0;
+ const noneSelected = selectedFiles.length === 0;
+ const selectedInsertions = selectedFiles.reduce((sum, file) => sum + file.insertions, 0);
+ const selectedDeletions = selectedFiles.reduce((sum, file) => sum + file.deletions, 0);
+ const selectedFilePreview = selectedFiles.slice(0, 3);
+
+ const runCommitAction = useCallback(
+ async (featureBranch: boolean) => {
+ const commitMessage = dialogCommitMessage.trim();
+ router.dismiss();
+ await gitActions.onRunSelectedThreadGitAction({
+ action: "commit",
+ featureBranch,
+ ...(commitMessage ? { commitMessage } : {}),
+ ...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}),
+ });
+ },
+ [allSelected, dialogCommitMessage, gitActions, router, selectedFiles],
+ );
+
+ return (
+
+
+
+ Branch
+
+ {gitStatus.data?.branch ?? "(detached HEAD)"}
+
+
+ {isDefaultBranch ? (
+
+ Warning: this is the default branch.
+
+ ) : null}
+
+
+
+
+
+ Files
+
+ {selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
+
+
+
+ {!allSelected && isEditingFiles ? (
+ setExcludedFiles(new Set())}
+ >
+ Reset
+
+ ) : null}
+ setIsEditingFiles((current) => !current)}
+ >
+
+ {isEditingFiles ? "Done" : "Edit"}
+
+
+
+
+
+ {allFiles.length === 0 ? (
+
+ No changed files are available to commit.
+
+ ) : !isEditingFiles ? (
+
+ {selectedFilePreview.map((file) => (
+
+
+ {file.path}
+
+
+ +{file.insertions}
+
+
+ -{file.deletions}
+
+
+ ))}
+ {selectedFiles.length > selectedFilePreview.length ? (
+
+ +{selectedFiles.length - selectedFilePreview.length} more files
+
+ ) : null}
+
+ ) : (
+
+ {allFiles.map((file) => {
+ const included = !excludedFiles.has(file.path);
+ return (
+ {
+ setExcludedFiles((current) => {
+ const next = new Set(current);
+ if (next.has(file.path)) {
+ next.delete(file.path);
+ } else {
+ next.add(file.path);
+ }
+ return next;
+ });
+ }}
+ >
+
+
+
+
+ {file.path}
+
+ {!included ? (
+
+ Excluded from this commit
+
+ ) : null}
+
+
+
+ +{file.insertions}
+
+
+ -{file.deletions}
+
+
+
+
+ );
+ })}
+
+ )}
+
+
+
+ Commit message
+
+
+
+
+
+ void runCommitAction(true)}
+ />
+
+
+ void runCommitAction(false)}
+ />
+
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx
new file mode 100644
index 0000000000..f73dc11d66
--- /dev/null
+++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx
@@ -0,0 +1,120 @@
+import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime";
+import { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
+import { useLocalSearchParams, useRouter } from "expo-router";
+import { useCallback, useMemo } from "react";
+import { View } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { AppText as Text } from "../../../components/AppText";
+import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
+import { SheetActionButton } from "./gitSheetComponents";
+
+export function GitConfirmSheet() {
+ const router = useRouter();
+ const insets = useSafeAreaInsets();
+ const gitState = useSelectedThreadGitState();
+ const gitActions = useSelectedThreadGitActions();
+
+ const params = useLocalSearchParams<{
+ confirmAction?: string;
+ branchName?: string;
+ includesCommit?: string;
+ commitMessage?: string;
+ filePaths?: string;
+ }>();
+
+ const confirmAction = params.confirmAction as
+ | "push"
+ | "create_pr"
+ | "commit_push"
+ | "commit_push_pr"
+ | undefined;
+ const branchName = params.branchName ?? "";
+ const includesCommit = params.includesCommit === "true";
+
+ const copy = useMemo(
+ () =>
+ confirmAction
+ ? resolveDefaultBranchActionDialogCopy({
+ action: confirmAction,
+ branchName,
+ includesCommit,
+ })
+ : null,
+ [branchName, confirmAction, includesCommit],
+ );
+
+ const continuePendingAction = useCallback(async () => {
+ if (!confirmAction) return;
+ router.dismissAll();
+ await gitActions.onRunSelectedThreadGitAction({
+ action: confirmAction,
+ ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}),
+ ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}),
+ });
+ }, [confirmAction, gitActions, params, router]);
+
+ const movePendingActionToFeatureBranch = useCallback(async () => {
+ if (!confirmAction) return;
+ router.dismissAll();
+
+ if (includesCommit) {
+ await gitActions.onRunSelectedThreadGitAction({
+ action: confirmAction,
+ featureBranch: true,
+ ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}),
+ ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}),
+ });
+ return;
+ }
+
+ const branches =
+ gitState.selectedThreadBranches.length > 0
+ ? gitState.selectedThreadBranches
+ : await gitActions.refreshSelectedThreadBranches();
+ const newBranchName = resolveAutoFeatureBranchName(
+ branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
+ );
+ await gitActions.onCreateSelectedThreadBranch(newBranchName);
+ await gitActions.onRunSelectedThreadGitAction({ action: confirmAction });
+ }, [confirmAction, gitActions, gitState.selectedThreadBranches, includesCommit, params, router]);
+
+ return (
+
+
+
+
+
+ Confirm
+
+
+ {copy?.title ?? "Run action on default branch?"}
+
+
+ {copy?.description ?? "Choose how to continue."}
+
+
+
+
+ void continuePendingAction()}
+ />
+ void movePendingActionToFeatureBranch()}
+ />
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
new file mode 100644
index 0000000000..765d603a4d
--- /dev/null
+++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
@@ -0,0 +1,245 @@
+import {
+ type GitActionRequestInput,
+ buildMenuItems,
+ getGitActionDisabledReason,
+ requiresDefaultBranchConfirmation,
+} from "@t3tools/client-runtime";
+import { useLocalSearchParams, useRouter } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useCallback, useEffect, useMemo } from "react";
+import { Alert, Linking, Pressable, ScrollView, View } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useThemeColor } from "../../../lib/useThemeColor";
+
+import { AppText as Text } from "../../../components/AppText";
+import { buildThreadReviewRoutePath } from "../../../lib/routes";
+import { useGitStatus } from "../../../state/use-git-status";
+import { useThreadSelection } from "../../../state/use-thread-selection";
+import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
+import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
+
+export function GitOverviewSheet() {
+ const router = useRouter();
+ const insets = useSafeAreaInsets();
+ const { environmentId, threadId } = useLocalSearchParams<{
+ environmentId: string;
+ threadId: string;
+ }>();
+ const { selectedThread, selectedThreadProject } = useThreadSelection();
+ const gitState = useSelectedThreadGitState();
+ const gitActions = useSelectedThreadGitActions();
+
+ const iconColor = useThemeColor("--color-icon");
+ const borderColor = useThemeColor("--color-border");
+
+ const gitStatus = useGitStatus({
+ environmentId: selectedThread?.environmentId ?? "",
+ cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
+ });
+
+ const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD";
+ const currentWorktreePath = selectedThread?.worktreePath ?? null;
+ const gitOperationLabel = gitState.gitOperationLabel;
+ const busy = gitOperationLabel !== null;
+ const isRepo = gitStatus.data?.isRepo ?? true;
+ const hasOriginRemote = gitStatus.data?.hasOriginRemote ?? false;
+ const isDefaultBranch = gitStatus.data?.isDefaultBranch ?? false;
+
+ const menuItems = useMemo(
+ () => (isRepo ? buildMenuItems(gitStatus.data, busy, hasOriginRemote) : []),
+ [busy, gitStatus.data, hasOriginRemote, isRepo],
+ );
+
+ const sheetMenuItems = useMemo(
+ () =>
+ menuItems.map((item) => ({
+ item,
+ disabledReason: getGitActionDisabledReason({
+ item,
+ gitStatus: gitStatus.data,
+ isBusy: busy,
+ hasOriginRemote,
+ }),
+ })),
+ [busy, gitStatus.data, hasOriginRemote, menuItems],
+ );
+
+ useEffect(() => {
+ void gitActions.refreshSelectedThreadGitStatus({ quiet: true });
+ }, [gitActions]);
+
+ const openExistingPr = useCallback(async () => {
+ const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
+ if (!prUrl) {
+ Alert.alert("No open PR", "This branch does not have an open pull request.");
+ return;
+ }
+ try {
+ await Linking.openURL(prUrl);
+ } catch (error) {
+ Alert.alert(
+ "Unable to open PR",
+ error instanceof Error ? error.message : "An error occurred.",
+ );
+ }
+ }, [gitStatus.data]);
+
+ const runActionWithPrompt = useCallback(
+ async (input: GitActionRequestInput) => {
+ const confirmableAction =
+ input.action === "push" ||
+ input.action === "create_pr" ||
+ input.action === "commit_push" ||
+ input.action === "commit_push_pr"
+ ? input.action
+ : null;
+ const branchName = gitStatus.data?.branch;
+ if (
+ branchName &&
+ confirmableAction &&
+ !input.featureBranch &&
+ requiresDefaultBranchConfirmation(input.action, isDefaultBranch)
+ ) {
+ router.push({
+ pathname: "/threads/[environmentId]/[threadId]/git-confirm",
+ params: {
+ environmentId,
+ threadId,
+ confirmAction: confirmableAction,
+ branchName,
+ includesCommit: String(
+ input.action === "commit_push" || input.action === "commit_push_pr",
+ ),
+ },
+ });
+ return;
+ }
+
+ router.dismiss();
+ await gitActions.onRunSelectedThreadGitAction(input);
+ },
+ [environmentId, gitActions, gitStatus.data, isDefaultBranch, router, threadId],
+ );
+
+ const onPressMenuItem = useCallback(
+ async (item: (typeof menuItems)[number]) => {
+ if (item.disabled) return;
+ if (item.kind === "open_pr") {
+ await openExistingPr();
+ return;
+ }
+ if (item.dialogAction === "commit") {
+ router.push({
+ pathname: "/threads/[environmentId]/[threadId]/git/commit",
+ params: { environmentId, threadId },
+ });
+ return;
+ }
+ if (item.dialogAction === "push") {
+ await runActionWithPrompt({ action: "push" });
+ return;
+ }
+ if (item.dialogAction === "create_pr") {
+ await runActionWithPrompt({ action: "create_pr" });
+ }
+ },
+ [environmentId, openExistingPr, router, runActionWithPrompt, threadId],
+ );
+
+ return (
+
+
+
+
+ void gitActions.refreshSelectedThreadGitStatus()}
+ >
+
+
+
+ Branch
+
+ {currentBranchLabel}
+
+ {statusSummary(gitStatus.data)}
+
+
+
+
+
+ {sheetMenuItems.map(({ item, disabledReason }, index) => (
+
+ {index > 0 ? (
+
+ ) : null}
+ void onPressMenuItem(item)}
+ />
+
+ ))}
+ {(gitStatus.data?.behindCount ?? 0) > 0 ? (
+ <>
+
+ void gitActions.onPullSelectedThreadBranch()}
+ />
+ >
+ ) : null}
+
+ router.push(buildThreadReviewRoutePath({ environmentId, threadId }))}
+ />
+
+
+ router.push({
+ pathname: "/threads/[environmentId]/[threadId]/git/branches",
+ params: { environmentId, threadId },
+ })
+ }
+ />
+
+
+ {currentWorktreePath ? : null}
+
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/git/gitSheetComponents.tsx b/apps/mobile/src/features/threads/git/gitSheetComponents.tsx
new file mode 100644
index 0000000000..b13f6a3020
--- /dev/null
+++ b/apps/mobile/src/features/threads/git/gitSheetComponents.tsx
@@ -0,0 +1,161 @@
+import { SymbolView } from "expo-symbols";
+import type { ComponentProps } from "react";
+import { Pressable, View } from "react-native";
+import { useThemeColor } from "../../../lib/useThemeColor";
+import { AppText as Text } from "../../../components/AppText";
+
+/* ─── Shared sheet components ──────────────────────────────────────── */
+
+export function SheetActionButton(props: {
+ readonly icon: ComponentProps["name"];
+ readonly label: string;
+ readonly disabled?: boolean;
+ 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,
+ };
+
+ return (
+
+
+
+ {props.label}
+
+
+ );
+}
+
+export function MetaCard(props: { readonly label: string; readonly value: string }) {
+ return (
+
+
+ {props.label}
+
+
+ {props.value}
+
+
+ );
+}
+
+export function SheetListRow(props: {
+ readonly icon: ComponentProps["name"];
+ readonly title: string;
+ readonly subtitle?: string | null;
+ readonly disabled?: boolean;
+ readonly onPress: () => void;
+}) {
+ const iconColor = useThemeColor("--color-icon");
+ const iconSubtleColor = useThemeColor("--color-icon-subtle");
+
+ return (
+
+
+
+
+
+ {props.title}
+ {props.subtitle ? (
+ {props.subtitle}
+ ) : null}
+
+
+
+ );
+}
+
+/* ─── Shared utilities ──────────────────────────────────────────────── */
+
+export function menuItemIconName(
+ icon: "commit" | "push" | "pr",
+): ComponentProps["name"] {
+ if (icon === "commit") return "checkmark.circle";
+ if (icon === "push") return "arrow.up.circle";
+ return "arrow.up.right.circle";
+}
+
+export function statusSummary(
+ gitStatus: {
+ readonly isRepo?: boolean;
+ readonly hasWorkingTreeChanges?: boolean;
+ readonly workingTree?: { readonly files: readonly { readonly path: string }[] };
+ readonly aheadCount?: number;
+ readonly behindCount?: number;
+ readonly pr?: { readonly state?: string; readonly number?: number } | null;
+ } | null,
+): string {
+ if (!gitStatus) {
+ return "Loading branch status\u2026";
+ }
+
+ if (!gitStatus.isRepo) {
+ return "Not a git repository";
+ }
+
+ const parts: string[] = [];
+ if (gitStatus.hasWorkingTreeChanges) {
+ const fileCount = gitStatus.workingTree?.files.length ?? 0;
+ parts.push(`${fileCount} file${fileCount === 1 ? "" : "s"} changed`);
+ } else {
+ parts.push("Clean");
+ }
+ if ((gitStatus.aheadCount ?? 0) > 0) {
+ parts.push(`${gitStatus.aheadCount} ahead`);
+ }
+ if ((gitStatus.behindCount ?? 0) > 0) {
+ parts.push(`${gitStatus.behindCount} behind`);
+ }
+ if (gitStatus.pr?.state === "open") {
+ parts.push(`PR #${gitStatus.pr.number} open`);
+ }
+
+ return parts.join(" \u00b7 ");
+}
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
new file mode 100644
index 0000000000..0ddc8a6ef3
--- /dev/null
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -0,0 +1,500 @@
+import React, { useCallback, useEffect, useMemo, useState } from "react";
+
+import type {
+ ClaudeCodeEffort,
+ EnvironmentId,
+ GitBranch,
+ ModelSelection,
+ ProviderInteractionMode,
+ RuntimeMode,
+} from "@t3tools/contracts";
+import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import { pipe } from "effect/Function";
+
+import type { DraftComposerImageAttachment } from "../../lib/composerImages";
+import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
+import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
+import { groupProjectsByRepository } from "../../lib/repositoryGroups";
+import { scopedProjectKey } from "../../lib/scopedEntities";
+import { gitBranchManager, useGitBranches } from "../../state/use-git-branches";
+import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import {
+ setPendingConnectionError,
+ useRemoteEnvironmentState,
+} from "../../state/use-remote-environment-registry";
+import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime";
+
+type WorkspaceMode = "local" | "worktree";
+
+function normalizeSelectedWorktreePath(
+ project: EnvironmentScopedProjectShell,
+ branch: GitBranch,
+): string | null {
+ if (!branch.worktreePath) {
+ return null;
+ }
+
+ return branch.worktreePath === project.workspaceRoot ? null : branch.worktreePath;
+}
+
+export function branchBadgeLabel(input: {
+ readonly branch: GitBranch;
+ readonly project: EnvironmentScopedProjectShell | null;
+}): string | null {
+ if (input.branch.current) {
+ return "current";
+ }
+ if (input.branch.worktreePath && input.branch.worktreePath !== input.project?.workspaceRoot) {
+ return "worktree";
+ }
+ if (input.branch.isDefault) {
+ return "default";
+ }
+ if (input.branch.isRemote) {
+ return "remote";
+ }
+ return null;
+}
+
+type NewTaskFlowContextValue = {
+ readonly logicalProjects: ReadonlyArray<{
+ readonly key: string;
+ readonly project: EnvironmentScopedProjectShell;
+ }>;
+ readonly selectedEnvironmentId: EnvironmentId;
+ readonly selectedProjectKey: string | null;
+ readonly selectedModelKey: string | null;
+ readonly workspaceMode: WorkspaceMode;
+ readonly selectedBranchName: string | null;
+ readonly selectedWorktreePath: string | null;
+ readonly prompt: string;
+ readonly attachments: ReadonlyArray;
+ readonly submitting: boolean;
+ readonly branchQuery: string;
+ readonly branchesLoading: boolean;
+ readonly availableBranches: ReadonlyArray;
+ readonly runtimeMode: RuntimeMode;
+ readonly interactionMode: ProviderInteractionMode;
+ readonly effort: ClaudeCodeEffort;
+ readonly fastMode: boolean;
+ readonly contextWindow: string;
+ readonly expandedProvider: string | null;
+ readonly environments: ReadonlyArray<{
+ readonly environmentId: EnvironmentId;
+ readonly environmentLabel: string;
+ }>;
+ readonly selectedProject: EnvironmentScopedProjectShell | null;
+ readonly modelOptions: ReadonlyArray;
+ readonly selectedModel: ModelSelection | null;
+ readonly selectedModelOption: ModelOption | null;
+ readonly providerGroups: ReadonlyArray;
+ readonly filteredBranches: ReadonlyArray;
+ readonly reset: () => void;
+ readonly setProject: (project: EnvironmentScopedProjectShell) => void;
+ readonly selectEnvironment: (environmentId: EnvironmentId) => void;
+ readonly setSelectedModelKey: (key: string | null) => void;
+ readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
+ readonly selectBranch: (branch: GitBranch) => void;
+ readonly setPrompt: (value: string) => void;
+ readonly replaceAttachments: (attachments: ReadonlyArray) => void;
+ readonly appendAttachments: (attachments: ReadonlyArray) => void;
+ readonly removeAttachment: (imageId: string) => void;
+ readonly clearAttachments: () => void;
+ readonly setSubmitting: (value: boolean) => void;
+ readonly setBranchQuery: (value: string) => void;
+ readonly loadBranches: () => Promise;
+ readonly setRuntimeMode: (value: RuntimeMode) => void;
+ readonly setInteractionMode: (value: ProviderInteractionMode) => void;
+ readonly setEffort: (value: ClaudeCodeEffort) => void;
+ readonly setFastMode: (value: boolean) => void;
+ readonly setContextWindow: (value: string) => void;
+ readonly setExpandedProvider: (value: string | null) => void;
+};
+
+const NewTaskFlowContext = React.createContext(null);
+
+export function NewTaskFlowProvider(props: React.PropsWithChildren) {
+ const { projects, serverConfigByEnvironmentId, threads } = useRemoteCatalog();
+ const { savedConnectionsById } = useRemoteEnvironmentState();
+
+ const repositoryGroups = useMemo(
+ () => groupProjectsByRepository({ projects, threads }),
+ [projects, threads],
+ );
+ const logicalProjects = useMemo(
+ () =>
+ pipe(
+ repositoryGroups,
+ Arr.map((group) => {
+ const primaryProject = group.projects[0]?.project;
+ if (!primaryProject) {
+ return null;
+ }
+ return { key: group.key, project: primaryProject };
+ }),
+ Arr.filter(
+ (
+ entry,
+ ): entry is {
+ readonly key: string;
+ readonly project: EnvironmentScopedProjectShell;
+ } => entry !== null,
+ ),
+ ),
+ [repositoryGroups],
+ );
+
+ const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(
+ projects[0]?.environmentId ?? "",
+ );
+ const [selectedProjectKey, setSelectedProjectKey] = useState(null);
+ const [selectedModelKey, setSelectedModelKey] = useState(null);
+ const [workspaceMode, setWorkspaceMode] = useState("local");
+ const [selectedBranchName, setSelectedBranchName] = useState(null);
+ const [selectedWorktreePath, setSelectedWorktreePath] = useState(null);
+ const [prompt, setPrompt] = useState("");
+ const [attachments, setAttachments] = useState>([]);
+ const [submitting, setSubmitting] = useState(false);
+ const [branchQuery, setBranchQuery] = useState("");
+ const [runtimeMode, setRuntimeMode] = useState(DEFAULT_RUNTIME_MODE);
+ const [interactionMode, setInteractionMode] = useState(
+ DEFAULT_PROVIDER_INTERACTION_MODE,
+ );
+ const [effort, setEffort] = useState("high");
+ const [fastMode, setFastMode] = useState(false);
+ const [contextWindow, setContextWindow] = useState("1M");
+ const [expandedProvider, setExpandedProvider] = useState(null);
+
+ const replaceAttachments = useCallback(
+ (nextAttachments: ReadonlyArray) => {
+ setAttachments(nextAttachments);
+ },
+ [],
+ );
+
+ const appendAttachments = useCallback(
+ (nextAttachments: ReadonlyArray) => {
+ setAttachments((current) => [...current, ...nextAttachments]);
+ },
+ [],
+ );
+
+ const removeAttachment = useCallback((imageId: string) => {
+ setAttachments((current) => current.filter((candidate) => candidate.id !== imageId));
+ }, []);
+
+ const clearAttachments = useCallback(() => {
+ setAttachments([]);
+ }, []);
+
+ const reset = useCallback(() => {
+ console.log("[new task flow] reset", {
+ defaultEnvironmentId: projects[0]?.environmentId ?? null,
+ projectCount: projects.length,
+ });
+ setSelectedEnvironmentId(projects[0]?.environmentId ?? "");
+ setSelectedProjectKey(null);
+ setSelectedModelKey(null);
+ setWorkspaceMode("local");
+ setSelectedBranchName(null);
+ setSelectedWorktreePath(null);
+ setPrompt("");
+ clearAttachments();
+ setSubmitting(false);
+ setBranchQuery("");
+ setRuntimeMode(DEFAULT_RUNTIME_MODE);
+ setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
+ setEffort("high");
+ setFastMode(false);
+ setContextWindow("1M");
+ setExpandedProvider(null);
+ }, [clearAttachments, projects]);
+
+ useEffect(() => {
+ if (selectedEnvironmentId || projects.length === 0) {
+ return;
+ }
+
+ console.log("[new task flow] initializing environment", {
+ environmentId: projects[0]!.environmentId,
+ });
+ setSelectedEnvironmentId(projects[0]!.environmentId);
+ }, [projects, selectedEnvironmentId]);
+
+ 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(
+ projects,
+ Arr.filter((project) => project.environmentId === selectedEnvironmentId),
+ ),
+ [projects, selectedEnvironmentId],
+ );
+
+ const selectedProject =
+ projectsForEnvironment.find(
+ (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
+ ) ??
+ projectsForEnvironment[0] ??
+ null;
+
+ const modelOptions = useMemo(
+ () =>
+ buildModelOptions(
+ selectedProject
+ ? (serverConfigByEnvironmentId[selectedProject.environmentId] ?? null)
+ : null,
+ selectedProject?.defaultModelSelection ?? null,
+ ),
+ [selectedProject, serverConfigByEnvironmentId],
+ );
+
+ const selectedModel =
+ modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
+ selectedProject?.defaultModelSelection ??
+ modelOptions[0]?.selection ??
+ null;
+
+ const selectedModelOption =
+ modelOptions.find(
+ (option) =>
+ selectedModel &&
+ option.selection.provider === selectedModel.provider &&
+ option.selection.model === selectedModel.model,
+ ) ?? null;
+
+ const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
+ const branchTarget = useMemo(
+ () => ({
+ environmentId: selectedProject?.environmentId ?? null,
+ cwd: selectedProject?.workspaceRoot ?? null,
+ query: null,
+ }),
+ [selectedProject?.environmentId, selectedProject?.workspaceRoot],
+ );
+ const branchState = useGitBranches(branchTarget);
+ const branchesLoading = branchState.isPending;
+ const availableBranches = useMemo(
+ () =>
+ pipe(
+ branchState.data?.branches ?? [],
+ Arr.filter((branch) => !branch.isRemote),
+ ),
+ [branchState.data?.branches],
+ );
+
+ const filteredBranches = useMemo(() => {
+ const query = branchQuery.trim().toLowerCase();
+ if (query.length === 0) {
+ return availableBranches;
+ }
+
+ return pipe(
+ availableBranches,
+ Arr.filter((branch) => branch.name.toLowerCase().includes(query)),
+ );
+ }, [availableBranches, branchQuery]);
+
+ const setProject = useCallback((project: EnvironmentScopedProjectShell) => {
+ setSelectedEnvironmentId(project.environmentId);
+ setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
+ }, []);
+
+ const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
+ setSelectedEnvironmentId(environmentId);
+ setSelectedProjectKey(null);
+ setSelectedBranchName(null);
+ setSelectedWorktreePath(null);
+ }, []);
+
+ const selectBranch = useCallback(
+ (branch: GitBranch) => {
+ setSelectedBranchName(branch.name);
+ setSelectedWorktreePath(
+ selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
+ );
+ },
+ [selectedProject],
+ );
+
+ const loadBranches = useCallback(async () => {
+ if (!selectedProject) {
+ return;
+ }
+
+ try {
+ const result = await gitBranchManager.load({
+ environmentId: selectedProject.environmentId,
+ cwd: selectedProject.workspaceRoot,
+ query: null,
+ });
+ setPendingConnectionError(null);
+ const branches = pipe(
+ result?.branches ?? [],
+ Arr.filter((branch) => !branch.isRemote),
+ );
+
+ if (workspaceMode === "worktree" && !selectedBranchName) {
+ const preferredBranch =
+ branches.find((branch) => branch.current)?.name ??
+ branches.find((branch) => branch.isDefault)?.name ??
+ null;
+ if (preferredBranch) {
+ setSelectedBranchName(preferredBranch);
+ }
+ }
+ } catch {
+ setPendingConnectionError("Failed to load branches.");
+ }
+ }, [selectedBranchName, selectedProject, workspaceMode]);
+
+ const value = useMemo(
+ () => ({
+ logicalProjects,
+ selectedEnvironmentId,
+ selectedProjectKey,
+ selectedModelKey,
+ workspaceMode,
+ selectedBranchName,
+ selectedWorktreePath,
+ prompt,
+ attachments,
+ submitting,
+ branchQuery,
+ branchesLoading,
+ availableBranches,
+ runtimeMode,
+ interactionMode,
+ effort,
+ fastMode,
+ contextWindow,
+ expandedProvider,
+ environments,
+ selectedProject,
+ modelOptions,
+ selectedModel,
+ selectedModelOption,
+ providerGroups,
+ filteredBranches,
+ reset,
+ setProject,
+ selectEnvironment,
+ setSelectedModelKey,
+ setWorkspaceMode,
+ selectBranch,
+ setPrompt,
+ replaceAttachments,
+ appendAttachments,
+ removeAttachment,
+ clearAttachments,
+ setSubmitting,
+ setBranchQuery,
+ loadBranches,
+ setRuntimeMode,
+ setInteractionMode,
+ setEffort,
+ setFastMode,
+ setContextWindow,
+ setExpandedProvider,
+ }),
+ [
+ attachments,
+ availableBranches,
+ branchQuery,
+ branchesLoading,
+ contextWindow,
+ effort,
+ environments,
+ expandedProvider,
+ fastMode,
+ filteredBranches,
+ interactionMode,
+ loadBranches,
+ logicalProjects,
+ modelOptions,
+ prompt,
+ providerGroups,
+ replaceAttachments,
+ reset,
+ runtimeMode,
+ selectedBranchName,
+ selectedEnvironmentId,
+ selectedModel,
+ selectedModelKey,
+ selectedModelOption,
+ selectedProject,
+ selectedProjectKey,
+ selectedWorktreePath,
+ setProject,
+ selectBranch,
+ selectEnvironment,
+ submitting,
+ workspaceMode,
+ appendAttachments,
+ clearAttachments,
+ removeAttachment,
+ ],
+ );
+
+ useEffect(() => {
+ console.log("[new task flow] state", {
+ availableBranchCount: availableBranches.length,
+ environmentCount: environments.length,
+ logicalProjectCount: logicalProjects.length,
+ selectedEnvironmentId,
+ selectedProjectKey,
+ selectedProjectTitle: selectedProject?.title ?? null,
+ });
+ }, [
+ availableBranches.length,
+ environments.length,
+ logicalProjects.length,
+ selectedEnvironmentId,
+ selectedProject?.title,
+ selectedProjectKey,
+ ]);
+
+ return {props.children};
+}
+
+export function useNewTaskFlow() {
+ const value = React.use(NewTaskFlowContext);
+ if (value === null) {
+ throw new Error("useNewTaskFlow must be used within NewTaskFlowProvider.");
+ }
+ return value;
+}
diff --git a/apps/mobile/src/features/threads/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/threads/review/ReviewCommentComposerSheet.tsx
new file mode 100644
index 0000000000..379d4c61a2
--- /dev/null
+++ b/apps/mobile/src/features/threads/review/ReviewCommentComposerSheet.tsx
@@ -0,0 +1,188 @@
+import { useLocalSearchParams, useRouter } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useMemo, useState } from "react";
+import { Platform, Pressable, ScrollView, Text as NativeText, View } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
+import { cn } from "../../../lib/cn";
+import { useThemeColor } from "../../../lib/useThemeColor";
+import {
+ clearReviewCommentTarget,
+ formatReviewCommentContext,
+ getReviewChangeMarker,
+ getReviewUnifiedLineNumber,
+ getSelectedReviewCommentLines,
+ useReviewCommentTarget,
+} from "./reviewCommentSelection";
+import { appendReviewCommentToDraft } from "../use-thread-composer-state";
+
+const REVIEW_MONO_FONT_FAMILY = Platform.select({
+ ios: "ui-monospace",
+ android: "monospace",
+ default: "monospace",
+});
+
+function renderVisibleWhitespace(value: string): string {
+ const expandedTabs = value.replace(/\t/g, " ");
+ return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
+}
+
+function changeTone(change: "context" | "add" | "delete"): string {
+ if (change === "add") return "bg-emerald-500/12";
+ if (change === "delete") return "bg-rose-500/12";
+ return "bg-card";
+}
+
+export function ReviewCommentComposerSheet() {
+ const router = useRouter();
+ const insets = useSafeAreaInsets();
+ const iconTint = String(useThemeColor("--color-icon"));
+ const target = useReviewCommentTarget();
+ const { environmentId, threadId } = useLocalSearchParams<{
+ environmentId: string;
+ threadId: string;
+ }>();
+ const [commentText, setCommentText] = useState("");
+
+ const selectedLines = useMemo(
+ () => (target ? getSelectedReviewCommentLines(target) : []),
+ [target],
+ );
+ const firstLine = selectedLines[0] ?? null;
+ const lastLine = selectedLines[selectedLines.length - 1] ?? null;
+ const firstNumber = firstLine ? getReviewUnifiedLineNumber(firstLine) : null;
+ const lastNumber = lastLine ? getReviewUnifiedLineNumber(lastLine) : null;
+ const canSubmit =
+ commentText.trim().length > 0 && target !== null && !!environmentId && !!threadId;
+
+ return (
+
+
+ {
+ clearReviewCommentTarget();
+ router.dismiss();
+ }}
+ >
+
+
+
+ Add Comment
+
+ {
+ if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
+ return;
+ }
+
+ appendReviewCommentToDraft({
+ environmentId,
+ threadId,
+ text: formatReviewCommentContext(target, commentText),
+ });
+ clearReviewCommentTarget();
+ router.dismiss();
+ }}
+ style={{ opacity: canSubmit ? 1 : 0.55 }}
+ >
+
+ Comment
+
+
+
+
+ {!target ? (
+
+ No selection
+
+ Select a diff line or range first.
+
+
+ ) : (
+ <>
+
+
+ {target.filePath}
+
+
+ {selectedLines.length === 1
+ ? firstNumber !== null
+ ? `Line ${firstNumber}`
+ : "File comment"
+ : firstNumber !== null && lastNumber !== null
+ ? `Lines ${firstNumber}-${lastNumber}`
+ : `${selectedLines.length} lines selected`}
+
+
+
+
+ {selectedLines.map((line) => {
+ const lineNumber = getReviewUnifiedLineNumber(line);
+
+ return (
+
+
+ {lineNumber ?? ""}
+
+
+ {getReviewChangeMarker(line.change)}
+
+
+ {renderVisibleWhitespace(line.content || " ")}
+
+
+ );
+ })}
+
+
+
+ Comment
+
+
+ >
+ )}
+
+ );
+}
diff --git a/apps/mobile/src/features/threads/review/ReviewSheet.tsx b/apps/mobile/src/features/threads/review/ReviewSheet.tsx
new file mode 100644
index 0000000000..5745669147
--- /dev/null
+++ b/apps/mobile/src/features/threads/review/ReviewSheet.tsx
@@ -0,0 +1,1000 @@
+import {
+ ThreadId,
+ type GitReviewDiffSection,
+ type OrchestrationCheckpointSummary,
+} from "@t3tools/contracts";
+import { useLocalSearchParams, useRouter } from "expo-router";
+import Stack from "expo-router/stack";
+import { SymbolView } from "expo-symbols";
+import { type ReactElement, useCallback, useEffect, useMemo, useState } from "react";
+import {
+ ActivityIndicator,
+ Platform,
+ Pressable,
+ ScrollView,
+ Text as NativeText,
+ useColorScheme,
+ useWindowDimensions,
+ View,
+} from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { AppText as Text } from "../../../components/AppText";
+import { cn } from "../../../lib/cn";
+import { useThemeColor } from "../../../lib/useThemeColor";
+import { getEnvironmentClient } from "../../../state/use-remote-environment-registry";
+import { useSelectedThreadDetail } from "../../../state/use-thread-detail";
+import { useThreadSelection } from "../../../state/use-thread-selection";
+import {
+ buildReviewParsedDiff,
+ getReadyReviewCheckpoints,
+ buildReviewSectionItems,
+ getDefaultReviewSectionId,
+ getReviewSectionIdForCheckpoint,
+ type ReviewRenderableFile,
+ type ReviewRenderableLineRow,
+} from "./reviewModel";
+import {
+ highlightReviewFile,
+ type ReviewDiffTheme,
+ type ReviewHighlightedFile,
+ type ReviewHighlightedToken,
+} from "./shikiReviewHighlighter";
+import {
+ buildReviewCommentTarget,
+ clearReviewCommentTarget,
+ formatReviewSelectedRangeLabel,
+ getReviewChangeMarker,
+ getReviewUnifiedLineNumber,
+ getSelectedReviewCommentLines,
+ setReviewCommentTarget,
+ type ReviewCommentTarget,
+ useReviewCommentTarget,
+} from "./reviewCommentSelection";
+
+interface PendingCommentSelection {
+ readonly sectionTitle: string;
+ readonly filePath: string;
+ readonly lines: ReadonlyArray;
+ readonly anchorIndex: number;
+}
+
+const REVIEW_MONO_FONT_FAMILY = Platform.select({
+ ios: "ui-monospace",
+ android: "monospace",
+ default: "monospace",
+});
+const IOS_NAV_BAR_HEIGHT = 44;
+const REVIEW_HEADER_SPACING = 32;
+
+function changeTone(change: ReviewRenderableLineRow["change"]): string {
+ if (change === "add") return "bg-emerald-500/12";
+ if (change === "delete") return "bg-rose-500/12";
+ return "bg-card";
+}
+
+function changeTypeLabel(type: ReviewRenderableFile["changeType"]): string {
+ switch (type) {
+ case "new":
+ return "Added";
+ case "deleted":
+ return "Deleted";
+ case "rename-pure":
+ return "Renamed";
+ case "rename-changed":
+ return "Renamed + edited";
+ default:
+ return "Edited";
+ }
+}
+
+function formatHeaderDiffSummary(parsedDiff: ReturnType): {
+ readonly additions: string | null;
+ readonly deletions: string | null;
+} {
+ if (parsedDiff.kind !== "files") {
+ return { additions: null, deletions: null };
+ }
+
+ return {
+ additions: `+${parsedDiff.additions}`,
+ deletions: `-${parsedDiff.deletions}`,
+ };
+}
+
+function shouldAutoExpandFile(file: ReviewRenderableFile): boolean {
+ return file.additions + file.deletions <= 20 && file.rows.length <= 40;
+}
+
+function getDefaultExpandedFileIds(
+ files: ReadonlyArray,
+): ReadonlyArray {
+ const autoExpanded = files.filter(shouldAutoExpandFile).map((file) => file.id);
+ if (autoExpanded.length > 0) {
+ return autoExpanded;
+ }
+ return files.length === 1 ? [files[0]!.id] : [];
+}
+
+function renderVisibleWhitespace(value: string): string {
+ const expandedTabs = value.replace(/\t/g, " ");
+ return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
+}
+
+function DiffTokenText(props: {
+ readonly tokens: ReadonlyArray | null;
+ readonly fallback: string;
+}) {
+ if (!props.tokens || props.tokens.length === 0) {
+ return (
+
+ {renderVisibleWhitespace(props.fallback || " ")}
+
+ );
+ }
+
+ return (
+
+ {(() => {
+ let offset = 0;
+
+ return props.tokens.map((token) => {
+ const start = offset;
+ offset += token.content.length;
+
+ const fontWeight =
+ token.fontStyle !== null && (token.fontStyle & 2) === 2
+ ? ("700" as const)
+ : ("400" as const);
+ const fontStyle =
+ token.fontStyle !== null && (token.fontStyle & 1) === 1
+ ? ("italic" as const)
+ : ("normal" as const);
+
+ return (
+
+ {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
+
+ );
+ });
+ })()}
+
+ );
+}
+
+function ReviewLineRow(props: {
+ readonly line: ReviewRenderableLineRow;
+ readonly tokens: ReadonlyArray | null;
+ readonly viewportWidth: number;
+ readonly selectionState: "anchor" | "selected" | null;
+ readonly onComment: () => void;
+ readonly onStartRangeSelection: () => void;
+}) {
+ const lineNumber = getReviewUnifiedLineNumber(props.line);
+
+ return (
+
+
+ {lineNumber ?? ""}
+
+
+ {getReviewChangeMarker(props.line.change)}
+
+
+
+
+
+ );
+}
+
+function ReviewFileCard(props: {
+ readonly file: ReviewRenderableFile;
+ readonly expanded: boolean;
+ readonly onToggle: () => void;
+}) {
+ return (
+
+
+
+
+
+
+
+ {props.file.path}
+
+ {props.file.previousPath && props.file.previousPath !== props.file.path ? (
+
+ {props.file.previousPath}
+
+ ) : null}
+
+
+
+ {changeTypeLabel(props.file.changeType)}
+
+
+
+ +{props.file.additions}
+
+ -{props.file.deletions}
+
+
+
+
+ );
+}
+
+function ReviewFileBody(props: {
+ readonly file: ReviewRenderableFile;
+ readonly sectionTitle: string;
+ readonly highlightedFile: ReviewHighlightedFile | null;
+ readonly viewportWidth: number;
+ readonly pendingSelection: PendingCommentSelection | null;
+ readonly selectedTarget: ReviewCommentTarget | null;
+ readonly onPressLine: (
+ line: ReviewRenderableLineRow,
+ availableLines: ReadonlyArray,
+ lineIndex: number,
+ ) => void;
+ readonly onStartRangeSelection: (
+ line: ReviewRenderableLineRow,
+ availableLines: ReadonlyArray,
+ lineIndex: number,
+ ) => void;
+}) {
+ const commentableLines = props.file.rows.filter(
+ (row): row is ReviewRenderableLineRow => row.kind === "line",
+ );
+ const anchorLineId =
+ props.pendingSelection &&
+ props.pendingSelection.sectionTitle === props.sectionTitle &&
+ props.pendingSelection.filePath === props.file.path
+ ? (props.pendingSelection.lines[props.pendingSelection.anchorIndex]?.id ?? null)
+ : null;
+ const selectedLineIds =
+ props.selectedTarget &&
+ props.selectedTarget.sectionTitle === props.sectionTitle &&
+ props.selectedTarget.filePath === props.file.path
+ ? new Set(getSelectedReviewCommentLines(props.selectedTarget).map((line) => line.id))
+ : null;
+
+ return (
+
+
+ {props.file.rows.map((row) => {
+ if (row.kind === "hunk") {
+ return (
+
+
+ {row.header}
+ {row.context ? ` ${row.context}` : ""}
+
+
+ );
+ }
+
+ const tokens =
+ row.change === "delete"
+ ? (props.highlightedFile?.deletionLines[row.deletionTokenIndex ?? -1] ?? null)
+ : (props.highlightedFile?.additionLines[row.additionTokenIndex ?? -1] ?? null);
+
+ return (
+ {
+ const lineIndex = commentableLines.findIndex(
+ (candidate) => candidate.id === row.id,
+ );
+ props.onPressLine(row, commentableLines, lineIndex >= 0 ? lineIndex : 0);
+ }}
+ onStartRangeSelection={() => {
+ const lineIndex = commentableLines.findIndex(
+ (candidate) => candidate.id === row.id,
+ );
+ props.onStartRangeSelection(row, commentableLines, lineIndex >= 0 ? lineIndex : 0);
+ }}
+ />
+ );
+ })}
+
+
+ );
+}
+
+function ReviewSelectionActionBar(props: {
+ readonly target: ReviewCommentTarget | null;
+ readonly bottomInset: number;
+ readonly onOpenComment: () => void;
+ readonly onClear: () => void;
+}) {
+ if (!props.target || props.target.startIndex === props.target.endIndex) {
+ return null;
+ }
+
+ return (
+
+
+
+
+ Comment on {formatReviewSelectedRangeLabel(props.target)}
+
+
+
+
+
+
+
+ );
+}
+
+export function ReviewSheet() {
+ const router = useRouter();
+ const insets = useSafeAreaInsets();
+ const { width } = useWindowDimensions();
+ const colorScheme = useColorScheme();
+ const headerForeground = String(useThemeColor("--color-foreground"));
+ const headerMuted = String(useThemeColor("--color-foreground-muted"));
+ const headerIcon = String(useThemeColor("--color-icon"));
+ const { environmentId, threadId } = useLocalSearchParams<{
+ environmentId: string;
+ threadId: string;
+ }>();
+ const { selectedThreadProject } = useThreadSelection();
+ const selectedThread = useSelectedThreadDetail();
+ const [gitSections, setGitSections] = useState>([]);
+ const [turnDiffById, setTurnDiffById] = useState>({});
+ const [loadingTurnIds, setLoadingTurnIds] = useState>({});
+ const [selectedSectionId, setSelectedSectionId] = useState(null);
+ const [loadingGitDiffs, setLoadingGitDiffs] = useState(false);
+ const [error, setError] = useState(null);
+ const [expandedFileIdsBySection, setExpandedFileIdsBySection] = useState<
+ Record | undefined>
+ >({});
+ const [highlightedFileByKey, setHighlightedFileByKey] = useState<
+ Record
+ >({});
+ const [pendingCommentSelection, setPendingCommentSelection] =
+ useState(null);
+ const activeCommentTarget = useReviewCommentTarget();
+
+ const cwd = selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null;
+ const readyCheckpoints = useMemo(
+ () => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
+ [selectedThread?.checkpoints],
+ );
+
+ const checkpointBySectionId = useMemo(() => {
+ return Object.fromEntries(
+ readyCheckpoints.map((checkpoint) => [
+ getReviewSectionIdForCheckpoint(checkpoint),
+ checkpoint,
+ ]),
+ ) as Record;
+ }, [readyCheckpoints]);
+
+ const reviewSections = useMemo(
+ () =>
+ buildReviewSectionItems({
+ checkpoints: readyCheckpoints,
+ gitSections,
+ turnDiffById,
+ loadingTurnIds,
+ }),
+ [gitSections, loadingTurnIds, readyCheckpoints, turnDiffById],
+ );
+
+ const selectedSection =
+ reviewSections.find((section) => section.id === selectedSectionId) ?? reviewSections[0] ?? null;
+ const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
+ const parsedDiff = useMemo(
+ () => buildReviewParsedDiff(selectedSection?.diff, selectedSection?.id ?? "mobile-review"),
+ [selectedSection?.diff, selectedSection?.id],
+ );
+ const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);
+
+ const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;
+ const expandedFileIds = useMemo(
+ () =>
+ selectedSection?.id && parsedDiff.kind === "files"
+ ? (expandedFileIdsBySection[selectedSection.id] ??
+ getDefaultExpandedFileIds(parsedDiff.files))
+ : [],
+ [expandedFileIdsBySection, parsedDiff, selectedSection?.id],
+ );
+ const expandedFiles = useMemo(
+ () =>
+ parsedDiff.kind === "files"
+ ? parsedDiff.files.filter((file) => expandedFileIds.includes(file.id))
+ : [],
+ [expandedFileIds, parsedDiff],
+ );
+
+ const loadGitDiffs = useCallback(async () => {
+ if (!environmentId || !cwd) {
+ return;
+ }
+
+ const client = getEnvironmentClient(environmentId);
+ if (!client) {
+ setError("Remote connection is not ready.");
+ return;
+ }
+
+ setLoadingGitDiffs(true);
+ setError(null);
+ try {
+ const result = await client.git.getReviewDiffs({ cwd });
+ setGitSections(result.sections);
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : "Failed to load review diffs.");
+ } finally {
+ setLoadingGitDiffs(false);
+ }
+ }, [cwd, environmentId]);
+
+ const loadTurnDiff = useCallback(
+ async (checkpoint: OrchestrationCheckpointSummary, force = false) => {
+ if (!environmentId || !threadId) {
+ return;
+ }
+
+ const sectionId = getReviewSectionIdForCheckpoint(checkpoint);
+ setSelectedSectionId(sectionId);
+
+ if (!force && turnDiffById[sectionId] !== undefined) {
+ return;
+ }
+
+ const client = getEnvironmentClient(environmentId);
+ if (!client) {
+ setError("Remote connection is not ready.");
+ return;
+ }
+
+ setLoadingTurnIds((current) => ({ ...current, [sectionId]: true }));
+ setError(null);
+ try {
+ const result = await client.orchestration.getTurnDiff({
+ threadId: ThreadId.make(threadId),
+ fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1),
+ toTurnCount: checkpoint.checkpointTurnCount,
+ });
+ setTurnDiffById((current) => ({ ...current, [sectionId]: result.diff }));
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : "Failed to load turn diff.");
+ } finally {
+ setLoadingTurnIds((current) => {
+ const next = { ...current };
+ delete next[sectionId];
+ return next;
+ });
+ }
+ },
+ [environmentId, threadId, turnDiffById],
+ );
+
+ useEffect(() => {
+ void loadGitDiffs();
+ }, [loadGitDiffs]);
+
+ useEffect(() => {
+ if (reviewSections.length === 0) {
+ return;
+ }
+
+ const fallbackId = getDefaultReviewSectionId(reviewSections);
+ if (!selectedSectionId || !reviewSections.some((section) => section.id === selectedSectionId)) {
+ setSelectedSectionId(fallbackId);
+ }
+ }, [reviewSections, selectedSectionId]);
+
+ useEffect(() => {
+ const latest = readyCheckpoints[0];
+ if (!latest) {
+ return;
+ }
+
+ const latestId = getReviewSectionIdForCheckpoint(latest);
+ if (turnDiffById[latestId] !== undefined || loadingTurnIds[latestId]) {
+ return;
+ }
+
+ void loadTurnDiff(latest);
+ }, [loadTurnDiff, loadingTurnIds, readyCheckpoints, turnDiffById]);
+
+ useEffect(() => {
+ if (!selectedSection || selectedSection.kind !== "turn" || selectedSection.diff !== null) {
+ return;
+ }
+
+ const checkpoint = checkpointBySectionId[selectedSection.id];
+ if (checkpoint && !loadingTurnIds[selectedSection.id]) {
+ void loadTurnDiff(checkpoint);
+ }
+ }, [checkpointBySectionId, loadTurnDiff, loadingTurnIds, selectedSection]);
+
+ useEffect(() => {
+ if (!selectedSectionId || parsedDiff.kind !== "files") {
+ return;
+ }
+
+ setExpandedFileIdsBySection((current) => {
+ const existing = current[selectedSectionId];
+ if (existing !== undefined) {
+ const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));
+ if (validIds.length === existing.length) {
+ return current;
+ }
+ return { ...current, [selectedSectionId]: validIds };
+ }
+
+ return {
+ ...current,
+ [selectedSectionId]: getDefaultExpandedFileIds(parsedDiff.files),
+ };
+ });
+ }, [parsedDiff, selectedSectionId]);
+
+ useEffect(() => {
+ if (!selectedSection || expandedFiles.length === 0) {
+ return;
+ }
+
+ const filesToHighlight = expandedFiles.filter((file) => {
+ const key = `${selectedSection.id}:${selectedTheme}:${file.cacheKey}`;
+ return highlightedFileByKey[key] === undefined;
+ });
+ if (filesToHighlight.length === 0) {
+ return;
+ }
+
+ let cancelled = false;
+ void Promise.all(
+ filesToHighlight.map(
+ async (file) =>
+ [
+ `${selectedSection.id}:${selectedTheme}:${file.cacheKey}`,
+ await highlightReviewFile(file, selectedTheme),
+ ] as const,
+ ),
+ )
+ .then((entries) => {
+ if (!cancelled) {
+ setHighlightedFileByKey((current) => ({
+ ...current,
+ ...Object.fromEntries(entries),
+ }));
+ }
+ })
+ .catch(() => {
+ if (cancelled) {
+ return;
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [expandedFiles, highlightedFileByKey, selectedSection, selectedTheme]);
+
+ const refreshSelectedSection = useCallback(async () => {
+ if (!selectedSection) {
+ return;
+ }
+
+ if (selectedSection.kind === "turn") {
+ const checkpoint = checkpointBySectionId[selectedSection.id];
+ if (checkpoint) {
+ await loadTurnDiff(checkpoint, true);
+ }
+ return;
+ }
+
+ await loadGitDiffs();
+ }, [checkpointBySectionId, loadGitDiffs, loadTurnDiff, selectedSection]);
+
+ const reviewContent = useMemo(() => {
+ const children: ReactElement[] = [];
+ const stickyHeaderIndices: number[] = [];
+
+ if (error) {
+ children.push(
+
+ Review unavailable
+ {error}
+ ,
+ );
+ }
+
+ if (parsedDiff.kind !== "empty" && parsedDiff.notice) {
+ children.push(
+
+
+ Partial diff
+
+
+ {parsedDiff.notice}
+
+ ,
+ );
+ }
+
+ if (!selectedSection) {
+ children.push(
+
+ No review diffs
+
+ This thread has no ready turn diffs and the worktree diff is empty.
+
+ ,
+ );
+ return { children, stickyHeaderIndices };
+ }
+
+ if (selectedSection.isLoading && selectedSection.diff === null) {
+ children.push(
+
+
+ Loading diff…
+ ,
+ );
+ return { children, stickyHeaderIndices };
+ }
+
+ if (parsedDiff.kind === "empty") {
+ children.push(
+
+ No changes
+
+ {selectedSection.subtitle ?? "This diff is empty."}
+
+ ,
+ );
+ return { children, stickyHeaderIndices };
+ }
+
+ if (parsedDiff.kind === "raw") {
+ children.push(
+
+
+ {parsedDiff.reason}
+
+
+
+ {parsedDiff.text}
+
+
+ ,
+ );
+ return { children, stickyHeaderIndices };
+ }
+
+ parsedDiff.files.forEach((file) => {
+ const isExpanded = expandedFileIds.includes(file.id);
+ const fileHighlightKey = `${selectedSection.id}:${selectedTheme}:${file.cacheKey}`;
+ const fileHighlights = highlightedFileByKey[fileHighlightKey] ?? null;
+
+ stickyHeaderIndices.push(children.length);
+ children.push(
+
+ setExpandedFileIdsBySection((current) => {
+ const existing =
+ current[selectedSection.id] ?? getDefaultExpandedFileIds(parsedDiff.files);
+ const next = existing.includes(file.id)
+ ? existing.filter((id) => id !== file.id)
+ : [...existing, file.id];
+ return {
+ ...current,
+ [selectedSection.id]: next,
+ };
+ })
+ }
+ />,
+ );
+
+ if (isExpanded) {
+ children.push(
+ {
+ if (pendingCommentSelection) {
+ if (
+ pendingCommentSelection.sectionTitle === selectedSection.title &&
+ pendingCommentSelection.filePath === file.path
+ ) {
+ setReviewCommentTarget(
+ buildReviewCommentTarget(
+ {
+ sectionTitle: pendingCommentSelection.sectionTitle,
+ filePath: pendingCommentSelection.filePath,
+ lines: pendingCommentSelection.lines,
+ },
+ pendingCommentSelection.anchorIndex,
+ lineIndex,
+ ),
+ );
+ setPendingCommentSelection(null);
+ return;
+ }
+
+ clearReviewCommentTarget();
+ setPendingCommentSelection({
+ sectionTitle: selectedSection.title,
+ filePath: file.path,
+ lines: availableLines,
+ anchorIndex: lineIndex,
+ });
+ return;
+ }
+
+ setReviewCommentTarget({
+ sectionTitle: selectedSection.title,
+ filePath: file.path,
+ lines: availableLines,
+ startIndex: lineIndex,
+ endIndex: lineIndex,
+ });
+ if (environmentId && threadId) {
+ router.push({
+ pathname: "/threads/[environmentId]/[threadId]/review-comment",
+ params: { environmentId, threadId },
+ });
+ }
+ }}
+ onStartRangeSelection={(_line, availableLines, lineIndex) => {
+ clearReviewCommentTarget();
+ setPendingCommentSelection({
+ sectionTitle: selectedSection.title,
+ filePath: file.path,
+ lines: availableLines,
+ anchorIndex: lineIndex,
+ });
+ }}
+ />,
+ );
+ }
+ });
+
+ return { children, stickyHeaderIndices };
+ }, [
+ activeCommentTarget,
+ error,
+ expandedFileIds,
+ highlightedFileByKey,
+ pendingCommentSelection,
+ parsedDiff,
+ router,
+ selectedSection,
+ selectedTheme,
+ threadId,
+ width,
+ environmentId,
+ ]);
+
+ return (
+ <>
+ (
+
+
+ Files Changed
+
+
+ {headerDiffSummary.additions && headerDiffSummary.deletions ? (
+ <>
+
+ {headerDiffSummary.additions}
+
+
+ {headerDiffSummary.deletions}
+
+ >
+ ) : (
+
+ {selectedSection?.title ?? "Review changes"}
+
+ )}
+
+
+ ),
+ }}
+ />
+
+
+
+ {reviewSections.map((section) => (
+ setSelectedSectionId(section.id)}
+ subtitle={section.subtitle ?? undefined}
+ >
+ {section.title}
+
+ ))}
+ void refreshSelectedSection()}
+ subtitle="Reload current diff"
+ >
+ Refresh
+
+
+
+
+
+
+ {reviewContent.children}
+
+
+ {
+ if (activeCommentTarget && environmentId && threadId) {
+ router.push({
+ pathname: "/threads/[environmentId]/[threadId]/review-comment",
+ params: { environmentId, threadId },
+ });
+ }
+ }}
+ onClear={() => {
+ clearReviewCommentTarget();
+ setPendingCommentSelection(null);
+ }}
+ />
+
+ >
+ );
+}
diff --git a/apps/mobile/src/features/threads/review/diffParser.ts b/apps/mobile/src/features/threads/review/diffParser.ts
new file mode 100644
index 0000000000..76e8872f8a
--- /dev/null
+++ b/apps/mobile/src/features/threads/review/diffParser.ts
@@ -0,0 +1,158 @@
+export type ParsedDiffLineType = "context" | "add" | "delete" | "meta" | "hunk";
+
+export interface ParsedDiffLine {
+ readonly id: string;
+ readonly type: ParsedDiffLineType;
+ readonly oldLine: number | null;
+ readonly newLine: number | null;
+ readonly content: string;
+}
+
+export interface ParsedDiffFile {
+ readonly id: string;
+ readonly oldPath: string | null;
+ readonly newPath: string | null;
+ readonly lines: ReadonlyArray;
+}
+
+function parseHunkStart(
+ line: string,
+): { readonly oldLine: number; readonly newLine: number } | null {
+ const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
+ if (!match) {
+ return null;
+ }
+
+ return {
+ oldLine: Number.parseInt(match[1] ?? "0", 10),
+ newLine: Number.parseInt(match[2] ?? "0", 10),
+ };
+}
+
+function parseDiffPath(line: string, prefix: "--- " | "+++ "): string | null {
+ if (!line.startsWith(prefix)) {
+ return null;
+ }
+ const raw = line.slice(prefix.length).trim();
+ if (raw === "/dev/null") {
+ return null;
+ }
+ return raw.replace(/^[ab]\//, "");
+}
+
+export function parseUnifiedDiff(diff: string): ReadonlyArray {
+ const files: ParsedDiffFile[] = [];
+ let current: {
+ oldPath: string | null;
+ newPath: string | null;
+ lines: ParsedDiffLine[];
+ } | null = null;
+ let oldLine: number | null = null;
+ let newLine: number | null = null;
+
+ const pushCurrent = () => {
+ if (!current) {
+ return;
+ }
+ files.push({
+ id: `${current.oldPath ?? "null"}:${current.newPath ?? "null"}:${files.length}`,
+ oldPath: current.oldPath,
+ newPath: current.newPath,
+ lines: current.lines,
+ });
+ };
+
+ for (const rawLine of diff.replace(/\r\n/g, "\n").split("\n")) {
+ if (rawLine.startsWith("diff --git ")) {
+ pushCurrent();
+ const match = rawLine.match(/^diff --git a\/(.+) b\/(.+)$/);
+ current = {
+ oldPath: match?.[1] ?? null,
+ newPath: match?.[2] ?? null,
+ lines: [],
+ };
+ oldLine = null;
+ newLine = null;
+ continue;
+ }
+
+ if (!current) {
+ if (rawLine.trim().length === 0) {
+ continue;
+ }
+ current = { oldPath: null, newPath: null, lines: [] };
+ }
+
+ const oldPath = parseDiffPath(rawLine, "--- ");
+ if (oldPath !== null || rawLine === "--- /dev/null") {
+ current.oldPath = oldPath;
+ continue;
+ }
+
+ const newPath = parseDiffPath(rawLine, "+++ ");
+ if (newPath !== null || rawLine === "+++ /dev/null") {
+ current.newPath = newPath;
+ continue;
+ }
+
+ const hunk = parseHunkStart(rawLine);
+ if (hunk) {
+ oldLine = hunk.oldLine;
+ newLine = hunk.newLine;
+ current.lines.push({
+ id: `${current.lines.length}:hunk`,
+ type: "hunk",
+ oldLine: null,
+ newLine: null,
+ content: rawLine,
+ });
+ continue;
+ }
+
+ if (oldLine === null || newLine === null) {
+ current.lines.push({
+ id: `${current.lines.length}:meta`,
+ type: "meta",
+ oldLine: null,
+ newLine: null,
+ content: rawLine,
+ });
+ continue;
+ }
+
+ const marker = rawLine[0];
+ const content = rawLine.length > 0 ? rawLine.slice(1) : "";
+ if (marker === "+") {
+ current.lines.push({
+ id: `${current.lines.length}:add:${newLine}`,
+ type: "add",
+ oldLine: null,
+ newLine,
+ content,
+ });
+ newLine += 1;
+ } else if (marker === "-") {
+ current.lines.push({
+ id: `${current.lines.length}:delete:${oldLine}`,
+ type: "delete",
+ oldLine,
+ newLine: null,
+ content,
+ });
+ oldLine += 1;
+ } else {
+ current.lines.push({
+ id: `${current.lines.length}:context:${oldLine}:${newLine}`,
+ type: "context",
+ oldLine,
+ newLine,
+ content: marker === " " ? content : rawLine,
+ });
+ oldLine += 1;
+ newLine += 1;
+ }
+ }
+
+ pushCurrent();
+ return files.filter((file) => file.lines.length > 0 || file.oldPath || file.newPath);
+}
diff --git a/apps/mobile/src/features/threads/review/reviewCommentSelection.ts b/apps/mobile/src/features/threads/review/reviewCommentSelection.ts
new file mode 100644
index 0000000000..0ffff8d186
--- /dev/null
+++ b/apps/mobile/src/features/threads/review/reviewCommentSelection.ts
@@ -0,0 +1,154 @@
+import { useSyncExternalStore } from "react";
+
+import type { ReviewRenderableLineRow } from "./reviewModel";
+
+export interface ReviewCommentTarget {
+ readonly sectionTitle: string;
+ readonly filePath: string;
+ readonly lines: ReadonlyArray;
+ readonly startIndex: number;
+ readonly endIndex: number;
+}
+
+let currentTarget: ReviewCommentTarget | null = null;
+const listeners = new Set<() => void>();
+
+function emitChange() {
+ listeners.forEach((listener) => listener());
+}
+
+export function subscribeReviewCommentTarget(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+export function getReviewCommentTarget(): ReviewCommentTarget | null {
+ return currentTarget;
+}
+
+export function setReviewCommentTarget(target: ReviewCommentTarget | null) {
+ currentTarget = target;
+ emitChange();
+}
+
+export function clearReviewCommentTarget() {
+ currentTarget = null;
+ emitChange();
+}
+
+export function useReviewCommentTarget(): ReviewCommentTarget | null {
+ return useSyncExternalStore(
+ subscribeReviewCommentTarget,
+ getReviewCommentTarget,
+ getReviewCommentTarget,
+ );
+}
+
+export function getSelectedReviewCommentLines(
+ target: ReviewCommentTarget,
+): ReadonlyArray {
+ return target.lines.slice(target.startIndex, target.endIndex + 1);
+}
+
+export function getReviewUnifiedLineNumber(line: ReviewRenderableLineRow): number | null {
+ return line.newLineNumber ?? line.oldLineNumber;
+}
+
+export function formatReviewLineLabel(line: ReviewRenderableLineRow): string {
+ if (line.newLineNumber !== null) {
+ return `new line ${line.newLineNumber}`;
+ }
+ if (line.oldLineNumber !== null) {
+ return `old line ${line.oldLineNumber}`;
+ }
+ return "file";
+}
+
+export function getReviewChangeMarker(change: ReviewRenderableLineRow["change"]): string {
+ if (change === "add") return "+";
+ if (change === "delete") return "-";
+ return " ";
+}
+
+export function buildReviewCommentTarget(
+ target: Pick,
+ anchorIndex: number,
+ lineIndex: number,
+): ReviewCommentTarget {
+ return {
+ sectionTitle: target.sectionTitle,
+ filePath: target.filePath,
+ lines: target.lines,
+ startIndex: Math.min(anchorIndex, lineIndex),
+ endIndex: Math.max(anchorIndex, lineIndex),
+ };
+}
+
+export function formatReviewSelectedRangeLabel(target: ReviewCommentTarget): string {
+ const lines = getSelectedReviewCommentLines(target);
+ const firstLine = lines[0]!;
+ const lastLine = lines[lines.length - 1]!;
+ const firstNumber = getReviewUnifiedLineNumber(firstLine);
+ const lastNumber = getReviewUnifiedLineNumber(lastLine);
+
+ if (firstNumber === null || lastNumber === null) {
+ return lines.length === 1 ? "line" : `${lines.length} lines`;
+ }
+
+ const firstMarker = getReviewChangeMarker(firstLine.change).trim();
+ const consistentMarker =
+ lines.every((line) => line.change === firstLine.change) && firstMarker.length > 0
+ ? getReviewChangeMarker(firstLine.change)
+ : "";
+
+ if (firstNumber === lastNumber) {
+ return `${consistentMarker}${firstNumber}`;
+ }
+
+ return `${consistentMarker}${firstNumber} to ${consistentMarker}${lastNumber}`;
+}
+
+function getDiffHunkRange(
+ selectedLines: ReadonlyArray,
+ key: "oldLineNumber" | "newLineNumber",
+): {
+ readonly start: number;
+ readonly count: number;
+} {
+ const numberedLines = selectedLines.filter((line) => line[key] !== null);
+ if (numberedLines.length === 0) {
+ return { start: 0, count: 0 };
+ }
+
+ return {
+ start: numberedLines[0]![key] ?? 0,
+ count: numberedLines.length,
+ };
+}
+
+function formatReviewSelectedDiff(target: ReviewCommentTarget): string {
+ const selectedLines = getSelectedReviewCommentLines(target);
+ const oldRange = getDiffHunkRange(selectedLines, "oldLineNumber");
+ const newRange = getDiffHunkRange(selectedLines, "newLineNumber");
+ const diffBody = selectedLines
+ .map((line) => `${getReviewChangeMarker(line.change)}${line.content}`)
+ .join("\n");
+
+ return [
+ `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
+ diffBody.length > 0 ? diffBody : " ",
+ ].join("\n");
+}
+
+export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string {
+ return [
+ "",
+ comment.trim(),
+ "```diff",
+ formatReviewSelectedDiff(target),
+ "```",
+ "",
+ ].join("\n");
+}
diff --git a/apps/mobile/src/features/threads/review/reviewModel.test.ts b/apps/mobile/src/features/threads/review/reviewModel.test.ts
new file mode 100644
index 0000000000..295ba871a2
--- /dev/null
+++ b/apps/mobile/src/features/threads/review/reviewModel.test.ts
@@ -0,0 +1,174 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ MessageId,
+ TurnId,
+ type GitReviewDiffSection,
+ type OrchestrationCheckpointSummary,
+} from "@t3tools/contracts";
+
+import {
+ buildReviewParsedDiff,
+ buildReviewSectionItems,
+ getDefaultReviewSectionId,
+ getReviewSectionIdForCheckpoint,
+} from "./reviewModel";
+
+function makeCheckpoint(
+ input: Partial &
+ Pick,
+): OrchestrationCheckpointSummary {
+ return {
+ checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
+ status: "ready",
+ files: [],
+ assistantMessageId: MessageId.make(`msg-${input.checkpointTurnCount}`),
+ ...input,
+ };
+}
+
+describe("buildReviewSectionItems", () => {
+ it("keeps one chip per checkpoint and appends git sources", () => {
+ const checkpoints = [
+ makeCheckpoint({
+ turnId: TurnId.make("turn-1"),
+ checkpointTurnCount: 1,
+ completedAt: "2026-04-01T00:00:00.000Z",
+ }),
+ makeCheckpoint({
+ turnId: TurnId.make("turn-2"),
+ checkpointTurnCount: 2,
+ completedAt: "2026-04-02T00:00:00.000Z",
+ }),
+ ];
+ const gitSections: GitReviewDiffSection[] = [
+ {
+ kind: "dirty",
+ title: "Dirty worktree",
+ baseRef: "HEAD",
+ headRef: null,
+ diff: "diff --git a/a.ts b/a.ts",
+ },
+ {
+ kind: "base",
+ title: "Against main",
+ baseRef: "main",
+ headRef: "feature",
+ diff: "diff --git a/a.ts b/a.ts",
+ },
+ ];
+
+ const loadedTurnId = getReviewSectionIdForCheckpoint(checkpoints[0]);
+ const items = buildReviewSectionItems({
+ checkpoints,
+ gitSections,
+ turnDiffById: {
+ [loadedTurnId]: "diff --git a/loaded.ts b/loaded.ts",
+ },
+ loadingTurnIds: {
+ [getReviewSectionIdForCheckpoint(checkpoints[1])]: true,
+ },
+ });
+
+ expect(items.map((item) => item.id)).toEqual(["turn:2", "turn:1", "git:dirty", "git:base"]);
+ expect(items[0]).toMatchObject({ isLoading: true, diff: null });
+ expect(items[1]).toMatchObject({
+ isLoading: false,
+ diff: expect.stringContaining("loaded.ts"),
+ });
+ expect(getDefaultReviewSectionId(items)).toBe("turn:2");
+ });
+});
+
+describe("buildReviewParsedDiff", () => {
+ it("builds renderable rows from a unified patch", () => {
+ const parsed = buildReviewParsedDiff(
+ [
+ "diff --git a/apps/mobile/src/a.ts b/apps/mobile/src/a.ts",
+ "index 1111111..2222222 100644",
+ "--- a/apps/mobile/src/a.ts",
+ "+++ b/apps/mobile/src/a.ts",
+ "@@ -1,2 +1,3 @@",
+ "-const before = 1;",
+ "+const after = 2;",
+ "+console.log(after);",
+ " return true;",
+ ].join("\n"),
+ "unit",
+ );
+
+ expect(parsed.kind).toBe("files");
+ if (parsed.kind !== "files") {
+ return;
+ }
+
+ expect(parsed.fileCount).toBe(1);
+ expect(parsed.additions).toBe(2);
+ expect(parsed.deletions).toBe(1);
+ expect(parsed.files[0]).toMatchObject({
+ path: "apps/mobile/src/a.ts",
+ additions: 2,
+ deletions: 1,
+ });
+ expect(parsed.files[0]?.rows).toEqual([
+ expect.objectContaining({ kind: "hunk", header: "@@ -1,2 +1,3 @@" }),
+ expect.objectContaining({
+ kind: "line",
+ change: "delete",
+ oldLineNumber: 1,
+ newLineNumber: null,
+ content: "const before = 1;",
+ }),
+ expect.objectContaining({
+ kind: "line",
+ change: "add",
+ oldLineNumber: null,
+ newLineNumber: 1,
+ content: "const after = 2;",
+ }),
+ expect.objectContaining({
+ kind: "line",
+ change: "add",
+ oldLineNumber: null,
+ newLineNumber: 2,
+ content: "console.log(after);",
+ }),
+ expect.objectContaining({
+ kind: "line",
+ change: "context",
+ oldLineNumber: 2,
+ newLineNumber: 3,
+ content: "return true;",
+ }),
+ ]);
+ });
+
+ it("treats truncated patches as partial diffs instead of failing", () => {
+ const parsed = buildReviewParsedDiff(
+ [
+ "diff --git a/apps/mobile/src/a.ts b/apps/mobile/src/a.ts",
+ "index 1111111..2222222 100644",
+ "--- a/apps/mobile/src/a.ts",
+ "+++ b/apps/mobile/src/a.ts",
+ "@@ -1 +1,2 @@",
+ " const before = 1;",
+ "+const after = 2;",
+ "",
+ "[truncated]",
+ ].join("\n"),
+ "unit-truncated",
+ );
+
+ expect(parsed.kind).toBe("files");
+ if (parsed.kind !== "files") {
+ return;
+ }
+
+ expect(parsed.notice).toContain("server size cap");
+ expect(parsed.fileCount).toBe(1);
+ expect(parsed.files[0]?.rows[0]).toMatchObject({
+ kind: "hunk",
+ header: "@@ -1,1 +1,2 @@",
+ });
+ });
+});
diff --git a/apps/mobile/src/features/threads/review/reviewModel.ts b/apps/mobile/src/features/threads/review/reviewModel.ts
new file mode 100644
index 0000000000..7b289fbc77
--- /dev/null
+++ b/apps/mobile/src/features/threads/review/reviewModel.ts
@@ -0,0 +1,380 @@
+import { parsePatchFiles, type ChangeTypes, type FileDiffMetadata } from "@pierre/diffs/utils";
+import type { GitReviewDiffSection, OrchestrationCheckpointSummary } from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+
+export type ReviewSectionKind = "turn" | "dirty" | "base";
+
+export interface ReviewSectionItem {
+ readonly id: string;
+ readonly kind: ReviewSectionKind;
+ readonly title: string;
+ readonly subtitle: string | null;
+ readonly diff: string | null;
+ readonly isLoading: boolean;
+}
+
+export interface ReviewRenderableHunkRow {
+ readonly kind: "hunk";
+ readonly id: string;
+ readonly header: string;
+ readonly context: string | null;
+}
+
+export interface ReviewRenderableLineRow {
+ readonly kind: "line";
+ readonly id: string;
+ readonly change: "context" | "add" | "delete";
+ readonly oldLineNumber: number | null;
+ readonly newLineNumber: number | null;
+ readonly content: string;
+ readonly additionTokenIndex: number | null;
+ readonly deletionTokenIndex: number | null;
+}
+
+export type ReviewRenderableRow = ReviewRenderableHunkRow | ReviewRenderableLineRow;
+
+export interface ReviewRenderableFile {
+ readonly id: string;
+ readonly cacheKey: string;
+ readonly path: string;
+ readonly previousPath: string | null;
+ readonly changeType: ChangeTypes;
+ readonly additions: number;
+ readonly deletions: number;
+ readonly languageHint: string | null;
+ readonly additionLines: ReadonlyArray;
+ readonly deletionLines: ReadonlyArray;
+ readonly rows: ReadonlyArray;
+}
+
+export type ReviewParsedDiff =
+ | {
+ readonly kind: "empty";
+ }
+ | {
+ readonly kind: "raw";
+ readonly text: string;
+ readonly reason: string;
+ readonly notice: string | null;
+ }
+ | {
+ readonly kind: "files";
+ readonly files: ReadonlyArray;
+ readonly fileCount: number;
+ readonly additions: number;
+ readonly deletions: number;
+ readonly notice: string | null;
+ };
+
+function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
+ return `Turn ${checkpoint.checkpointTurnCount}`;
+}
+
+function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
+ const fileCount = checkpoint.files.length;
+ if (checkpoint.status !== "ready") {
+ return `Diff ${checkpoint.status}`;
+ }
+ return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
+}
+
+function compareCheckpointTurnCountDescending(
+ left: OrchestrationCheckpointSummary,
+ right: OrchestrationCheckpointSummary,
+): -1 | 0 | 1 {
+ if (left.checkpointTurnCount === right.checkpointTurnCount) {
+ return 0;
+ }
+
+ return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
+}
+
+const readyCheckpointOrder = Order.make(
+ compareCheckpointTurnCountDescending,
+);
+
+function gitSubtitle(section: GitReviewDiffSection): string | null {
+ if (section.kind === "dirty") {
+ return "Tracked, staged, and untracked worktree changes";
+ }
+ if (section.baseRef) {
+ return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`;
+ }
+ return "Base branch unavailable";
+}
+
+function stripGitPrefix(pathValue: string | undefined): string | null {
+ if (!pathValue) {
+ return null;
+ }
+ if (pathValue.startsWith("a/") || pathValue.startsWith("b/")) {
+ return pathValue.slice(2);
+ }
+ return pathValue;
+}
+
+function stripTrailingNewline(value: string): string {
+ return value.endsWith("\n") ? value.slice(0, -1) : value;
+}
+
+function splitTruncationMarker(diff: string): {
+ readonly text: string;
+ readonly truncated: boolean;
+} {
+ const trimmed = diff.trimEnd();
+ if (!trimmed.endsWith("[truncated]")) {
+ return { text: trimmed, truncated: false };
+ }
+
+ return {
+ text: trimmed.replace(/\n*\[truncated\]\s*$/, "").trimEnd(),
+ truncated: true,
+ };
+}
+
+function runDiffParserSilently(callback: () => T): T {
+ const originalConsoleError = console.error;
+ console.error = () => undefined;
+ try {
+ return callback();
+ } finally {
+ console.error = originalConsoleError;
+ }
+}
+
+const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
+const FNV_PRIME_32 = 0x01000193;
+const SECONDARY_HASH_SEED = 0x9e3779b9;
+const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
+
+function fnv1a32(input: string, seed: number, multiplier: number): number {
+ let hash = seed >>> 0;
+ for (let index = 0; index < input.length; index += 1) {
+ hash ^= input.charCodeAt(index);
+ hash = Math.imul(hash, multiplier) >>> 0;
+ }
+ return hash >>> 0;
+}
+
+function buildPatchCacheKey(patch: string, scope: string): string {
+ const normalizedPatch = patch.trim();
+ const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
+ const secondary = fnv1a32(
+ normalizedPatch,
+ SECONDARY_HASH_SEED,
+ SECONDARY_HASH_MULTIPLIER,
+ ).toString(36);
+ return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
+}
+
+function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
+ return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
+}
+
+function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray {
+ const rows: ReviewRenderableRow[] = [];
+ let rowIndex = 0;
+
+ file.hunks.forEach((hunk, hunkIndex) => {
+ rows.push({
+ kind: "hunk",
+ id: `${file.cacheKey ?? file.name}:hunk:${hunkIndex}`,
+ header: fallbackHunkHeader(hunk),
+ context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null,
+ });
+
+ let deletionLineNumber = hunk.deletionStart;
+ let additionLineNumber = hunk.additionStart;
+ let deletionTokenIndex = hunk.deletionLineIndex;
+ let additionTokenIndex = hunk.additionLineIndex;
+
+ hunk.hunkContent.forEach((segment) => {
+ if (segment.type === "context") {
+ for (let index = 0; index < segment.lines; index += 1) {
+ rows.push({
+ kind: "line",
+ id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
+ change: "context",
+ oldLineNumber: deletionLineNumber,
+ newLineNumber: additionLineNumber,
+ content: stripTrailingNewline(
+ file.additionLines[additionTokenIndex] ??
+ file.deletionLines[deletionTokenIndex] ??
+ "",
+ ),
+ additionTokenIndex,
+ deletionTokenIndex,
+ });
+ deletionLineNumber += 1;
+ additionLineNumber += 1;
+ deletionTokenIndex += 1;
+ additionTokenIndex += 1;
+ }
+ return;
+ }
+
+ for (let index = 0; index < segment.deletions; index += 1) {
+ rows.push({
+ kind: "line",
+ id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
+ change: "delete",
+ oldLineNumber: deletionLineNumber,
+ newLineNumber: null,
+ content: stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""),
+ additionTokenIndex: null,
+ deletionTokenIndex,
+ });
+ deletionLineNumber += 1;
+ deletionTokenIndex += 1;
+ }
+
+ for (let index = 0; index < segment.additions; index += 1) {
+ rows.push({
+ kind: "line",
+ id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
+ change: "add",
+ oldLineNumber: null,
+ newLineNumber: additionLineNumber,
+ content: stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""),
+ additionTokenIndex,
+ deletionTokenIndex: null,
+ });
+ additionLineNumber += 1;
+ additionTokenIndex += 1;
+ }
+ });
+ });
+
+ return rows;
+}
+
+function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
+ const path = stripGitPrefix(file.name) ?? stripGitPrefix(file.prevName) ?? file.name;
+ const previousPath = stripGitPrefix(file.prevName);
+ const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);
+ const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0);
+ const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;
+
+ return {
+ id: cacheKey,
+ cacheKey,
+ path,
+ previousPath,
+ changeType: file.type,
+ additions,
+ deletions,
+ languageHint: file.lang ?? null,
+ additionLines: file.additionLines,
+ deletionLines: file.deletionLines,
+ rows: buildRenderableRows(file),
+ };
+}
+
+export function getReviewSectionIdForCheckpoint(
+ checkpoint: Pick,
+): string {
+ return `turn:${checkpoint.checkpointTurnCount}`;
+}
+
+export function getReadyReviewCheckpoints(
+ checkpoints: ReadonlyArray,
+): ReadonlyArray {
+ return Arr.sort(
+ checkpoints.filter((checkpoint) => checkpoint.status === "ready"),
+ readyCheckpointOrder,
+ );
+}
+
+export function buildReviewSectionItems(input: {
+ readonly checkpoints: ReadonlyArray;
+ readonly gitSections: ReadonlyArray;
+ readonly turnDiffById: Readonly>;
+ readonly loadingTurnIds: Readonly>;
+}): ReadonlyArray {
+ const turnItems = getReadyReviewCheckpoints(input.checkpoints).map(
+ (checkpoint) => {
+ const id = getReviewSectionIdForCheckpoint(checkpoint);
+ return {
+ id,
+ kind: "turn",
+ title: checkpointTitle(checkpoint),
+ subtitle: checkpointSubtitle(checkpoint),
+ diff: input.turnDiffById[id] ?? null,
+ isLoading: input.loadingTurnIds[id] === true,
+ };
+ },
+ );
+
+ const gitItems = input.gitSections.map((section) => ({
+ id: `git:${section.kind}`,
+ kind: section.kind,
+ title: section.title,
+ subtitle: gitSubtitle(section),
+ diff: section.diff,
+ isLoading: false,
+ }));
+
+ return [...turnItems, ...gitItems];
+}
+
+export function getDefaultReviewSectionId(
+ sections: ReadonlyArray,
+): string | null {
+ return sections[0]?.id ?? null;
+}
+
+export function buildReviewParsedDiff(
+ diff: string | null | undefined,
+ cacheScope: string,
+): ReviewParsedDiff {
+ const normalized = diff?.trim();
+ if (!normalized) {
+ return { kind: "empty" };
+ }
+
+ const { text, truncated } = splitTruncationMarker(normalized);
+ if (text.length === 0) {
+ return { kind: "empty" };
+ }
+
+ const notice = truncated
+ ? "Diff output hit the server size cap. Showing the available excerpt."
+ : null;
+
+ try {
+ const parsedPatches = runDiffParserSilently(() =>
+ parsePatchFiles(text, buildPatchCacheKey(text, cacheScope)),
+ );
+ const files = parsedPatches.flatMap((patch) => patch.files).map(mapRenderableFile);
+
+ if (files.length === 0) {
+ return {
+ kind: "raw",
+ text,
+ reason: truncated
+ ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
+ : "Unsupported diff format. Showing raw patch.",
+ notice,
+ };
+ }
+
+ return {
+ kind: "files",
+ files,
+ fileCount: files.length,
+ additions: files.reduce((total, file) => total + file.additions, 0),
+ deletions: files.reduce((total, file) => total + file.deletions, 0),
+ notice,
+ };
+ } catch {
+ return {
+ kind: "raw",
+ text,
+ reason: truncated
+ ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
+ : "Failed to parse patch. Showing raw patch.",
+ notice,
+ };
+ }
+}
diff --git a/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts
new file mode 100644
index 0000000000..722cb4ea7a
--- /dev/null
+++ b/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts
@@ -0,0 +1,131 @@
+import { getFiletypeFromFileName } from "@pierre/diffs/utils";
+
+import type { ReviewRenderableFile } from "./reviewModel";
+
+export type ReviewDiffTheme = "light" | "dark";
+
+export interface ReviewHighlightedToken {
+ readonly content: string;
+ readonly color: string | null;
+ readonly fontStyle: number | null;
+}
+
+export interface ReviewHighlightedFile {
+ readonly additionLines: ReadonlyArray>;
+ readonly deletionLines: ReadonlyArray>;
+}
+
+const SHIKI_THEME_BY_SCHEME = {
+ light: "github-light-default",
+ dark: "github-dark-default",
+} as const;
+
+const highlightCache = new Map>();
+const loadedLanguages = new Set(["text"]);
+type ShikiHighlighter = {
+ loadLanguage: (...langs: string[]) => Promise;
+ codeToTokensBase: (
+ code: string,
+ options: { readonly lang: string; readonly theme: string },
+ ) => Promise>>;
+};
+let highlighterPromise: Promise | null = null;
+
+function cleanLastNewline(value: string): string {
+ return value.endsWith("\n") ? value.slice(0, -1) : value;
+}
+
+function joinPatchLines(lines: ReadonlyArray): string {
+ if (lines.length === 0) {
+ return "";
+ }
+
+ return cleanLastNewline(lines.join(""));
+}
+
+async function getHighlighter() {
+ if (!highlighterPromise) {
+ highlighterPromise = import("shiki").then(
+ async ({ createHighlighter, createJavaScriptRegexEngine }) => {
+ const highlighter = await createHighlighter({
+ themes: [SHIKI_THEME_BY_SCHEME.light, SHIKI_THEME_BY_SCHEME.dark],
+ langs: [],
+ engine: createJavaScriptRegexEngine(),
+ });
+ return highlighter as unknown as ShikiHighlighter;
+ },
+ );
+ }
+
+ return highlighterPromise as Promise;
+}
+
+async function resolveLanguage(file: ReviewRenderableFile): Promise {
+ const candidate = file.languageHint ?? getFiletypeFromFileName(file.path);
+ if (!candidate || candidate === "text" || candidate === "ansi") {
+ return "text";
+ }
+
+ const highlighter = await getHighlighter();
+ if (!loadedLanguages.has(candidate)) {
+ try {
+ await highlighter.loadLanguage(candidate);
+ loadedLanguages.add(candidate);
+ } catch {
+ return "text";
+ }
+ }
+
+ return candidate;
+}
+
+function normalizeHighlightedLines(
+ tokenLines: ReadonlyArray>,
+): ReadonlyArray> {
+ return tokenLines.map((line) =>
+ line.map((token) => ({
+ content: token.content,
+ color: token.color ?? null,
+ fontStyle: token.fontStyle ?? null,
+ })),
+ );
+}
+
+async function highlightLines(
+ code: string,
+ language: string,
+ theme: string,
+): Promise>> {
+ if (code.length === 0) {
+ return [];
+ }
+
+ const highlighter = await getHighlighter();
+ const tokenLines = await highlighter.codeToTokensBase(code, { lang: language, theme });
+ return normalizeHighlightedLines(tokenLines);
+}
+
+export async function highlightReviewFile(
+ file: ReviewRenderableFile,
+ theme: ReviewDiffTheme,
+): Promise {
+ const shikiTheme = SHIKI_THEME_BY_SCHEME[theme];
+ const cacheKey = `${shikiTheme}:${file.cacheKey}`;
+ const cached = highlightCache.get(cacheKey);
+ if (cached) {
+ return cached;
+ }
+
+ const promise = (async () => {
+ const language = await resolveLanguage(file);
+ const [additionLines, deletionLines] = await Promise.all([
+ highlightLines(joinPatchLines(file.additionLines), language, shikiTheme),
+ highlightLines(joinPatchLines(file.deletionLines), language, shikiTheme),
+ ]);
+
+ return { additionLines, deletionLines };
+ })();
+
+ highlightCache.set(cacheKey, promise);
+ return promise;
+}
diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts
new file mode 100644
index 0000000000..4253cedbc7
--- /dev/null
+++ b/apps/mobile/src/features/threads/threadPresentation.ts
@@ -0,0 +1,53 @@
+import type { StatusTone } from "../../components/StatusPill";
+import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
+
+export function threadSortValue(thread: EnvironmentScopedThreadShell): number {
+ const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
+ return Number.isNaN(candidate) ? 0 : candidate;
+}
+
+export function threadStatusTone(thread: EnvironmentScopedThreadShell): StatusTone {
+ const status = thread.session?.status;
+ if (status === "running") {
+ return {
+ label: "Running",
+ pillClassName: "bg-orange-500/12 dark:bg-orange-500/16",
+ textClassName: "text-orange-700 dark:text-orange-300",
+ };
+ }
+ if (status === "ready") {
+ return {
+ label: "Ready",
+ pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16",
+ textClassName: "text-emerald-700 dark:text-emerald-300",
+ };
+ }
+ if (status === "starting") {
+ return {
+ label: "Starting",
+ pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
+ textClassName: "text-sky-700 dark:text-sky-300",
+ };
+ }
+ if (status === "error") {
+ return {
+ label: "Error",
+ pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
+ textClassName: "text-rose-700 dark:text-rose-300",
+ };
+ }
+ return {
+ label: "Idle",
+ pillClassName: "bg-neutral-500/10 dark:bg-neutral-500/16",
+ textClassName: "text-neutral-600 dark:text-neutral-300",
+ };
+}
+
+export function messageImageUrl(httpBaseUrl: string | null, attachmentId: string): string | null {
+ if (!httpBaseUrl) {
+ return null;
+ }
+
+ const url = new URL(`/attachments/${encodeURIComponent(attachmentId)}`, httpBaseUrl);
+ return url.toString();
+}
diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts
new file mode 100644
index 0000000000..5abc13acf6
--- /dev/null
+++ b/apps/mobile/src/features/threads/use-project-actions.ts
@@ -0,0 +1,258 @@
+import { useCallback } from "react";
+
+import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime";
+import {
+ CommandId,
+ DEFAULT_PROVIDER_INTERACTION_MODE,
+ DEFAULT_RUNTIME_MODE,
+ MessageId,
+ ThreadId,
+ type GitBranch,
+ type ModelSelection,
+ type ProviderInteractionMode,
+ type RuntimeMode,
+} from "@t3tools/contracts";
+import { buildTemporaryWorktreeBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
+
+import type { DraftComposerImageAttachment } from "../../lib/composerImages";
+import { uuidv4 } from "../../lib/uuid";
+import { environmentRuntimeManager } from "../../state/use-environment-runtime";
+import { gitBranchManager } from "../../state/use-git-branches";
+import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import {
+ getEnvironmentClient,
+ setPendingConnectionError,
+ useRemoteEnvironmentState,
+} from "../../state/use-remote-environment-registry";
+
+function useRefreshRemoteData() {
+ const { savedConnectionsById } = useRemoteEnvironmentState();
+
+ return useCallback(
+ async (environmentIds?: ReadonlyArray) => {
+ const targets = environmentIds ?? Object.keys(savedConnectionsById);
+
+ await Promise.all(
+ targets.map(async (environmentId) => {
+ const client = getEnvironmentClient(environmentId);
+ if (!client) {
+ return;
+ }
+
+ try {
+ const serverConfig = await client.server.getConfig();
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
+ ...current,
+ serverConfig,
+ connectionError: null,
+ }));
+ } catch (error) {
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
+ ...current,
+ connectionError:
+ error instanceof Error ? error.message : "Failed to refresh remote data.",
+ }));
+ }
+ }),
+ );
+ },
+ [savedConnectionsById],
+ );
+}
+
+function deriveThreadTitleFromPrompt(value: string): string {
+ const trimmed = value.trim();
+ if (trimmed.length === 0) {
+ return "New thread";
+ }
+
+ const compact = trimmed.replace(/\s+/g, " ");
+ return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
+}
+
+export function useProjectActions() {
+ const { threads } = useRemoteCatalog();
+ const refreshRemoteData = useRefreshRemoteData();
+
+ const onCreateThreadWithOptions = useCallback(
+ async (input: {
+ readonly project: EnvironmentScopedProjectShell;
+ readonly modelSelection: ModelSelection;
+ readonly envMode: "local" | "worktree";
+ readonly branch: string | null;
+ readonly worktreePath: string | null;
+ readonly runtimeMode: RuntimeMode;
+ readonly interactionMode: ProviderInteractionMode;
+ readonly initialMessageText: string;
+ readonly initialAttachments: ReadonlyArray;
+ }) => {
+ const client = getEnvironmentClient(input.project.environmentId);
+ if (!client) {
+ return null;
+ }
+
+ const threadId = ThreadId.make(uuidv4());
+ const createdAt = new Date().toISOString();
+ const initialMessageText = input.initialMessageText.trim();
+ const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
+
+ if (initialMessageText.length === 0) {
+ return null;
+ }
+ if (input.envMode === "worktree" && !input.branch) {
+ return null;
+ }
+
+ const isWorktree = input.envMode === "worktree";
+
+ await client.orchestration.dispatchCommand({
+ type: "thread.turn.start",
+ commandId: CommandId.make(uuidv4()),
+ threadId,
+ message: {
+ messageId: MessageId.make(uuidv4()),
+ role: "user",
+ text: initialMessageText,
+ attachments: input.initialAttachments,
+ },
+ modelSelection: input.modelSelection,
+ titleSeed: nextTitle,
+ runtimeMode: input.runtimeMode,
+ interactionMode: input.interactionMode,
+ bootstrap: {
+ createThread: {
+ projectId: input.project.id,
+ title: nextTitle,
+ modelSelection: input.modelSelection,
+ runtimeMode: input.runtimeMode,
+ interactionMode: input.interactionMode,
+ branch: input.branch,
+ worktreePath: isWorktree ? null : input.worktreePath,
+ createdAt,
+ },
+ ...(isWorktree
+ ? {
+ prepareWorktree: {
+ projectCwd: input.project.workspaceRoot,
+ baseBranch: input.branch!,
+ branch: buildTemporaryWorktreeBranchName(),
+ },
+ runSetupScript: true,
+ }
+ : {}),
+ },
+ createdAt: new Date().toISOString(),
+ });
+
+ await refreshRemoteData([input.project.environmentId]);
+ return {
+ environmentId: input.project.environmentId,
+ threadId,
+ };
+ },
+ [refreshRemoteData],
+ );
+
+ const onCreateThread = useCallback(
+ async (project: EnvironmentScopedProjectShell) => {
+ const latestProjectThread =
+ threads.find(
+ (thread) =>
+ thread.environmentId === project.environmentId && thread.projectId === project.id,
+ ) ?? null;
+ const modelSelection =
+ project.defaultModelSelection ?? latestProjectThread?.modelSelection ?? null;
+ if (!modelSelection) {
+ setPendingConnectionError("This project does not have a default model configured yet.");
+ return null;
+ }
+
+ return await onCreateThreadWithOptions({
+ project,
+ modelSelection,
+ envMode: "local",
+ branch: null,
+ worktreePath: null,
+ runtimeMode: DEFAULT_RUNTIME_MODE,
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ initialMessageText: "",
+ initialAttachments: [],
+ });
+ },
+ [onCreateThreadWithOptions, threads],
+ );
+
+ const onListProjectBranches = useCallback(
+ async (project: EnvironmentScopedProjectShell): Promise> => {
+ const client = getEnvironmentClient(project.environmentId);
+ if (!client) {
+ return [];
+ }
+
+ try {
+ const result = await gitBranchManager.load(
+ { environmentId: project.environmentId, cwd: project.workspaceRoot, query: null },
+ client.git,
+ { limit: 100 },
+ );
+ return (result?.branches ?? []).filter((branch) => !branch.isRemote);
+ } catch (error) {
+ setPendingConnectionError(
+ error instanceof Error ? error.message : "Failed to load branches.",
+ );
+ return [];
+ }
+ },
+ [],
+ );
+
+ const onCreateProjectWorktree = useCallback(
+ async (
+ project: EnvironmentScopedProjectShell,
+ nextWorktree: {
+ readonly baseBranch: string;
+ readonly newBranch: string;
+ },
+ ): Promise<{
+ readonly branch: string;
+ readonly worktreePath: string;
+ } | null> => {
+ const client = getEnvironmentClient(project.environmentId);
+ if (!client) {
+ return null;
+ }
+
+ try {
+ const result = await client.git.createWorktree({
+ cwd: project.workspaceRoot,
+ branch: nextWorktree.baseBranch,
+ newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
+ path: null,
+ });
+ gitBranchManager.invalidate({
+ environmentId: project.environmentId,
+ cwd: project.workspaceRoot,
+ query: null,
+ });
+ return {
+ branch: result.worktree.branch,
+ worktreePath: result.worktree.path,
+ };
+ } catch (error) {
+ setPendingConnectionError(
+ error instanceof Error ? error.message : "Failed to create worktree.",
+ );
+ return null;
+ }
+ },
+ [],
+ );
+
+ return {
+ onCreateThread,
+ onCreateThreadWithOptions,
+ onListProjectBranches,
+ onCreateProjectWorktree,
+ onRefreshProjects: refreshRemoteData,
+ };
+}
diff --git a/apps/mobile/src/features/threads/use-selected-thread-commands.ts b/apps/mobile/src/features/threads/use-selected-thread-commands.ts
new file mode 100644
index 0000000000..fc3e2711b5
--- /dev/null
+++ b/apps/mobile/src/features/threads/use-selected-thread-commands.ts
@@ -0,0 +1,259 @@
+import { useCallback, useState } from "react";
+
+import {
+ ApprovalRequestId,
+ CommandId,
+ type ModelSelection,
+ type ProviderApprovalDecision,
+ type ProviderInteractionMode,
+ type RuntimeMode,
+} from "@t3tools/contracts";
+
+import { uuidv4 } from "../../lib/uuid";
+import { environmentRuntimeManager } from "../../state/use-environment-runtime";
+import {
+ getEnvironmentClient,
+ useRemoteEnvironmentState,
+} from "../../state/use-remote-environment-registry";
+import { useThreadSelection } from "../../state/use-thread-selection";
+
+export function useSelectedThreadCommands(input: {
+ readonly activePendingUserInput: {
+ readonly requestId: ApprovalRequestId;
+ } | null;
+ readonly activePendingUserInputAnswers: Record | null;
+ readonly refreshSelectedThreadGitStatus: (options?: {
+ readonly quiet?: boolean;
+ readonly cwd?: string | null;
+ }) => Promise;
+}) {
+ const { activePendingUserInput, activePendingUserInputAnswers, refreshSelectedThreadGitStatus } =
+ input;
+ const { selectedThread } = useThreadSelection();
+ const { savedConnectionsById } = useRemoteEnvironmentState();
+ const [respondingApprovalId, setRespondingApprovalId] = useState(null);
+ const [respondingUserInputId, setRespondingUserInputId] = useState(
+ null,
+ );
+
+ const onRefresh = useCallback(async () => {
+ const targets = selectedThread
+ ? [selectedThread.environmentId]
+ : Object.keys(savedConnectionsById);
+
+ await Promise.all(
+ targets.map(async (environmentId) => {
+ const client = getEnvironmentClient(environmentId);
+ if (!client) {
+ return;
+ }
+
+ try {
+ const serverConfig = await client.server.getConfig();
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
+ ...current,
+ serverConfig,
+ connectionError: null,
+ }));
+ } catch (error) {
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
+ ...current,
+ connectionError:
+ error instanceof Error ? error.message : "Failed to refresh remote data.",
+ }));
+ }
+ }),
+ );
+
+ if (selectedThread) {
+ await refreshSelectedThreadGitStatus({ quiet: true });
+ }
+ }, [refreshSelectedThreadGitStatus, savedConnectionsById, selectedThread]);
+
+ const onUpdateThreadModelSelection = useCallback(
+ async (modelSelection: ModelSelection) => {
+ if (!selectedThread) {
+ return;
+ }
+
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return;
+ }
+
+ await client.orchestration.dispatchCommand({
+ type: "thread.meta.update",
+ commandId: CommandId.make(uuidv4()),
+ threadId: selectedThread.id,
+ modelSelection,
+ });
+ },
+ [selectedThread],
+ );
+
+ const onUpdateThreadRuntimeMode = useCallback(
+ async (runtimeMode: RuntimeMode) => {
+ if (!selectedThread) {
+ return;
+ }
+
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return;
+ }
+
+ await client.orchestration.dispatchCommand({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make(uuidv4()),
+ threadId: selectedThread.id,
+ runtimeMode,
+ createdAt: new Date().toISOString(),
+ });
+ },
+ [selectedThread],
+ );
+
+ const onUpdateThreadInteractionMode = useCallback(
+ async (interactionMode: ProviderInteractionMode) => {
+ if (!selectedThread) {
+ return;
+ }
+
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return;
+ }
+
+ await client.orchestration.dispatchCommand({
+ type: "thread.interaction-mode.set",
+ commandId: CommandId.make(uuidv4()),
+ threadId: selectedThread.id,
+ interactionMode,
+ createdAt: new Date().toISOString(),
+ });
+ },
+ [selectedThread],
+ );
+
+ const onStopThread = useCallback(async () => {
+ if (!selectedThread) {
+ return;
+ }
+
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return;
+ }
+
+ if (
+ selectedThread.session?.status !== "running" &&
+ selectedThread.session?.status !== "starting"
+ ) {
+ return;
+ }
+
+ await client.orchestration.dispatchCommand({
+ type: "thread.turn.interrupt",
+ commandId: CommandId.make(uuidv4()),
+ threadId: selectedThread.id,
+ ...(selectedThread.session?.activeTurnId
+ ? { turnId: selectedThread.session.activeTurnId }
+ : {}),
+ createdAt: new Date().toISOString(),
+ });
+ }, [selectedThread]);
+
+ const onRenameThread = useCallback(
+ async (title: string) => {
+ if (!selectedThread) {
+ return;
+ }
+
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return;
+ }
+
+ const trimmed = title.trim();
+ if (!trimmed || trimmed === selectedThread.title) {
+ return;
+ }
+
+ await client.orchestration.dispatchCommand({
+ type: "thread.meta.update",
+ commandId: CommandId.make(uuidv4()),
+ threadId: selectedThread.id,
+ title: trimmed,
+ });
+ },
+ [selectedThread],
+ );
+
+ const onRespondToApproval = useCallback(
+ async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
+ if (!selectedThread) {
+ return;
+ }
+
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return;
+ }
+
+ setRespondingApprovalId(requestId);
+ try {
+ await client.orchestration.dispatchCommand({
+ type: "thread.approval.respond",
+ commandId: CommandId.make(uuidv4()),
+ threadId: selectedThread.id,
+ requestId,
+ decision,
+ createdAt: new Date().toISOString(),
+ });
+ } finally {
+ setRespondingApprovalId((current) => (current === requestId ? null : current));
+ }
+ },
+ [selectedThread],
+ );
+
+ const onSubmitUserInput = useCallback(async () => {
+ if (!selectedThread || !activePendingUserInput || !activePendingUserInputAnswers) {
+ return;
+ }
+
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return;
+ }
+
+ setRespondingUserInputId(activePendingUserInput.requestId);
+ try {
+ await client.orchestration.dispatchCommand({
+ type: "thread.user-input.respond",
+ commandId: CommandId.make(uuidv4()),
+ threadId: selectedThread.id,
+ requestId: activePendingUserInput.requestId,
+ answers: activePendingUserInputAnswers,
+ createdAt: new Date().toISOString(),
+ });
+ } finally {
+ setRespondingUserInputId((current) =>
+ current === activePendingUserInput.requestId ? null : current,
+ );
+ }
+ }, [activePendingUserInput, activePendingUserInputAnswers, selectedThread]);
+
+ return {
+ respondingApprovalId,
+ respondingUserInputId,
+ onRefresh,
+ onUpdateThreadModelSelection,
+ onUpdateThreadRuntimeMode,
+ onUpdateThreadInteractionMode,
+ onRenameThread,
+ onStopThread,
+ onRespondToApproval,
+ onSubmitUserInput,
+ };
+}
diff --git a/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts b/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts
new file mode 100644
index 0000000000..283c530554
--- /dev/null
+++ b/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts
@@ -0,0 +1,341 @@
+import { useCallback, useEffect } from "react";
+
+import {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+ type GitActionRequestInput,
+} from "@t3tools/client-runtime";
+import {
+ CommandId,
+ type GitBranch,
+ type GitRunStackedActionResult,
+ ThreadId,
+} from "@t3tools/contracts";
+import {
+ dedupeRemoteBranchesWithLocalMatches,
+ sanitizeFeatureBranchName,
+} from "@t3tools/shared/git";
+
+import { uuidv4 } from "../../lib/uuid";
+import {
+ getEnvironmentClient,
+ setPendingConnectionError,
+} from "../../state/use-remote-environment-registry";
+import { gitActionManager, showGitActionResult } from "../../state/use-git-action-state";
+import { gitBranchManager } from "../../state/use-git-branches";
+import { gitStatusManager } from "../../state/use-git-status";
+import { useThreadSelection } from "../../state/use-thread-selection";
+
+export function useSelectedThreadGitActions() {
+ const { selectedThread, selectedThreadProject } = useThreadSelection();
+
+ const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
+
+ const updateThreadGitContext = useCallback(
+ async (
+ thread: NonNullable,
+ nextState: {
+ readonly branch?: string | null;
+ readonly worktreePath?: string | null;
+ },
+ ) => {
+ const client = getEnvironmentClient(thread.environmentId);
+ if (!client) {
+ return;
+ }
+
+ await client.orchestration.dispatchCommand({
+ type: "thread.meta.update",
+ commandId: CommandId.make(uuidv4()),
+ threadId: ThreadId.make(thread.id),
+ ...(nextState.branch !== undefined ? { branch: nextState.branch } : {}),
+ ...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}),
+ });
+ },
+ [],
+ );
+
+ const refreshSelectedThreadGitStatus = useCallback(
+ async (options?: { readonly quiet?: boolean; readonly cwd?: string | null }) => {
+ if (!selectedThread || !selectedThreadProject) {
+ return null;
+ }
+
+ const cwd =
+ options?.cwd ?? selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot;
+ if (!cwd) {
+ return null;
+ }
+
+ try {
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return null;
+ }
+
+ const status = await gitActionManager.refreshStatus(
+ { environmentId: selectedThread.environmentId, cwd },
+ client.git,
+ options,
+ );
+ setPendingConnectionError(null);
+ return status;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to refresh git status.";
+ setPendingConnectionError(message);
+ return null;
+ }
+ },
+ [selectedThread, selectedThreadProject],
+ );
+
+ useEffect(() => {
+ if (!selectedThread || !selectedThreadProject) {
+ return;
+ }
+
+ void refreshSelectedThreadGitStatus({ quiet: true });
+ }, [refreshSelectedThreadGitStatus, selectedThread, selectedThreadProject]);
+
+ const runSelectedThreadGitMutation = useCallback(
+ async (
+ operation: (input: {
+ readonly thread: EnvironmentScopedThreadShell;
+ readonly project: EnvironmentScopedProjectShell;
+ readonly cwd: string;
+ }) => Promise,
+ ): Promise => {
+ if (!selectedThread || !selectedThreadProject) {
+ return null;
+ }
+
+ const cwd = selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot;
+ if (!cwd) {
+ return null;
+ }
+
+ try {
+ setPendingConnectionError(null);
+ return await operation({
+ thread: selectedThread,
+ project: selectedThreadProject,
+ cwd,
+ });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Git action failed.";
+ setPendingConnectionError(message);
+ showGitActionResult({ type: "error", title: "Git action failed", description: message });
+ return null;
+ }
+ },
+ [selectedThread, selectedThreadProject],
+ );
+
+ const refreshSelectedThreadBranches = useCallback(async (): Promise> => {
+ if (!selectedThread || !selectedThreadProject || !selectedThreadGitRootCwd) {
+ return [];
+ }
+
+ const client = getEnvironmentClient(selectedThread.environmentId);
+ if (!client) {
+ return [];
+ }
+
+ try {
+ const result = await gitBranchManager.load(
+ { environmentId: selectedThread.environmentId, cwd: selectedThreadGitRootCwd, query: null },
+ client.git,
+ { limit: 100 },
+ );
+ return dedupeRemoteBranchesWithLocalMatches(result?.branches ?? []).filter(
+ (branch) => !branch.isRemote,
+ );
+ } catch (error) {
+ setPendingConnectionError(
+ error instanceof Error ? error.message : "Failed to load branches.",
+ );
+ return [];
+ }
+ }, [selectedThread, selectedThreadGitRootCwd, selectedThreadProject]);
+
+ const syncSelectedThreadBranchState = useCallback(
+ async (input: {
+ readonly thread: EnvironmentScopedThreadShell;
+ readonly cwd: string;
+ readonly branchRootCwd?: string | null;
+ readonly nextThreadState?: {
+ readonly branch?: string | null;
+ readonly worktreePath?: string | null;
+ };
+ }) => {
+ if (input.nextThreadState) {
+ await updateThreadGitContext(input.thread, input.nextThreadState);
+ }
+
+ const branchRootCwd = input.branchRootCwd ?? selectedThreadProject?.workspaceRoot ?? null;
+ if (branchRootCwd) {
+ gitBranchManager.invalidate({
+ environmentId: input.thread.environmentId,
+ cwd: branchRootCwd,
+ query: null,
+ });
+ await refreshSelectedThreadBranches();
+ }
+
+ await refreshSelectedThreadGitStatus({ quiet: true, cwd: input.cwd });
+ },
+ [
+ refreshSelectedThreadBranches,
+ refreshSelectedThreadGitStatus,
+ selectedThreadProject?.workspaceRoot,
+ updateThreadGitContext,
+ ],
+ );
+
+ const onCheckoutSelectedThreadBranch = useCallback(
+ async (branch: string) => {
+ await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
+ const result = await gitActionManager.checkout(
+ { environmentId: thread.environmentId, cwd },
+ { branch },
+ );
+ await syncSelectedThreadBranchState({
+ thread,
+ cwd,
+ nextThreadState: {
+ branch: result?.branch ?? thread.branch,
+ worktreePath: thread.worktreePath,
+ },
+ });
+ });
+ },
+ [runSelectedThreadGitMutation, syncSelectedThreadBranchState],
+ );
+
+ const onCreateSelectedThreadBranch = useCallback(
+ async (branch: string) => {
+ await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
+ const result = await gitActionManager.createBranch(
+ { environmentId: thread.environmentId, cwd },
+ {
+ branch,
+ checkout: true,
+ },
+ );
+ await syncSelectedThreadBranchState({
+ thread,
+ cwd,
+ nextThreadState: {
+ branch: result?.branch ?? thread.branch,
+ worktreePath: thread.worktreePath,
+ },
+ });
+ });
+ },
+ [runSelectedThreadGitMutation, syncSelectedThreadBranchState],
+ );
+
+ const onCreateSelectedThreadWorktree = useCallback(
+ async (nextWorktree: { readonly baseBranch: string; readonly newBranch: string }) => {
+ await runSelectedThreadGitMutation(async ({ thread, project }) => {
+ const result = await gitActionManager.createWorktree(
+ { environmentId: thread.environmentId, cwd: project.workspaceRoot },
+ {
+ branch: nextWorktree.baseBranch,
+ newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
+ path: null,
+ },
+ );
+ if (!result) {
+ return;
+ }
+
+ await syncSelectedThreadBranchState({
+ thread,
+ cwd: result.worktree.path,
+ branchRootCwd: project.workspaceRoot,
+ nextThreadState: {
+ branch: result.worktree.branch,
+ worktreePath: result.worktree.path,
+ },
+ });
+ });
+ },
+ [runSelectedThreadGitMutation, syncSelectedThreadBranchState],
+ );
+
+ const onPullSelectedThreadBranch = useCallback(async () => {
+ await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
+ const result = await gitActionManager.pull({ environmentId: thread.environmentId, cwd });
+ await refreshSelectedThreadGitStatus({ quiet: true, cwd });
+ if (result) {
+ showGitActionResult({
+ type: "success",
+ title:
+ result.status === "skipped_up_to_date"
+ ? "Already up to date"
+ : `Pulled latest on ${result.branch}`,
+ });
+ }
+ });
+ }, [refreshSelectedThreadGitStatus, runSelectedThreadGitMutation]);
+
+ const onRunSelectedThreadGitAction = useCallback(
+ async (input: GitActionRequestInput): Promise => {
+ return await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
+ const result = await gitActionManager.runStackedAction(
+ { environmentId: thread.environmentId, cwd },
+ {
+ actionId: uuidv4(),
+ action: input.action,
+ ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
+ ...(input.featureBranch ? { featureBranch: input.featureBranch } : {}),
+ ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
+ },
+ {
+ gitStatus: gitStatusManager.getSnapshot({
+ environmentId: thread.environmentId,
+ cwd,
+ }).data,
+ },
+ );
+ if (!result) {
+ return null;
+ }
+
+ showGitActionResult({
+ type: "success",
+ title: result.toast.title,
+ description: result.toast.description,
+ prUrl: result.toast.cta.kind === "open_pr" ? result.toast.cta.url : undefined,
+ });
+
+ if (result.branch.status === "created" && result.branch.name) {
+ await syncSelectedThreadBranchState({
+ thread,
+ cwd,
+ nextThreadState: {
+ branch: result.branch.name,
+ worktreePath: thread.worktreePath,
+ },
+ });
+ return result;
+ }
+
+ await refreshSelectedThreadGitStatus({ quiet: true, cwd });
+ return result;
+ });
+ },
+ [refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, syncSelectedThreadBranchState],
+ );
+
+ return {
+ refreshSelectedThreadGitStatus,
+ refreshSelectedThreadBranches,
+ onCheckoutSelectedThreadBranch,
+ onCreateSelectedThreadBranch,
+ onCreateSelectedThreadWorktree,
+ onPullSelectedThreadBranch,
+ onRunSelectedThreadGitAction,
+ };
+}
diff --git a/apps/mobile/src/features/threads/use-selected-thread-git-state.ts b/apps/mobile/src/features/threads/use-selected-thread-git-state.ts
new file mode 100644
index 0000000000..efcc6e2556
--- /dev/null
+++ b/apps/mobile/src/features/threads/use-selected-thread-git-state.ts
@@ -0,0 +1,47 @@
+import { useMemo } from "react";
+
+import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
+
+import { useGitActionState } from "../../state/use-git-action-state";
+import { useGitBranches } from "../../state/use-git-branches";
+import { useThreadSelection } from "../../state/use-thread-selection";
+
+export function useSelectedThreadGitState() {
+ const { selectedThread, selectedThreadProject } = useThreadSelection();
+
+ const selectedThreadGitTarget = useMemo(
+ () => ({
+ environmentId: selectedThread?.environmentId ?? null,
+ cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
+ }),
+ [
+ selectedThread?.environmentId,
+ selectedThread?.worktreePath,
+ selectedThreadProject?.workspaceRoot,
+ ],
+ );
+ const gitActionState = useGitActionState(selectedThreadGitTarget);
+
+ const selectedThreadBranchTarget = useMemo(
+ () => ({
+ environmentId: selectedThread?.environmentId ?? null,
+ cwd: selectedThreadProject?.workspaceRoot ?? null,
+ query: null,
+ }),
+ [selectedThread?.environmentId, selectedThreadProject?.workspaceRoot],
+ );
+ const selectedThreadBranchState = useGitBranches(selectedThreadBranchTarget);
+ const selectedThreadBranches = useMemo(
+ () =>
+ dedupeRemoteBranchesWithLocalMatches(selectedThreadBranchState.data?.branches ?? []).filter(
+ (branch) => !branch.isRemote,
+ ),
+ [selectedThreadBranchState.data?.branches],
+ );
+
+ return {
+ gitOperationLabel: gitActionState.currentLabel,
+ selectedThreadBranches,
+ selectedThreadBranchesLoading: selectedThreadBranchState.isPending,
+ };
+}
diff --git a/apps/mobile/src/features/threads/use-thread-composer-state.ts b/apps/mobile/src/features/threads/use-thread-composer-state.ts
new file mode 100644
index 0000000000..66392c66bf
--- /dev/null
+++ b/apps/mobile/src/features/threads/use-thread-composer-state.ts
@@ -0,0 +1,560 @@
+import { useAtomValue } from "@effect/atom-react";
+import { useCallback, useEffect, useMemo } from "react";
+
+import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
+import {
+ ApprovalRequestId,
+ CommandId,
+ EnvironmentId,
+ MessageId,
+ ThreadId,
+} from "@t3tools/contracts";
+import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
+import { Atom } from "effect/unstable/reactivity";
+
+import {
+ convertPastedImagesToAttachments,
+ pasteComposerClipboard,
+ pickComposerImages,
+} from "../../lib/composerImages";
+import type { DraftComposerImageAttachment } from "../../lib/composerImages";
+import { scopedRequestKey, scopedThreadKey } from "../../lib/scopedEntities";
+import {
+ buildPendingUserInputAnswers,
+ buildThreadFeed,
+ derivePendingApprovals,
+ derivePendingUserInputs,
+ setPendingUserInputCustomAnswer,
+ type PendingUserInputDraftAnswer,
+ type QueuedThreadMessage,
+} from "../../lib/threadActivity";
+import { uuidv4 } from "../../lib/uuid";
+import { appAtomRegistry } from "../../state/atom-registry";
+import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
+import {
+ getEnvironmentClient,
+ setPendingConnectionError,
+ useRemoteConnectionStatus,
+} from "../../state/use-remote-environment-registry";
+import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import { useSelectedThreadDetail } from "../../state/use-thread-detail";
+import { useThreadSelection } from "../../state/use-thread-selection";
+
+const draftMessageByThreadKeyAtom = Atom.make>({}).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:thread-composer:draft-message"),
+);
+
+const draftAttachmentsByThreadKeyAtom = Atom.make<
+ Record>
+>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-composer:draft-attachments"));
+
+const dispatchingQueuedMessageIdAtom = Atom.make(null).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:thread-composer:dispatching-message-id"),
+);
+
+const queuedMessagesByThreadKeyAtom = Atom.make>>(
+ {},
+).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-composer:queued-messages"));
+
+const userInputDraftsByRequestKeyAtom = Atom.make<
+ Record>
+>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
+
+function setDraftMessage(threadKey: string, value: string): void {
+ const current = appAtomRegistry.get(draftMessageByThreadKeyAtom);
+ appAtomRegistry.set(draftMessageByThreadKeyAtom, {
+ ...current,
+ [threadKey]: value,
+ });
+}
+
+function appendDraftAttachments(
+ threadKey: string,
+ attachments: ReadonlyArray,
+): void {
+ const current = appAtomRegistry.get(draftAttachmentsByThreadKeyAtom);
+ appAtomRegistry.set(draftAttachmentsByThreadKeyAtom, {
+ ...current,
+ [threadKey]: [...(current[threadKey] ?? []), ...attachments],
+ });
+}
+
+function appendDraftMessage(threadKey: string, value: string): void {
+ const current = appAtomRegistry.get(draftMessageByThreadKeyAtom);
+ appAtomRegistry.set(draftMessageByThreadKeyAtom, {
+ ...current,
+ [threadKey]: `${current[threadKey] ?? ""}${value}`,
+ });
+}
+
+export function appendReviewCommentToDraft(input: {
+ readonly environmentId: string;
+ readonly threadId: string;
+ readonly text: string;
+}): void {
+ const threadKey = scopedThreadKey(
+ EnvironmentId.make(input.environmentId),
+ ThreadId.make(input.threadId),
+ );
+ const current = appAtomRegistry.get(draftMessageByThreadKeyAtom);
+ const existing = current[threadKey] ?? "";
+ const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";
+ appAtomRegistry.set(draftMessageByThreadKeyAtom, {
+ ...current,
+ [threadKey]: `${existing}${separator}${input.text}`,
+ });
+}
+
+function clearDraft(threadKey: string): void {
+ const draftMessages = appAtomRegistry.get(draftMessageByThreadKeyAtom);
+ const draftAttachments = appAtomRegistry.get(draftAttachmentsByThreadKeyAtom);
+ appAtomRegistry.set(draftMessageByThreadKeyAtom, {
+ ...draftMessages,
+ [threadKey]: "",
+ });
+ appAtomRegistry.set(draftAttachmentsByThreadKeyAtom, {
+ ...draftAttachments,
+ [threadKey]: [],
+ });
+}
+
+function removeDraftImage(threadKey: string, imageId: string): void {
+ const current = appAtomRegistry.get(draftAttachmentsByThreadKeyAtom);
+ appAtomRegistry.set(draftAttachmentsByThreadKeyAtom, {
+ ...current,
+ [threadKey]: (current[threadKey] ?? []).filter((image) => image.id !== imageId),
+ });
+}
+
+function beginDispatchingQueuedMessage(queuedMessageId: MessageId): void {
+ appAtomRegistry.set(dispatchingQueuedMessageIdAtom, queuedMessageId);
+}
+
+function finishDispatchingQueuedMessage(queuedMessageId: MessageId): void {
+ const current = appAtomRegistry.get(dispatchingQueuedMessageIdAtom);
+ appAtomRegistry.set(dispatchingQueuedMessageIdAtom, current === queuedMessageId ? null : current);
+}
+
+function enqueueQueuedMessage(message: QueuedThreadMessage): void {
+ const current = appAtomRegistry.get(queuedMessagesByThreadKeyAtom);
+ const threadKey = scopedThreadKey(message.environmentId, message.threadId);
+ appAtomRegistry.set(queuedMessagesByThreadKeyAtom, {
+ ...current,
+ [threadKey]: [...(current[threadKey] ?? []), message],
+ });
+}
+
+function removeQueuedMessage(
+ environmentId: EnvironmentId,
+ threadId: ThreadId,
+ queuedMessageId: MessageId,
+): void {
+ const current = appAtomRegistry.get(queuedMessagesByThreadKeyAtom);
+ const threadKey = scopedThreadKey(environmentId, threadId);
+ const existing = current[threadKey];
+ if (!existing) {
+ return;
+ }
+
+ const nextQueue = existing.filter((entry) => entry.messageId !== queuedMessageId);
+ const next = { ...current };
+ if (nextQueue.length === 0) {
+ delete next[threadKey];
+ } else {
+ next[threadKey] = nextQueue;
+ }
+
+ appAtomRegistry.set(queuedMessagesByThreadKeyAtom, next);
+}
+
+function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
+ const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
+ appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
+ ...current,
+ [requestKey]: {
+ ...current[requestKey],
+ [questionId]: {
+ selectedOptionLabel: label,
+ },
+ },
+ });
+}
+
+function setUserInputDraftCustomAnswer(
+ requestKey: string,
+ questionId: string,
+ customAnswer: string,
+): void {
+ const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
+ appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
+ ...current,
+ [requestKey]: {
+ ...current[requestKey],
+ [questionId]: setPendingUserInputCustomAnswer(
+ current[requestKey]?.[questionId],
+ customAnswer,
+ ),
+ },
+ });
+}
+
+function useQueueDrain(input: {
+ readonly dispatchingQueuedMessageId: string | null;
+ readonly queuedMessagesByThreadKey: Record>;
+ readonly threads: ReadonlyArray;
+ readonly environments: ReadonlyArray;
+ readonly sendQueuedMessage: (message: QueuedThreadMessage) => Promise;
+}) {
+ const {
+ dispatchingQueuedMessageId,
+ environments,
+ queuedMessagesByThreadKey,
+ sendQueuedMessage,
+ threads,
+ } = input;
+
+ useEffect(() => {
+ if (dispatchingQueuedMessageId !== null) {
+ return;
+ }
+
+ for (const [threadKey, queuedMessages] of Object.entries(queuedMessagesByThreadKey)) {
+ const nextQueuedMessage = queuedMessages[0];
+ if (!nextQueuedMessage) {
+ continue;
+ }
+
+ const thread = threads.find(
+ (candidate) => scopedThreadKey(candidate.environmentId, candidate.id) === threadKey,
+ );
+ if (!thread) {
+ continue;
+ }
+
+ const environment = environments.find(
+ (candidate) => candidate.environmentId === nextQueuedMessage.environmentId,
+ );
+ if (!environment || environment.connectionState !== "ready") {
+ continue;
+ }
+
+ const threadStatus = thread.session?.status;
+ if (threadStatus === "running" || threadStatus === "starting") {
+ continue;
+ }
+
+ void sendQueuedMessage(nextQueuedMessage);
+ return;
+ }
+ }, [
+ dispatchingQueuedMessageId,
+ environments,
+ queuedMessagesByThreadKey,
+ sendQueuedMessage,
+ threads,
+ ]);
+}
+
+export function useThreadComposerState() {
+ const { connectedEnvironments } = useRemoteConnectionStatus();
+ const { threads } = useRemoteCatalog();
+ const { selectedThread: selectedThreadShell } = useThreadSelection();
+ const selectedThread = useSelectedThreadDetail();
+ const draftMessageByThreadKey = useAtomValue(draftMessageByThreadKeyAtom);
+ const draftAttachmentsByThreadKey = useAtomValue(draftAttachmentsByThreadKeyAtom);
+ const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
+ const queuedMessagesByThreadKey = useAtomValue(queuedMessagesByThreadKeyAtom);
+ const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
+
+ const selectedThreadKey = selectedThreadShell
+ ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
+ : null;
+ const selectedRequestKey = selectedThreadShell
+ ? (requestId: ApprovalRequestId) =>
+ scopedRequestKey(selectedThreadShell.environmentId, requestId)
+ : null;
+ const selectedThreadQueuedMessages = useMemo(
+ () => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
+ [queuedMessagesByThreadKey, selectedThreadKey],
+ );
+
+ const selectedThreadFeed = useMemo(
+ () =>
+ selectedThread
+ ? buildThreadFeed(selectedThread, selectedThreadQueuedMessages, dispatchingQueuedMessageId)
+ : [],
+ [dispatchingQueuedMessageId, selectedThread, selectedThreadQueuedMessages],
+ );
+
+ const draftMessage = selectedThreadKey ? (draftMessageByThreadKey[selectedThreadKey] ?? "") : "";
+ const draftAttachments = selectedThreadKey
+ ? (draftAttachmentsByThreadKey[selectedThreadKey] ?? [])
+ : [];
+ const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
+
+ const selectedThreadSessionActivity = useMemo(() => {
+ if (!selectedThread?.session) {
+ return null;
+ }
+
+ return {
+ orchestrationStatus: selectedThread.session.status,
+ activeTurnId: selectedThread.session.activeTurnId ?? undefined,
+ };
+ }, [selectedThread]);
+
+ const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
+ const activeWorkStartedAt = useMemo(() => {
+ if (!selectedThread) {
+ return null;
+ }
+
+ return deriveActiveWorkStartedAt(
+ selectedThread.latestTurn,
+ selectedThreadSessionActivity,
+ queuedSendStartedAt,
+ );
+ }, [queuedSendStartedAt, selectedThread, selectedThreadSessionActivity]);
+
+ const activePendingApprovals = useMemo(
+ () => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
+ [selectedThread],
+ );
+ const activePendingApproval = activePendingApprovals[0] ?? null;
+
+ const activePendingUserInputs = useMemo(
+ () => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
+ [selectedThread],
+ );
+ const activePendingUserInput = activePendingUserInputs[0] ?? null;
+ const activePendingUserInputDrafts =
+ activePendingUserInput && selectedRequestKey
+ ? (userInputDraftsByRequestKey[selectedRequestKey(activePendingUserInput.requestId)] ?? {})
+ : {};
+ const activePendingUserInputAnswers = activePendingUserInput
+ ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts)
+ : null;
+
+ const activeThreadBusy =
+ !!selectedThread &&
+ (selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
+
+ const sendQueuedMessage = useCallback(
+ async (queuedMessage: QueuedThreadMessage) => {
+ const client = getEnvironmentClient(queuedMessage.environmentId);
+ const thread = threads.find(
+ (candidate) =>
+ candidate.environmentId === queuedMessage.environmentId &&
+ candidate.id === queuedMessage.threadId,
+ );
+ if (!client || !thread) {
+ return;
+ }
+
+ beginDispatchingQueuedMessage(queuedMessage.messageId);
+ try {
+ await client.orchestration.dispatchCommand({
+ type: "thread.turn.start",
+ commandId: CommandId.make(queuedMessage.commandId),
+ threadId: ThreadId.make(queuedMessage.threadId),
+ message: {
+ messageId: MessageId.make(queuedMessage.messageId),
+ role: "user",
+ text: queuedMessage.text,
+ attachments: queuedMessage.attachments,
+ },
+ runtimeMode: thread.runtimeMode,
+ interactionMode: thread.interactionMode,
+ createdAt: queuedMessage.createdAt,
+ });
+
+ removeQueuedMessage(
+ queuedMessage.environmentId,
+ queuedMessage.threadId,
+ queuedMessage.messageId,
+ );
+ } catch (error) {
+ removeQueuedMessage(
+ queuedMessage.environmentId,
+ queuedMessage.threadId,
+ queuedMessage.messageId,
+ );
+ setPendingConnectionError(
+ error instanceof Error ? error.message : "Failed to send message.",
+ );
+ } finally {
+ finishDispatchingQueuedMessage(queuedMessage.messageId);
+ }
+ },
+ [threads],
+ );
+
+ useQueueDrain({
+ dispatchingQueuedMessageId,
+ queuedMessagesByThreadKey,
+ threads,
+ environments: connectedEnvironments,
+ sendQueuedMessage,
+ });
+
+ const onSendMessage = useCallback(() => {
+ if (!selectedThreadShell) {
+ return;
+ }
+
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
+ const text = (draftMessageByThreadKey[threadKey] ?? "").trim();
+ const attachments = draftAttachmentsByThreadKey[threadKey] ?? [];
+ if (text.length === 0 && attachments.length === 0) {
+ return;
+ }
+
+ const createdAt = new Date().toISOString();
+ enqueueQueuedMessage({
+ environmentId: selectedThreadShell.environmentId,
+ threadId: selectedThreadShell.id,
+ messageId: MessageId.make(uuidv4()),
+ commandId: CommandId.make(uuidv4()),
+ text,
+ attachments,
+ createdAt,
+ });
+ clearDraft(threadKey);
+ }, [draftAttachmentsByThreadKey, draftMessageByThreadKey, selectedThreadShell]);
+
+ const onSelectUserInputOption = useCallback(
+ (requestId: string, questionId: string, label: string) => {
+ if (!selectedThreadShell) {
+ return;
+ }
+
+ const requestKey = scopedRequestKey(
+ selectedThreadShell.environmentId,
+ requestId as ApprovalRequestId,
+ );
+ setUserInputDraftOption(requestKey, questionId, label);
+ },
+ [selectedThreadShell],
+ );
+
+ const onChangeUserInputCustomAnswer = useCallback(
+ (requestId: string, questionId: string, customAnswer: string) => {
+ if (!selectedThreadShell) {
+ return;
+ }
+
+ const requestKey = scopedRequestKey(
+ selectedThreadShell.environmentId,
+ requestId as ApprovalRequestId,
+ );
+ setUserInputDraftCustomAnswer(requestKey, questionId, customAnswer);
+ },
+ [selectedThreadShell],
+ );
+
+ const onChangeDraftMessage = useCallback(
+ (value: string) => {
+ if (!selectedThreadShell) {
+ return;
+ }
+
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
+ setDraftMessage(threadKey, value);
+ },
+ [selectedThreadShell],
+ );
+
+ const onPickDraftImages = useCallback(async () => {
+ if (!selectedThreadShell) {
+ return;
+ }
+
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
+ const result = await pickComposerImages({
+ existingCount: draftAttachmentsByThreadKey[threadKey]?.length ?? 0,
+ });
+ if (result.images.length > 0) {
+ appendDraftAttachments(threadKey, result.images);
+ }
+ if (result.error) {
+ setPendingConnectionError(result.error);
+ }
+ }, [draftAttachmentsByThreadKey, selectedThreadShell]);
+
+ const onPasteIntoDraft = useCallback(async () => {
+ if (!selectedThreadShell) {
+ return;
+ }
+
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
+ const result = await pasteComposerClipboard({
+ existingCount: draftAttachmentsByThreadKey[threadKey]?.length ?? 0,
+ });
+ if (result.images.length > 0) {
+ appendDraftAttachments(threadKey, result.images);
+ }
+ if (result.text) {
+ appendDraftMessage(threadKey, result.text);
+ }
+ if (result.error) {
+ setPendingConnectionError(result.error);
+ }
+ }, [draftAttachmentsByThreadKey, selectedThreadShell]);
+
+ const onNativePasteImages = useCallback(
+ async (uris: ReadonlyArray) => {
+ if (!selectedThreadShell || uris.length === 0) {
+ return;
+ }
+
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
+ try {
+ const images = await convertPastedImagesToAttachments({
+ uris,
+ existingCount: draftAttachmentsByThreadKey[threadKey]?.length ?? 0,
+ });
+ if (images.length > 0) {
+ appendDraftAttachments(threadKey, images);
+ }
+ } catch (error) {
+ console.error("[native paste] error converting images", error);
+ }
+ },
+ [draftAttachmentsByThreadKey, selectedThreadShell],
+ );
+
+ const onRemoveDraftImage = useCallback(
+ (imageId: string) => {
+ if (!selectedThreadShell) {
+ return;
+ }
+
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
+ removeDraftImage(threadKey, imageId);
+ },
+ [selectedThreadShell],
+ );
+
+ return {
+ selectedThreadFeed,
+ selectedThreadQueueCount,
+ activeWorkStartedAt,
+ activePendingApproval,
+ activePendingUserInput,
+ activePendingUserInputDrafts,
+ activePendingUserInputAnswers,
+ draftMessage,
+ draftAttachments,
+ activeThreadBusy,
+ onChangeDraftMessage,
+ onPickDraftImages,
+ onPasteIntoDraft,
+ onNativePasteImages,
+ onRemoveDraftImage,
+ onSendMessage,
+ onSelectUserInputOption,
+ onChangeUserInputCustomAnswer,
+ };
+}
diff --git a/apps/mobile/src/hooks/useNativePaste.ts b/apps/mobile/src/hooks/useNativePaste.ts
new file mode 100644
index 0000000000..c97eb5a35f
--- /dev/null
+++ b/apps/mobile/src/hooks/useNativePaste.ts
@@ -0,0 +1,21 @@
+import type { PasteEventPayload } from "expo-paste-input";
+import { useCallback } from "react";
+
+/**
+ * Returns a stable `onPaste` handler for `TextInputWrapper` from
+ * `expo-paste-input`. When the user pastes images via the OS paste gesture,
+ * `onImages` is called with the pasted URIs. Text pastes are left to the
+ * native TextInput — no extra handling is needed.
+ *
+ * Used by both the thread composer and the new-task draft screen.
+ */
+export function useNativePaste(onImages: (uris: ReadonlyArray) => void) {
+ return useCallback(
+ (payload: PasteEventPayload) => {
+ if (payload.type === "images" && payload.uris && payload.uris.length > 0) {
+ onImages(payload.uris);
+ }
+ },
+ [onImages],
+ );
+}
diff --git a/apps/mobile/src/lib/cn.ts b/apps/mobile/src/lib/cn.ts
new file mode 100644
index 0000000000..365058cebd
--- /dev/null
+++ b/apps/mobile/src/lib/cn.ts
@@ -0,0 +1,6 @@
+import { type ClassValue, clsx } from "clsx";
+import { twMerge } from "tailwind-merge";
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs));
+}
diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts
new file mode 100644
index 0000000000..871982442e
--- /dev/null
+++ b/apps/mobile/src/lib/composerImages.ts
@@ -0,0 +1,249 @@
+import {
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
+ PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
+ type UploadChatImageAttachment,
+} from "@t3tools/contracts";
+import { uuidv4 } from "./uuid";
+
+export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
+ readonly id: string;
+ readonly previewUri: string;
+}
+
+function estimateBase64ByteSize(base64: string): number {
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
+ return Math.floor((base64.length * 3) / 4) - padding;
+}
+
+async function loadImagePicker() {
+ try {
+ return await import("expo-image-picker");
+ } catch (error) {
+ throw new Error("Image attachments are unavailable right now.", { cause: error });
+ }
+}
+
+async function loadClipboard() {
+ try {
+ return await import("expo-clipboard");
+ } catch (error) {
+ throw new Error("Clipboard paste is unavailable right now.", { cause: error });
+ }
+}
+
+export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
+ readonly images: ReadonlyArray;
+ readonly error: string | null;
+}> {
+ const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
+ if (remainingSlots <= 0) {
+ return {
+ images: [],
+ error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
+ };
+ }
+
+ let imagePicker: Awaited>;
+ try {
+ imagePicker = await loadImagePicker();
+ } catch (error) {
+ return {
+ images: [],
+ error:
+ error instanceof Error ? error.message : "Image attachments are unavailable right now.",
+ };
+ }
+
+ const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
+ if (!permission.granted) {
+ return {
+ images: [],
+ error: "Allow photo library access to attach images.",
+ };
+ }
+
+ const result = await imagePicker.launchImageLibraryAsync({
+ mediaTypes: ["images"],
+ allowsMultipleSelection: true,
+ selectionLimit: remainingSlots,
+ base64: true,
+ quality: 1,
+ });
+
+ if (result.canceled) {
+ return {
+ images: [],
+ error: null,
+ };
+ }
+
+ const nextImages: DraftComposerImageAttachment[] = [];
+ let error: string | null = null;
+
+ for (const asset of result.assets) {
+ const mimeType = asset.mimeType?.toLowerCase();
+ if (!mimeType?.startsWith("image/")) {
+ error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
+ continue;
+ }
+
+ const base64 = asset.base64;
+ if (!base64) {
+ error = `Failed to read '${asset.fileName ?? "image"}'.`;
+ continue;
+ }
+
+ const sizeBytes = asset.fileSize ?? estimateBase64ByteSize(base64);
+ if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
+ error = `'${asset.fileName ?? "image"}' exceeds the 10 MB attachment limit.`;
+ continue;
+ }
+
+ nextImages.push({
+ id: uuidv4(),
+ type: "image",
+ name: asset.fileName ?? "image",
+ mimeType,
+ sizeBytes,
+ dataUrl: `data:${mimeType};base64,${base64}`,
+ previewUri: asset.uri,
+ });
+ }
+
+ return {
+ images: nextImages,
+ error,
+ };
+}
+
+export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<{
+ readonly images: ReadonlyArray;
+ readonly text: string | null;
+ readonly error: string | null;
+}> {
+ let clipboard: Awaited>;
+ try {
+ clipboard = await loadClipboard();
+ } catch (error) {
+ return {
+ images: [],
+ text: null,
+ error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
+ };
+ }
+
+ const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
+
+ if (await clipboard.hasImageAsync()) {
+ if (remainingSlots <= 0) {
+ return {
+ images: [],
+ text: null,
+ error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
+ };
+ }
+ const image = await clipboard.getImageAsync({ format: "png" });
+ if (!image) {
+ return {
+ images: [],
+ text: null,
+ error: "Clipboard image is unavailable.",
+ };
+ }
+
+ const base64 = image.data.split(",")[1] ?? "";
+ const sizeBytes = estimateBase64ByteSize(base64);
+ if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
+ return {
+ images: [],
+ text: null,
+ error: "Clipboard image exceeds the 10 MB attachment limit.",
+ };
+ }
+
+ return {
+ images: [
+ {
+ id: uuidv4(),
+ type: "image",
+ name: "pasted-image.png",
+ mimeType: "image/png",
+ sizeBytes,
+ dataUrl: image.data,
+ previewUri: image.data,
+ },
+ ],
+ text: null,
+ error: null,
+ };
+ }
+
+ if (await clipboard.hasStringAsync()) {
+ const text = await clipboard.getStringAsync();
+ return {
+ images: [],
+ text: text.length > 0 ? text : null,
+ error: text.length > 0 ? null : "Clipboard is empty.",
+ };
+ }
+
+ return {
+ images: [],
+ text: null,
+ error: "Clipboard does not contain pasteable text or image content.",
+ };
+}
+
+function mimeTypeFromUri(uri: string): string {
+ const ext = uri.split(".").pop()?.toLowerCase();
+ switch (ext) {
+ case "png":
+ return "image/png";
+ case "jpg":
+ case "jpeg":
+ return "image/jpeg";
+ case "gif":
+ return "image/gif";
+ case "webp":
+ return "image/webp";
+ case "heic":
+ return "image/heic";
+ default:
+ return "image/png";
+ }
+}
+
+export async function convertPastedImagesToAttachments(input: {
+ readonly uris: ReadonlyArray;
+ readonly existingCount: number;
+}): Promise> {
+ const { File } = await import("expo-file-system");
+ const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
+ const uris = input.uris.slice(0, Math.max(0, remainingSlots));
+ const results: DraftComposerImageAttachment[] = [];
+
+ for (const uri of uris) {
+ try {
+ const file = new File(uri);
+ const base64 = await file.base64();
+ const sizeBytes = estimateBase64ByteSize(base64);
+ if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
+ continue;
+ }
+ const mimeType = mimeTypeFromUri(uri);
+ results.push({
+ id: uuidv4(),
+ type: "image",
+ name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
+ mimeType,
+ sizeBytes,
+ dataUrl: `data:${mimeType};base64,${base64}`,
+ previewUri: uri,
+ });
+ } catch (error) {
+ console.warn("Failed to read pasted image", uri, error);
+ }
+ }
+
+ return results;
+}
diff --git a/apps/mobile/src/lib/connection.ts b/apps/mobile/src/lib/connection.ts
new file mode 100644
index 0000000000..3127c64aac
--- /dev/null
+++ b/apps/mobile/src/lib/connection.ts
@@ -0,0 +1,54 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import {
+ bootstrapRemoteBearerSession,
+ fetchRemoteEnvironmentDescriptor,
+ resolveRemotePairingTarget,
+} from "@t3tools/shared/remote";
+
+export interface RemoteConnectionInput {
+ readonly pairingUrl: string;
+}
+
+export interface SavedRemoteConnection {
+ readonly environmentId: EnvironmentId;
+ readonly environmentLabel: string;
+ readonly pairingUrl: string;
+ readonly displayUrl: string;
+ readonly httpBaseUrl: string;
+ readonly wsBaseUrl: string;
+ readonly bearerToken: string;
+}
+
+export type RemoteClientConnectionState =
+ | "idle"
+ | "connecting"
+ | "ready"
+ | "reconnecting"
+ | "disconnected";
+
+export async function bootstrapRemoteConnection(
+ input: RemoteConnectionInput,
+): Promise {
+ const target = resolveRemotePairingTarget({
+ pairingUrl: input.pairingUrl,
+ });
+
+ const descriptor = await fetchRemoteEnvironmentDescriptor({
+ httpBaseUrl: target.httpBaseUrl,
+ });
+
+ const bootstrap = await bootstrapRemoteBearerSession({
+ httpBaseUrl: target.httpBaseUrl,
+ credential: target.credential,
+ });
+
+ return {
+ environmentId: descriptor.environmentId,
+ environmentLabel: descriptor.label,
+ pairingUrl: input.pairingUrl.trim(),
+ displayUrl: target.httpBaseUrl,
+ httpBaseUrl: target.httpBaseUrl,
+ wsBaseUrl: target.wsBaseUrl,
+ bearerToken: bootstrap.sessionToken,
+ };
+}
diff --git a/apps/mobile/src/lib/mobileLayout.ts b/apps/mobile/src/lib/mobileLayout.ts
new file mode 100644
index 0000000000..0ae284e463
--- /dev/null
+++ b/apps/mobile/src/lib/mobileLayout.ts
@@ -0,0 +1,37 @@
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(Math.max(value, min), max);
+}
+
+export type MobileLayoutVariant = "compact" | "split";
+
+export interface MobileLayout {
+ readonly variant: MobileLayoutVariant;
+ readonly usesSplitView: boolean;
+ readonly listPaneWidth: number | null;
+ readonly shellPadding: number;
+}
+
+export function deriveMobileLayout(input: {
+ readonly width: number;
+ readonly height: number;
+}): MobileLayout {
+ const { width, height } = input;
+ const shortestEdge = Math.min(width, height);
+ const wideEnoughForSplit = width >= 900 || (width >= 700 && shortestEdge >= 700);
+
+ if (!wideEnoughForSplit) {
+ return {
+ variant: "compact",
+ usesSplitView: false,
+ listPaneWidth: null,
+ shellPadding: 0,
+ };
+ }
+
+ return {
+ variant: "split",
+ usesSplitView: true,
+ listPaneWidth: clamp(Math.round(width * 0.34), 320, 420),
+ shellPadding: width >= 1180 ? 20 : 14,
+ };
+}
diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts
new file mode 100644
index 0000000000..7497b7147e
--- /dev/null
+++ b/apps/mobile/src/lib/modelOptions.ts
@@ -0,0 +1,89 @@
+import type { ModelSelection, ServerConfig as T3ServerConfig } from "@t3tools/contracts";
+
+export type ModelOption = {
+ readonly key: string;
+ readonly label: string;
+ readonly subtitle: string;
+ readonly providerKey: string;
+ readonly providerLabel: string;
+ readonly selection: ModelSelection;
+};
+
+export type ProviderGroup = {
+ readonly providerKey: string;
+ readonly providerLabel: string;
+ readonly models: ReadonlyArray;
+};
+
+function providerDisplayLabel(provider: string): string {
+ if (provider === "codex") return "Codex";
+ if (provider === "claudeAgent") return "Claude";
+ return provider;
+}
+
+export function buildModelOptions(
+ config: T3ServerConfig | null | undefined,
+ fallbackModelSelection: ModelSelection | null,
+): ReadonlyArray {
+ const options = new Map();
+
+ for (const provider of config?.providers ?? []) {
+ if (!provider.enabled || !provider.installed || provider.auth.status === "unauthenticated") {
+ continue;
+ }
+
+ const providerLabel = providerDisplayLabel(provider.provider);
+ for (const model of provider.models) {
+ const key = `${provider.provider}:${model.slug}`;
+ options.set(key, {
+ key,
+ label: model.name,
+ subtitle: providerLabel,
+ providerKey: provider.provider,
+ providerLabel,
+ selection: {
+ provider: provider.provider,
+ model: model.slug,
+ },
+ });
+ }
+ }
+
+ if (fallbackModelSelection) {
+ const key = `${fallbackModelSelection.provider}:${fallbackModelSelection.model}`;
+ if (!options.has(key)) {
+ const providerLabel = providerDisplayLabel(fallbackModelSelection.provider);
+ options.set(key, {
+ key,
+ label: fallbackModelSelection.model,
+ subtitle: providerLabel,
+ providerKey: fallbackModelSelection.provider,
+ providerLabel,
+ selection: fallbackModelSelection,
+ });
+ }
+ }
+
+ return [...options.values()];
+}
+
+export function groupByProvider(options: ReadonlyArray): ReadonlyArray {
+ const groups = new Map();
+ for (const option of options) {
+ const existing = groups.get(option.providerKey);
+ if (existing) {
+ existing.models.push(option);
+ } else {
+ groups.set(option.providerKey, {
+ providerLabel: option.providerLabel,
+ models: [option],
+ });
+ }
+ }
+
+ return [...groups.entries()].map(([providerKey, group]) => ({
+ providerKey,
+ providerLabel: group.providerLabel,
+ models: group.models,
+ }));
+}
diff --git a/apps/mobile/src/lib/repositoryGroups.test.ts b/apps/mobile/src/lib/repositoryGroups.test.ts
new file mode 100644
index 0000000000..f557860ae0
--- /dev/null
+++ b/apps/mobile/src/lib/repositoryGroups.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, it } from "vitest";
+
+import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
+
+import { groupProjectsByRepository } from "./repositoryGroups";
+import {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+} from "@t3tools/client-runtime";
+
+function makeProject(
+ input: Partial &
+ Pick,
+): EnvironmentScopedProjectShell {
+ return {
+ workspaceRoot: `/workspaces/${input.id}`,
+ repositoryIdentity: null,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ ...input,
+ };
+}
+
+function makeThread(
+ input: Partial &
+ Pick<
+ EnvironmentScopedThreadShell,
+ "environmentId" | "id" | "projectId" | "title" | "modelSelection"
+ >,
+): EnvironmentScopedThreadShell {
+ return {
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ archivedAt: null,
+ session: null,
+ latestUserMessageAt: null,
+ hasPendingApprovals: false,
+ hasPendingUserInput: false,
+ hasActionableProposedPlan: false,
+ ...input,
+ };
+}
+
+describe("groupProjectsByRepository", () => {
+ it("groups projects across environments by repository identity", () => {
+ const repoIdentity = {
+ canonicalKey: "github.com/t3tools/t3code",
+ locator: {
+ source: "git-remote" as const,
+ remoteName: "origin",
+ remoteUrl: "git@github.com:t3tools/t3code.git",
+ },
+ provider: "github",
+ owner: "t3tools",
+ name: "t3code",
+ displayName: "T3 Code",
+ };
+
+ const projects = [
+ makeProject({
+ environmentId: EnvironmentId.make("env-local"),
+ id: ProjectId.make("project-local"),
+ title: "T3 Code",
+ repositoryIdentity: repoIdentity,
+ }),
+ makeProject({
+ environmentId: EnvironmentId.make("env-staging"),
+ id: ProjectId.make("project-staging"),
+ title: "T3 Code",
+ repositoryIdentity: repoIdentity,
+ }),
+ ];
+
+ const threads = [
+ makeThread({
+ environmentId: EnvironmentId.make("env-staging"),
+ id: ThreadId.make("thread-2"),
+ projectId: ProjectId.make("project-staging"),
+ title: "Fix reconnect flow",
+ modelSelection: { provider: "codex", model: "gpt-5.4" },
+ updatedAt: "2026-04-02T12:00:00.000Z",
+ }),
+ makeThread({
+ environmentId: EnvironmentId.make("env-local"),
+ id: ThreadId.make("thread-1"),
+ projectId: ProjectId.make("project-local"),
+ title: "Polish mobile shell",
+ modelSelection: { provider: "codex", model: "gpt-5.4" },
+ updatedAt: "2026-04-03T12:00:00.000Z",
+ }),
+ ];
+
+ const groups = groupProjectsByRepository({ projects, threads });
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0]).toMatchObject({
+ key: "github.com/t3tools/t3code",
+ title: "T3 Code",
+ subtitle: "t3tools/t3code",
+ projectCount: 2,
+ threadCount: 2,
+ });
+ expect(
+ groups[0]?.projects
+ .map((entry) => entry.project.environmentId)
+ .toSorted((left, right) => left.localeCompare(right)),
+ ).toEqual(["env-local", "env-staging"]);
+ });
+
+ it("falls back to a scoped project key when repository identity is unavailable", () => {
+ const projects = [
+ makeProject({
+ environmentId: EnvironmentId.make("env-local"),
+ id: ProjectId.make("project-local"),
+ title: "Scratchpad",
+ }),
+ ];
+
+ const groups = groupProjectsByRepository({ projects, threads: [] });
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.key).toBe("env-local:project-local");
+ expect(groups[0]?.title).toBe("Scratchpad");
+ expect(groups[0]?.subtitle).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/lib/repositoryGroups.ts b/apps/mobile/src/lib/repositoryGroups.ts
new file mode 100644
index 0000000000..1468676a06
--- /dev/null
+++ b/apps/mobile/src/lib/repositoryGroups.ts
@@ -0,0 +1,132 @@
+import * as Order from "effect/Order";
+import * as Arr from "effect/Array";
+import type { RepositoryIdentity } from "@t3tools/contracts";
+
+import { scopedProjectKey } from "./scopedEntities";
+import {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+} from "@t3tools/client-runtime";
+
+export interface MobileRepositoryProjectGroup {
+ readonly key: string;
+ readonly project: EnvironmentScopedProjectShell;
+ readonly threads: ReadonlyArray;
+ readonly latestActivityAt: string;
+}
+
+export interface MobileRepositoryGroup {
+ readonly key: string;
+ readonly title: string;
+ readonly subtitle: string | null;
+ readonly repositoryIdentity: RepositoryIdentity | null;
+ readonly projectCount: number;
+ readonly threadCount: number;
+ readonly latestActivityAt: string;
+ readonly projects: ReadonlyArray;
+}
+
+function compareIsoDateDescending(left: string, right: string): number {
+ return new Date(right).getTime() - new Date(left).getTime();
+}
+
+function deriveRepositoryGroupKey(project: EnvironmentScopedProjectShell): string {
+ return (
+ project.repositoryIdentity?.canonicalKey ?? scopedProjectKey(project.environmentId, project.id)
+ );
+}
+
+function deriveRepositoryTitle(project: EnvironmentScopedProjectShell): string {
+ const identity = project.repositoryIdentity;
+ return identity?.displayName ?? identity?.name ?? project.title;
+}
+
+function deriveRepositorySubtitle(identity: RepositoryIdentity | null | undefined): string | null {
+ if (!identity) {
+ return null;
+ }
+ if (identity.owner && identity.name) {
+ return `${identity.owner}/${identity.name}`;
+ }
+ return identity.canonicalKey;
+}
+
+function deriveProjectLatestActivity(
+ project: EnvironmentScopedProjectShell,
+ threads: ReadonlyArray,
+): string {
+ const latestThread = threads[0];
+ return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
+}
+
+export function groupProjectsByRepository(input: {
+ readonly projects: ReadonlyArray;
+ readonly threads: ReadonlyArray;
+}): ReadonlyArray {
+ const threadsByProjectKey = new Map();
+
+ for (const thread of input.threads) {
+ const key = scopedProjectKey(thread.environmentId, thread.projectId);
+ const existing = threadsByProjectKey.get(key);
+ if (existing) {
+ existing.push(thread);
+ } else {
+ threadsByProjectKey.set(key, [thread]);
+ }
+ }
+
+ const grouped = new Map();
+
+ for (const project of input.projects) {
+ const key = deriveRepositoryGroupKey(project);
+ const projectKey = scopedProjectKey(project.environmentId, project.id);
+ const threads = Arr.sortWith(
+ threadsByProjectKey.get(projectKey) ?? [],
+ (s) => new Date(s.updatedAt ?? s.createdAt),
+ Order.Date,
+ );
+
+ const latestActivityAt = deriveProjectLatestActivity(project, threads);
+ const projectGroup: MobileRepositoryProjectGroup = {
+ key: projectKey,
+ project,
+ threads,
+ latestActivityAt,
+ };
+
+ const existing = grouped.get(key);
+ if (!existing) {
+ grouped.set(key, {
+ key,
+ title: deriveRepositoryTitle(project),
+ subtitle: deriveRepositorySubtitle(project.repositoryIdentity),
+ repositoryIdentity: project.repositoryIdentity ?? null,
+ projectCount: 1,
+ threadCount: threads.length,
+ latestActivityAt,
+ projects: [projectGroup],
+ });
+ continue;
+ }
+
+ grouped.set(key, {
+ ...existing,
+ title: existing.repositoryIdentity ? existing.title : deriveRepositoryTitle(project),
+ subtitle: existing.subtitle ?? deriveRepositorySubtitle(project.repositoryIdentity),
+ repositoryIdentity: existing.repositoryIdentity ?? project.repositoryIdentity ?? null,
+ projectCount: existing.projectCount + 1,
+ threadCount: existing.threadCount + threads.length,
+ latestActivityAt:
+ compareIsoDateDescending(existing.latestActivityAt, latestActivityAt) > 0
+ ? latestActivityAt
+ : existing.latestActivityAt,
+ projects: Arr.sortWith(
+ [...existing.projects, projectGroup],
+ (s) => new Date(s.latestActivityAt),
+ Order.Date,
+ ),
+ });
+ }
+
+ return Arr.sortWith([...grouped.values()], (s) => new Date(s.latestActivityAt), Order.Date);
+}
diff --git a/apps/mobile/src/lib/routes.ts b/apps/mobile/src/lib/routes.ts
new file mode 100644
index 0000000000..b70ab7638e
--- /dev/null
+++ b/apps/mobile/src/lib/routes.ts
@@ -0,0 +1,39 @@
+import type { Router } from "expo-router";
+
+import type { SelectedThreadRef } from "../state/remote-runtime-types";
+import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
+
+type ThreadRouteInput =
+ | Pick
+ | Pick;
+type PlainThreadRouteInput =
+ | {
+ environmentId: string;
+ threadId: string;
+ }
+ | {
+ environmentId: string;
+ id: string;
+ };
+
+export function buildThreadRoutePath(input: ThreadRouteInput | PlainThreadRouteInput): string {
+ const environmentId = input.environmentId;
+ const threadId = "threadId" in input ? input.threadId : input.id;
+
+ return `/threads/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`;
+}
+
+export function buildThreadReviewRoutePath(
+ input: ThreadRouteInput | PlainThreadRouteInput,
+): string {
+ return `${buildThreadRoutePath(input)}/review`;
+}
+
+export function dismissRoute(router: Router) {
+ if (router.canGoBack()) {
+ router.back();
+ return;
+ }
+
+ router.replace("/");
+}
diff --git a/apps/mobile/src/lib/scopedEntities.ts b/apps/mobile/src/lib/scopedEntities.ts
new file mode 100644
index 0000000000..34709957fd
--- /dev/null
+++ b/apps/mobile/src/lib/scopedEntities.ts
@@ -0,0 +1,16 @@
+import { ApprovalRequestId, EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
+
+export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {
+ return `${environmentId}:${projectId}`;
+}
+
+export function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId): string {
+ return `${environmentId}:${threadId}`;
+}
+
+export function scopedRequestKey(
+ environmentId: EnvironmentId,
+ requestId: ApprovalRequestId,
+): string {
+ return `${environmentId}:${requestId}`;
+}
diff --git a/apps/mobile/src/lib/storage.ts b/apps/mobile/src/lib/storage.ts
new file mode 100644
index 0000000000..e40fdc3179
--- /dev/null
+++ b/apps/mobile/src/lib/storage.ts
@@ -0,0 +1,55 @@
+import * as Arr from "effect/Array";
+import { pipe } from "effect/Function";
+import * as SecureStore from "expo-secure-store";
+
+import type { SavedRemoteConnection } from "./connection";
+
+const CONNECTIONS_KEY = "t3code.connections";
+
+async function readStorageItem(key: string): Promise {
+ return await SecureStore.getItemAsync(key);
+}
+
+async function writeStorageItem(key: string, value: string): Promise {
+ await SecureStore.setItemAsync(key, value);
+}
+
+export async function loadSavedConnections(): Promise> {
+ const raw = (await readStorageItem(CONNECTIONS_KEY)) ?? "";
+ if (!raw.trim()) {
+ return [];
+ }
+
+ try {
+ const parsed = JSON.parse(raw) as {
+ readonly connections?: ReadonlyArray;
+ };
+ return pipe(
+ parsed.connections ?? [],
+ Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()),
+ );
+ } catch {
+ return [];
+ }
+}
+
+export async function saveConnection(connection: SavedRemoteConnection): Promise {
+ const current = await loadSavedConnections();
+ const next = current.some((entry) => entry.environmentId === connection.environmentId)
+ ? pipe(
+ current,
+ Arr.map((entry) => (entry.environmentId === connection.environmentId ? connection : entry)),
+ )
+ : pipe(current, Arr.append(connection));
+
+ await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
+}
+
+export async function clearSavedConnection(environmentId: string): Promise {
+ const current = await loadSavedConnections();
+ const next = pipe(
+ current,
+ Arr.filter((entry) => entry.environmentId !== environmentId),
+ );
+ await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
+}
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts
new file mode 100644
index 0000000000..bc235c2ed7
--- /dev/null
+++ b/apps/mobile/src/lib/threadActivity.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ EventId,
+ ProjectId,
+ ThreadId,
+ TurnId,
+ type OrchestrationThread,
+ type OrchestrationThreadActivity,
+} from "@t3tools/contracts";
+
+import { buildThreadFeed } from "./threadActivity";
+
+function makeActivity(
+ input: Partial &
+ Pick,
+): OrchestrationThreadActivity {
+ return {
+ tone: "info",
+ payload: {},
+ turnId: null,
+ ...input,
+ };
+}
+
+function makeThread(
+ input: Partial & Pick,
+): OrchestrationThread {
+ return {
+ modelSelection: { provider: "codex", model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ archivedAt: null,
+ deletedAt: null,
+ messages: [],
+ proposedPlans: [],
+ activities: [],
+ checkpoints: [],
+ session: null,
+ ...input,
+ };
+}
+
+describe("buildThreadFeed", () => {
+ it("includes runtime warnings from the latest turn", () => {
+ const thread = makeThread({
+ id: ThreadId.make("thread-1"),
+ projectId: ProjectId.make("project-1"),
+ title: "Runtime warning thread",
+ latestTurn: {
+ turnId: TurnId.make("turn-latest"),
+ state: "running",
+ requestedAt: "2026-04-01T00:00:00.000Z",
+ startedAt: "2026-04-01T00:00:01.000Z",
+ completedAt: null,
+ assistantMessageId: null,
+ },
+ activities: [
+ makeActivity({
+ id: EventId.make("activity-old"),
+ kind: "runtime.warning",
+ summary: "Runtime warning",
+ createdAt: "2026-04-01T00:00:02.000Z",
+ turnId: TurnId.make("turn-old"),
+ payload: {
+ message: "Old warning",
+ },
+ }),
+ makeActivity({
+ id: EventId.make("activity-latest"),
+ kind: "runtime.warning",
+ summary: "Runtime warning",
+ createdAt: "2026-04-01T00:00:03.000Z",
+ turnId: TurnId.make("turn-latest"),
+ payload: {
+ message: "Latest warning",
+ },
+ }),
+ ],
+ });
+
+ const feed = buildThreadFeed(thread, [], null);
+ const group = feed[0];
+
+ expect(group).toMatchObject({
+ type: "activity-group",
+ });
+ if (!group || group.type !== "activity-group") {
+ return;
+ }
+
+ expect(group.activities).toEqual([
+ {
+ id: "activity-latest",
+ createdAt: "2026-04-01T00:00:03.000Z",
+ summary: "Runtime warning",
+ detail: null,
+ status: null,
+ },
+ ]);
+ });
+
+ it("collapses matching tool lifecycle rows like desktop", () => {
+ const thread = makeThread({
+ id: ThreadId.make("thread-2"),
+ projectId: ProjectId.make("project-1"),
+ title: "Collapsed tools",
+ latestTurn: {
+ turnId: TurnId.make("turn-1"),
+ state: "completed",
+ requestedAt: "2026-04-01T00:00:00.000Z",
+ startedAt: "2026-04-01T00:00:01.000Z",
+ completedAt: "2026-04-01T00:00:03.000Z",
+ assistantMessageId: null,
+ },
+ activities: [
+ makeActivity({
+ id: EventId.make("tool-updated"),
+ kind: "tool.updated",
+ tone: "tool",
+ summary: "Run tests",
+ createdAt: "2026-04-01T00:00:01.000Z",
+ turnId: TurnId.make("turn-1"),
+ payload: {
+ title: "Run tests",
+ itemType: "command_execution",
+ detail: "/bin/zsh -lc 'bun run test'",
+ },
+ }),
+ makeActivity({
+ id: EventId.make("tool-completed"),
+ kind: "tool.completed",
+ tone: "tool",
+ summary: "Run tests completed",
+ createdAt: "2026-04-01T00:00:02.000Z",
+ turnId: TurnId.make("turn-1"),
+ payload: {
+ title: "Run tests",
+ itemType: "command_execution",
+ detail: "/bin/zsh -lc 'bun run test'",
+ },
+ }),
+ ],
+ });
+
+ const feed = buildThreadFeed(thread, [], null);
+ const group = feed[0];
+
+ expect(group).toMatchObject({
+ type: "activity-group",
+ });
+ if (!group || group.type !== "activity-group") {
+ return;
+ }
+
+ expect(group.activities).toEqual([
+ {
+ id: "tool-completed",
+ createdAt: "2026-04-01T00:00:02.000Z",
+ summary: "Run tests",
+ detail: "bun run test",
+ status: null,
+ },
+ ]);
+ });
+});
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
new file mode 100644
index 0000000000..a5d901e7a8
--- /dev/null
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -0,0 +1,933 @@
+import { isToolLifecycleItemType } from "@t3tools/contracts";
+import type {
+ ApprovalRequestId,
+ CommandId,
+ EnvironmentId,
+ MessageId,
+ OrchestrationThread,
+ OrchestrationThreadActivity,
+ TurnId,
+ ToolLifecycleItemType,
+ ThreadId,
+ UserInputQuestion,
+} from "@t3tools/contracts";
+
+import type { DraftComposerImageAttachment } from "./composerImages";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+
+export interface PendingApproval {
+ readonly requestId: ApprovalRequestId;
+ readonly requestKind: "command" | "file-read" | "file-change";
+ readonly createdAt: string;
+ readonly detail?: string;
+}
+
+export interface PendingUserInput {
+ readonly requestId: ApprovalRequestId;
+ readonly createdAt: string;
+ readonly questions: ReadonlyArray;
+}
+
+export interface PendingUserInputDraftAnswer {
+ readonly selectedOptionLabel?: string;
+ readonly customAnswer?: string;
+}
+
+export interface QueuedThreadMessage {
+ readonly environmentId: EnvironmentId;
+ readonly threadId: ThreadId;
+ readonly messageId: MessageId;
+ readonly commandId: CommandId;
+ readonly text: string;
+ readonly attachments: ReadonlyArray;
+ readonly createdAt: string;
+}
+
+export interface ThreadFeedActivity {
+ readonly id: string;
+ readonly createdAt: string;
+ readonly summary: string;
+ readonly detail: string | null;
+ readonly status: string | null;
+}
+
+interface WorkLogEntry {
+ id: string;
+ createdAt: string;
+ label: string;
+ detail?: string;
+ command?: string;
+ rawCommand?: string;
+ changedFiles?: ReadonlyArray;
+ tone: "thinking" | "tool" | "info" | "error";
+ toolTitle?: string;
+ itemType?: ToolLifecycleItemType;
+ requestKind?: PendingApproval["requestKind"];
+}
+
+interface DerivedWorkLogEntry extends WorkLogEntry {
+ activityKind: OrchestrationThreadActivity["kind"];
+ collapseKey?: string;
+}
+
+type RawThreadFeedEntry =
+ | {
+ readonly type: "message";
+ readonly id: string;
+ readonly createdAt: string;
+ readonly message: OrchestrationThread["messages"][number];
+ }
+ | {
+ readonly type: "queued-message";
+ readonly id: string;
+ readonly createdAt: string;
+ readonly queuedMessage: QueuedThreadMessage;
+ readonly sending: boolean;
+ }
+ | {
+ readonly type: "activity";
+ readonly id: string;
+ readonly createdAt: string;
+ readonly activity: ThreadFeedActivity;
+ };
+
+export type ThreadFeedEntry =
+ | Extract
+ | {
+ readonly type: "activity-group";
+ readonly id: string;
+ readonly createdAt: string;
+ readonly activities: ReadonlyArray;
+ };
+
+function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
+ switch (requestType) {
+ case "command_execution_approval":
+ case "exec_command_approval":
+ return "command";
+ case "file_read_approval":
+ return "file-read";
+ case "file_change_approval":
+ case "apply_patch_approval":
+ return "file-change";
+ default:
+ return null;
+ }
+}
+
+function isStalePendingRequestFailureDetail(detail: string | undefined): boolean {
+ const normalized = detail?.toLowerCase();
+ if (!normalized) {
+ return false;
+ }
+ return (
+ normalized.includes("stale pending approval request") ||
+ normalized.includes("stale pending user-input request") ||
+ normalized.includes("unknown pending approval request") ||
+ normalized.includes("unknown pending permission request") ||
+ normalized.includes("unknown pending user-input request")
+ );
+}
+
+function parseUserInputQuestions(
+ payload: Record | null,
+): ReadonlyArray | null {
+ const questions = payload?.questions;
+ if (!Array.isArray(questions)) {
+ return null;
+ }
+
+ const parsed = questions
+ .map((entry) => {
+ if (!entry || typeof entry !== "object") return null;
+ const question = entry as Record;
+ if (
+ typeof question.id !== "string" ||
+ typeof question.header !== "string" ||
+ typeof question.question !== "string" ||
+ !Array.isArray(question.options)
+ ) {
+ return null;
+ }
+ const options = question.options
+ .map((option) => {
+ if (!option || typeof option !== "object") return null;
+ const record = option as Record;
+ if (typeof record.label !== "string" || typeof record.description !== "string") {
+ return null;
+ }
+ return {
+ label: record.label,
+ description: record.description,
+ };
+ })
+ .filter((option): option is UserInputQuestion["options"][number] => option !== null);
+ if (options.length === 0) {
+ return null;
+ }
+ return {
+ id: question.id,
+ header: question.header,
+ question: question.question,
+ options,
+ multiSelect: question.multiSelect === true,
+ };
+ })
+ .filter((question): question is UserInputQuestion => question !== null);
+
+ return parsed.length > 0 ? parsed : null;
+}
+
+function normalizeDraftAnswer(value: string | undefined): string | null {
+ if (typeof value !== "string") {
+ return null;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function resolvePendingUserInputAnswer(
+ draft: PendingUserInputDraftAnswer | undefined,
+): string | null {
+ const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
+ if (customAnswer) {
+ return customAnswer;
+ }
+ return normalizeDraftAnswer(draft?.selectedOptionLabel);
+}
+
+function deriveWorkLogEntries(
+ activities: ReadonlyArray,
+ latestTurnId: TurnId | undefined,
+): WorkLogEntry[] {
+ const ordered = Arr.sort(activities, activityOrder);
+ const entries = ordered
+ .filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
+ .filter((activity) => activity.kind !== "tool.started")
+ .filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
+ .filter((activity) => activity.kind !== "context-window.updated")
+ .filter((activity) => activity.summary !== "Checkpoint captured")
+ .filter((activity) => !isPlanBoundaryToolActivity(activity))
+ .map(toDerivedWorkLogEntry);
+ return collapseDerivedWorkLogEntries(entries).map(
+ ({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
+ );
+}
+
+function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
+ if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") {
+ return false;
+ }
+
+ const payload =
+ activity.payload && typeof activity.payload === "object"
+ ? (activity.payload as Record)
+ : null;
+ return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
+}
+
+function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
+ const payload =
+ activity.payload && typeof activity.payload === "object"
+ ? (activity.payload as Record)
+ : null;
+ const commandPreview = extractToolCommand(payload);
+ const changedFiles = extractChangedFiles(payload);
+ const title = extractToolTitle(payload);
+ const entry: DerivedWorkLogEntry = {
+ id: activity.id,
+ createdAt: activity.createdAt,
+ label: activity.summary,
+ tone: activity.tone === "approval" ? "info" : activity.tone,
+ activityKind: activity.kind,
+ };
+ const itemType = extractWorkLogItemType(payload);
+ const requestKind = extractWorkLogRequestKind(payload);
+ if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
+ const detail = stripTrailingExitCode(payload.detail).output;
+ if (detail) {
+ entry.detail = detail;
+ }
+ }
+ if (commandPreview.command) {
+ entry.command = commandPreview.command;
+ }
+ if (commandPreview.rawCommand) {
+ entry.rawCommand = commandPreview.rawCommand;
+ }
+ if (changedFiles.length > 0) {
+ entry.changedFiles = changedFiles;
+ }
+ if (title) {
+ entry.toolTitle = title;
+ }
+ if (itemType) {
+ entry.itemType = itemType;
+ }
+ if (requestKind) {
+ entry.requestKind = requestKind;
+ }
+ const collapseKey = deriveToolLifecycleCollapseKey(entry);
+ if (collapseKey) {
+ entry.collapseKey = collapseKey;
+ }
+ return entry;
+}
+
+function collapseDerivedWorkLogEntries(
+ entries: ReadonlyArray,
+): DerivedWorkLogEntry[] {
+ const collapsed: DerivedWorkLogEntry[] = [];
+ for (const entry of entries) {
+ const previous = collapsed.at(-1);
+ if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
+ collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
+ continue;
+ }
+ collapsed.push(entry);
+ }
+ return collapsed;
+}
+
+function shouldCollapseToolLifecycleEntries(
+ previous: DerivedWorkLogEntry,
+ next: DerivedWorkLogEntry,
+): boolean {
+ if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") {
+ return false;
+ }
+ if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") {
+ return false;
+ }
+ if (previous.activityKind === "tool.completed") {
+ return false;
+ }
+ return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey;
+}
+
+function mergeDerivedWorkLogEntries(
+ previous: DerivedWorkLogEntry,
+ next: DerivedWorkLogEntry,
+): DerivedWorkLogEntry {
+ const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
+ const detail = next.detail ?? previous.detail;
+ const command = next.command ?? previous.command;
+ const rawCommand = next.rawCommand ?? previous.rawCommand;
+ const toolTitle = next.toolTitle ?? previous.toolTitle;
+ const itemType = next.itemType ?? previous.itemType;
+ const requestKind = next.requestKind ?? previous.requestKind;
+ const collapseKey = next.collapseKey ?? previous.collapseKey;
+ return {
+ ...previous,
+ ...next,
+ ...(detail ? { detail } : {}),
+ ...(command ? { command } : {}),
+ ...(rawCommand ? { rawCommand } : {}),
+ ...(changedFiles.length > 0 ? { changedFiles } : {}),
+ ...(toolTitle ? { toolTitle } : {}),
+ ...(itemType ? { itemType } : {}),
+ ...(requestKind ? { requestKind } : {}),
+ ...(collapseKey ? { collapseKey } : {}),
+ };
+}
+
+function mergeChangedFiles(
+ previous: ReadonlyArray | undefined,
+ next: ReadonlyArray | undefined,
+): string[] {
+ const merged = [...(previous ?? []), ...(next ?? [])];
+ if (merged.length === 0) {
+ return [];
+ }
+ return [...new Set(merged)];
+}
+
+function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {
+ if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
+ return undefined;
+ }
+ const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label);
+ const detail = entry.detail?.trim() ?? "";
+ const itemType = entry.itemType ?? "";
+ if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) {
+ return undefined;
+ }
+ return [itemType, normalizedLabel, detail].join("\u001f");
+}
+
+function normalizeCompactToolLabel(value: string): string {
+ return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
+}
+
+function workEntryPreview(
+ workEntry: Pick,
+): string | null {
+ if (workEntry.command) return workEntry.command;
+ if (workEntry.detail) return workEntry.detail;
+ if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
+ const [firstPath] = workEntry.changedFiles ?? [];
+ if (!firstPath) return null;
+ return workEntry.changedFiles!.length === 1
+ ? firstPath
+ : `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
+}
+
+function capitalizePhrase(value: string): string {
+ const trimmed = value.trim();
+ if (trimmed.length === 0) {
+ return value;
+ }
+ return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
+}
+
+function workEntryHeading(workEntry: WorkLogEntry): string {
+ if (!workEntry.toolTitle) {
+ return capitalizePhrase(normalizeCompactToolLabel(workEntry.label));
+ }
+ return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
+}
+
+function asRecord(value: unknown): Record | null {
+ return value && typeof value === "object" ? (value as Record) : null;
+}
+
+function asTrimmedString(value: unknown): string | null {
+ if (typeof value !== "string") {
+ return null;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function trimMatchingOuterQuotes(value: string): string {
+ const trimmed = value.trim();
+ if (
+ (trimmed.startsWith("'") && trimmed.endsWith("'")) ||
+ (trimmed.startsWith('"') && trimmed.endsWith('"'))
+ ) {
+ const unquoted = trimmed.slice(1, -1).trim();
+ return unquoted.length > 0 ? unquoted : trimmed;
+ }
+ return trimmed;
+}
+
+function executableBasename(value: string): string | null {
+ const trimmed = trimMatchingOuterQuotes(value);
+ if (trimmed.length === 0) {
+ return null;
+ }
+ const normalized = trimmed.replace(/\\/g, "/");
+ const segments = normalized.split("/");
+ const last = segments.at(-1)?.trim() ?? "";
+ return last.length > 0 ? last.toLowerCase() : null;
+}
+
+function splitExecutableAndRest(value: string): { executable: string; rest: string } | null {
+ const trimmed = value.trim();
+ if (trimmed.length === 0) {
+ return null;
+ }
+
+ if (trimmed.startsWith('"') || trimmed.startsWith("'")) {
+ const quote = trimmed.charAt(0);
+ const closeIndex = trimmed.indexOf(quote, 1);
+ if (closeIndex <= 0) {
+ return null;
+ }
+ return {
+ executable: trimmed.slice(0, closeIndex + 1),
+ rest: trimmed.slice(closeIndex + 1).trim(),
+ };
+ }
+
+ const firstWhitespace = trimmed.search(/\s/);
+ if (firstWhitespace < 0) {
+ return {
+ executable: trimmed,
+ rest: "",
+ };
+ }
+
+ return {
+ executable: trimmed.slice(0, firstWhitespace),
+ rest: trimmed.slice(firstWhitespace).trim(),
+ };
+}
+
+const SHELL_WRAPPER_SPECS = [
+ {
+ executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"],
+ wrapperFlagPattern: /(?:^|\s)-command\s+/i,
+ },
+ {
+ executables: ["cmd", "cmd.exe"],
+ wrapperFlagPattern: /(?:^|\s)\/c\s+/i,
+ },
+ {
+ executables: ["bash", "sh", "zsh"],
+ wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i,
+ },
+] as const;
+
+function findShellWrapperSpec(shell: string) {
+ return SHELL_WRAPPER_SPECS.find((spec) =>
+ (spec.executables as ReadonlyArray).includes(shell),
+ );
+}
+
+function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null {
+ const match = wrapperFlagPattern.exec(value);
+ if (!match) {
+ return null;
+ }
+
+ const command = value.slice(match.index + match[0].length).trim();
+ if (command.length === 0) {
+ return null;
+ }
+
+ const unwrapped = trimMatchingOuterQuotes(command);
+ return unwrapped.length > 0 ? unwrapped : null;
+}
+
+function unwrapKnownShellCommandWrapper(value: string): string {
+ const split = splitExecutableAndRest(value);
+ if (!split || split.rest.length === 0) {
+ return value;
+ }
+
+ const shell = executableBasename(split.executable);
+ if (!shell) {
+ return value;
+ }
+
+ const spec = findShellWrapperSpec(shell);
+ if (!spec) {
+ return value;
+ }
+
+ return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value;
+}
+
+function formatCommandArrayPart(value: string): string {
+ return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
+}
+
+function formatCommandValue(value: unknown): string | null {
+ const direct = asTrimmedString(value);
+ if (direct) {
+ return direct;
+ }
+ if (!Array.isArray(value)) {
+ return null;
+ }
+ const parts = value
+ .map((entry) => asTrimmedString(entry))
+ .filter((entry): entry is string => entry !== null);
+ if (parts.length === 0) {
+ return null;
+ }
+ return parts.map((part) => formatCommandArrayPart(part)).join(" ");
+}
+
+function normalizeCommandValue(value: unknown): string | null {
+ const formatted = formatCommandValue(value);
+ return formatted ? unwrapKnownShellCommandWrapper(formatted) : null;
+}
+
+function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null {
+ const formatted = formatCommandValue(value);
+ if (!formatted || normalizedCommand === null) {
+ return null;
+ }
+ return formatted === normalizedCommand ? null : formatted;
+}
+
+function extractToolCommand(payload: Record | null): {
+ command: string | null;
+ rawCommand: string | null;
+} {
+ const data = asRecord(payload?.data);
+ const item = asRecord(data?.item);
+ const itemResult = asRecord(item?.result);
+ const itemInput = asRecord(item?.input);
+ const itemType = asTrimmedString(payload?.itemType);
+ const detail = asTrimmedString(payload?.detail);
+ const candidates: unknown[] = [
+ item?.command,
+ itemInput?.command,
+ itemResult?.command,
+ data?.command,
+ itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null,
+ ];
+
+ for (const candidate of candidates) {
+ const command = normalizeCommandValue(candidate);
+ if (!command) {
+ continue;
+ }
+ return {
+ command,
+ rawCommand: toRawToolCommand(candidate, command),
+ };
+ }
+
+ return {
+ command: null,
+ rawCommand: null,
+ };
+}
+
+function extractToolTitle(payload: Record | null): string | null {
+ return asTrimmedString(payload?.title);
+}
+
+function stripTrailingExitCode(value: string): {
+ output: string | null;
+ exitCode?: number | undefined;
+} {
+ const trimmed = value.trim();
+ const match = /^(?