Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 259ff4173f Format provider pill optimization
Co-authored-by: Julius Marminge <[email protected]>
2026-07-07 16:15:05 +00:00
Cursor AgentandJulius Marminge cb1d13db85 Fix provider pill progress tone typing
Co-authored-by: Julius Marminge <[email protected]>
2026-07-07 16:14:45 +00:00
Cursor AgentandJulius Marminge d9c9757e30 Optimize provider update pill renders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-07 16:08:22 +00:00
Julius Marminge 4414f922fe Clear VCS presentation state on finish (#3764) 2026-07-07 08:54:27 -07:00
Julius Marminge 6e42231cb1 Extend Done display to 15 minutes and show up to 5 Live Activity banner rows (#3761) 2026-07-07 02:00:36 -07:00
Julius Marminge bdf5aed665 Fix Expo widget asset wiring order (#3763) 2026-07-07 02:00:10 -07:00
Julius Marminge 0b62e2eb11 Use variant-specific splash icons in mobile app (#3762) 2026-07-07 01:59:13 -07:00
Julius Marminge f9727d0853 Prevent Add Project sheet from collapsing on relayout (#3759) 2026-07-07 01:58:29 -07:00
Julius MarmingeandClaude Opus 4.8 d8e0ba3ea0 Improve live activity routing and diagnostics (#3685)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-07 00:56:20 -07:00
Julius MarmingeandClaude Fable 5 32e7844837 Fix mobile legend anchor under automatic iOS insets (#3684)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-05 22:50:33 -07:00
Julius MarmingeandClaude Opus 4.8 482d56233d Load thread snapshots over HTTP before live sync (#3719)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-05 22:00:13 -07:00
Theo BrowneandClaude Fable 5 6009720844 Add repo-root favicon.svg so t3 code shows its own icon (#3683)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-04 15:05:45 -07:00
Theo BrowneandClaude Opus 4.8 e26e55f389 fix(mobile): combined test branch — scroll, back-swipe, thread lists, computer switching (#3687)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-04 14:28:51 -07:00
Julius Marminge 4ac094fef6 Surface pending tasks in mobile home and draft flow (#3670) 2026-07-03 13:32:14 -07:00
Julius Marminge a7e43b2281 Upgrade Vite Plus and enable bundled dev opt-in (#3679) 2026-07-03 11:21:47 -07:00
Julius MarmingeandClaude Fable 5 cabc93bad3 Make the thread composer read as elevated liquid glass (#3668)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-03 07:05:38 +00:00
Julius MarmingeandClaude Fable 5 5cda815626 fix(mobile): compile patched native pods from source on EAS (#3667)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-03 06:52:01 +00:00
32d17d3db5 Add adaptive split-view layout for iPad/mobile workspace (#3514)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-02 22:42:14 -07:00
Theo Browne 6d35a87c5d fix(dev): Fix electron dev launch and add test (#3662) 2026-07-02 18:57:59 -07:00
Julius Marminge 7b9eef7ac2 Restore the ultrathink frame border effect (#3625) 2026-07-01 00:25:36 +00:00
Julius Marminge 9d66b104fe Add Claude Sonnet 5 as the default Claude model (#3620) 2026-06-30 11:40:35 -07:00
Utkarsh Patil 51ea084c87 fix: warm WSL before preflight in WSL-only backend mode (#3588) 2026-06-30 11:27:34 -07:00
Hugo BlomandJulius Marminge 0615fd7df1 Add middle-click close for right panel tabs (#3161)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-30 17:13:38 +00:00
t3-code[bot] 2448212367 chore(release): prepare v0.0.28 2026-06-29 22:57:48 +00:00
Julius Marminge fda6486233 Restore chat scroll affordances and add timeline minimap (#3587) 2026-06-29 19:35:16 +00:00
344 changed files with 28516 additions and 6729 deletions

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
name: Mobile EAS Production
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
# Under the fingerprint runtime-version policy the fingerprint must be computed
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
on:
workflow_dispatch:
inputs:
mode:
description: "build (+ auto-submit to TestFlight) or update (OTA)"
required: true
type: choice
default: build
options:
- build
- update
platform:
description: "Target platform"
required: true
type: choice
default: ios
options:
- ios
- android
- all
message:
description: "OTA update message (mode=update only)"
required: false
type: string
jobs:
production:
name: EAS Production ${{ inputs.mode }}
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
env:
APP_VARIANT: production
NODE_OPTIONS: --max-old-space-size=8192
steps:
- id: expo-token
name: Check for EXPO_TOKEN
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
if [ -n "$EXPO_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup EAS
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
- name: Pull production environment variables
if: steps.expo-token.outputs.present == 'true'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Build and submit
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
- name: Publish OTA update
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
eas update \
--channel production \
--environment production \
--platform ${{ inputs.platform }} \
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
--non-interactive
+1
View File
@@ -0,0 +1 @@
vp staged
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.27",
"version": "0.0.28",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+13 -6
View File
@@ -358,10 +358,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
}
export function resolveElectronPath() {
ensureElectronRuntime();
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
if (hostPlatform !== "darwin") {
return electronBinaryPath;
@@ -378,13 +375,23 @@ export function resolveElectronLaunchCommand(args = []) {
};
}
export function resolveElectronBinaryPath({
ensureRuntime = ensureElectronRuntime,
createRequire = NodeModule.createRequire,
moduleUrl = import.meta.url,
} = {}) {
ensureRuntime();
const require = createRequire(moduleUrl);
return require("electron");
}
export function resolveDevProtocolClient() {
if (hostPlatform !== "darwin" || !isDevelopment) {
return null;
}
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
@@ -1,6 +1,6 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
@@ -25,4 +25,24 @@ describe("electron development launcher", () => {
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
it("repairs Electron before loading the package entrypoint", () => {
const calls = [];
const electronPath = resolveElectronBinaryPath({
ensureRuntime: () => {
calls.push("ensure");
},
createRequire: () => (specifier) => {
calls.push(`require:${specifier}`);
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
},
moduleUrl: import.meta.url,
});
assert.equal(
electronPath,
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
);
assert.deepEqual(calls, ["ensure", "require:electron"]);
});
});
@@ -607,6 +607,7 @@ export const make = Effect.gen(function* () {
const backendExposure = yield* serverExposure.backendConfig;
const persistedSettings = yield* settings.get;
const shared = yield* sharedInputs;
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
return yield* resolveWslStartConfig({
...shared,
port: backendExposure.port,
+1
View File
@@ -1,6 +1,7 @@
included:
- ios/T3Code
- modules/t3-composer-editor/ios
- modules/t3-native-controls/ios
- modules/t3-terminal/ios
- modules/t3-review-diff/ios
+34 -4
View File
@@ -15,30 +15,38 @@ const VARIANT_CONFIG: Record<
readonly appName: string;
readonly scheme: string;
readonly iosIcon: string;
readonly splashIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
readonly relyingParty?: string;
}
> = {
development: {
appName: "T3 Code Dev",
scheme: "t3code-dev",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
relyingParty: "clerk.t3.codes",
},
preview: {
appName: "T3 Code Preview",
scheme: "t3code-preview",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
},
production: {
appName: "T3 Code",
scheme: "t3code",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
relyingParty: "clerk.t3.codes",
},
};
@@ -62,7 +70,11 @@ const config: ExpoConfig = {
scheme: variant.scheme,
version: "0.1.0",
runtimeVersion: {
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
// With appVersion, every 0.1.0 build shares a runtime version, so a JS update
// could land on a binary missing the native changes it needs and crash.
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
},
orientation: "portrait",
icon: "./assets/icon.png",
@@ -77,6 +89,14 @@ const config: ExpoConfig = {
icon: variant.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
// Sign in with Apple, or push notification entitlements).
appleTeamId: "ARK85ZXQ4Z",
associatedDomains: [
`applinks:${variant.relyingParty}`,
`webcredentials:${variant.relyingParty}`,
],
infoPlist: {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
@@ -101,7 +121,6 @@ const config: ExpoConfig = {
favicon: "./assets/favicon.png",
},
plugins: [
"expo-router",
"expo-font",
"expo-secure-store",
["@clerk/expo", { theme: "./clerk-theme.json" }],
@@ -116,12 +135,12 @@ const config: ExpoConfig = {
[
"expo-splash-screen",
{
image: "./assets/splash-icon.png",
image: variant.splashIcon,
resizeMode: "contain",
backgroundColor: "#ffffff",
imageWidth: 220,
dark: {
image: "./assets/splash-icon.png",
image: variant.splashIcon,
backgroundColor: "#0a0a0a",
},
},
@@ -139,12 +158,22 @@ const config: ExpoConfig = {
},
},
],
"./plugins/withIosCocoaPodsUuidCache.cjs",
// Must be listed BEFORE expo-widgets: same-type mods run last-registered-
// first, so registering earlier makes this plugin's mods run AFTER
// expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
// would delete the asset catalog) and its xcodeproj mod creates the widget
// target (which must exist before the compile phase can be attached).
"./plugins/withWidgetLogoAsset.cjs",
[
"expo-widgets",
{
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
enablePushNotifications: true,
// Agent activity can update many times an hour; without the
// frequent-updates entitlement iOS throttles the update budget sooner.
frequentUpdates: true,
widgets: [
{
name: "AgentActivity",
@@ -155,6 +184,7 @@ const config: ExpoConfig = {
],
},
],
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
],
extra: {
File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.0 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

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

After

Width:  |  Height:  |  Size: 887 B

+8 -1
View File
@@ -6,6 +6,7 @@
},
"build": {
"development": {
"corepack": true,
"env": {
"APP_VARIANT": "development"
},
@@ -14,6 +15,7 @@
"distribution": "internal"
},
"preview": {
"corepack": true,
"env": {
"APP_VARIANT": "preview"
},
@@ -22,6 +24,7 @@
"distribution": "internal"
},
"preview:dev": {
"corepack": true,
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint"
@@ -35,6 +38,7 @@
}
},
"production": {
"corepack": true,
"env": {
"APP_VARIANT": "production"
},
@@ -46,7 +50,10 @@
"submit": {
"production": {
"ios": {
"ascAppId": "6761315631"
"ascAppId": "6787819824"
},
"android": {
"track": "internal"
}
}
}
+18 -18
View File
@@ -199,24 +199,24 @@
--font-bold: "DMSans_700Bold";
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
--text-3xs: 10px;
--text-3xs--line-height: 13px;
--text-2xs: 11px;
--text-2xs--line-height: 15px;
--text-xs: 12px;
--text-xs--line-height: 16px;
--text-sm: 13px;
--text-sm--line-height: 18px;
--text-base: 15px;
--text-base--line-height: 22px;
--text-lg: 17px;
--text-lg--line-height: 22px;
--text-xl: 20px;
--text-xl--line-height: 26px;
--text-2xl: 24px;
--text-2xl--line-height: 30px;
--text-3xl: 28px;
--text-3xl--line-height: 34px;
--text-3xs: 11px;
--text-3xs--line-height: 14px;
--text-2xs: 12px;
--text-2xs--line-height: 16px;
--text-xs: 13px;
--text-xs--line-height: 17px;
--text-sm: 14px;
--text-sm--line-height: 19px;
--text-base: 16px;
--text-base--line-height: 23px;
--text-lg: 18px;
--text-lg--line-height: 23px;
--text-xl: 21px;
--text-xl--line-height: 28px;
--text-2xl: 26px;
--text-2xl--line-height: 32px;
--text-3xl: 30px;
--text-3xl--line-height: 36px;
}
/* ─── Custom utilities ──────────────────────────────────────────────── */
+10 -1
View File
@@ -1,2 +1,11 @@
import { registerRootComponent } from "expo";
import "react-native-gesture-handler";
import "expo-router/entry";
import { featureFlags } from "react-native-screens";
import App from "./src/App";
// Required for react-native-screens' iOS FormSheet sizing fix when a nested
// native stack is rendered inside a non-fitToContents formSheet.
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
registerRootComponent(App);
@@ -47,6 +47,7 @@ public class T3ComposerEditorModule: Module {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange"
)
@@ -63,6 +63,24 @@ private final class ComposerTextView: UITextView {
var onPasteImages: (([String]) -> Void)?
var onAttributedMutation: (() -> Void)?
var onSubmit: (() -> Void)?
override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
let submit = UIKeyCommand(
input: "\r",
modifierFlags: .command,
action: #selector(submitMessage(_:))
)
submit.discoverabilityTitle = "Send Message"
submit.wantsPriorityOverSystemBehavior = true
commands.append(submit)
return commands
}
@objc private func submitMessage(_ sender: UIKeyCommand) {
onSubmit?()
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(paste(_:)) {
@@ -299,6 +317,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
let onComposerSelectionChange = EventDispatcher()
let onComposerFocus = EventDispatcher()
let onComposerBlur = EventDispatcher()
let onComposerSubmit = EventDispatcher()
let onComposerPasteImages = EventDispatcher()
let onComposerContentSizeChange = EventDispatcher()
@@ -320,6 +339,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
textView.onAttributedMutation = { [weak self] in
self?.emitTextChange()
}
textView.onSubmit = { [weak self] in
self?.onComposerSubmit([:])
}
addSubview(textView)
placeholderLabel.numberOfLines = 0
@@ -26,6 +26,15 @@ function nodeKey(node: MarkdownNode, index: number): string {
return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
}
/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
return Math.max(10, Math.round(textStyle.fontSize * 0.8));
}
function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
return codeBlockFontSize(textStyle) + 6;
}
function nodeText(node: MarkdownNode): string {
if (node.content !== undefined) {
return node.content;
@@ -161,8 +170,8 @@ function HighlightedCodeText(props: {
style={{
color: props.textStyle.codeColor,
fontFamily: "ui-monospace",
fontSize: 12,
lineHeight: 18,
fontSize: codeBlockFontSize(props.textStyle),
lineHeight: codeBlockLineHeight(props.textStyle),
}}
>
{props.content}
@@ -196,8 +205,8 @@ function HighlightedCodeText(props: {
style={{
color: props.textStyle.codeColor,
fontFamily: "ui-monospace",
fontSize: 12,
lineHeight: 18,
fontSize: codeBlockFontSize(props.textStyle),
lineHeight: codeBlockLineHeight(props.textStyle),
}}
>
{keyedLines.map((line, lineIndex) => (
@@ -264,7 +273,7 @@ function NativeCodeBlock(props: {
flex: 1,
color: props.textStyle.mutedColor,
fontFamily: "ui-monospace",
fontSize: 12,
fontSize: codeBlockFontSize(props.textStyle),
}}
>
{languageLabel}
@@ -32,11 +32,25 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
].join(":");
}
const DEFAULT_BODY_FONT_SIZE = 15;
const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
const index = Math.max(0, Math.min(5, headingLevel - 1));
const configured = textStyle.headingFontSizes?.[index];
if (typeof configured === "number" && Number.isFinite(configured)) {
return configured;
}
const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
}
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
const isFile = run.fileIcon != null;
const isSkill = run.skillName != null;
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
const isHeading = run.role === "heading";
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
const hasParagraphStyle = run.headIndent !== undefined;
@@ -88,7 +102,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
: isHeading
? headingFontSize
: run.role === "code-language"
? 11
? Math.max(10, Math.round(textStyle.fontSize * 0.73))
: run.code || isCodeBlock
? Math.max(12, textStyle.fontSize - 2)
: textStyle.fontSize,
@@ -98,9 +112,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
: run.role === "list-break"
? textStyle.lineHeight + (run.spacing ?? 0)
: isHeading
? Math.max(headingFontSize + 6, 20)
? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
: isCodeBlock
? 18
? Math.max(16, textStyle.lineHeight - 2)
: textStyle.lineHeight,
fontStyle: run.italic ? "italic" : "normal",
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
@@ -148,6 +162,9 @@ export function NativeMarkdownSelectableText(props: {
// color-only child update can otherwise leave the previous appearance cached.
const appearanceKey = [
colorScheme ?? "unspecified",
props.textStyle.fontSize,
props.textStyle.lineHeight,
props.textStyle.headingFontSizes?.join(","),
props.textStyle.color,
props.textStyle.strongColor,
props.textStyle.mutedColor,
@@ -16,6 +16,7 @@ export interface NativeMarkdownTextStyle {
readonly fontFamily: string;
readonly headingFontFamily: string;
readonly boldFontFamily: string;
readonly headingFontSizes?: ReadonlyArray<number>;
}
export interface MarkdownHighlightedToken {
@@ -0,0 +1,6 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
}
}
@@ -0,0 +1,62 @@
import ExpoModulesCore
import UIKit
public final class T3HeaderButtonView: ExpoView {
private static let size: CGFloat = 44
private static let symbolSize: CGFloat = 18
private let button = UIButton(type: .system)
private var systemImage = "circle"
let onTriggered = EventDispatcher()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
isAccessibilityElement = false
button.frame = bounds
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
addSubview(button)
applyConfiguration()
}
public override var intrinsicContentSize: CGSize {
CGSize(width: Self.size, height: Self.size)
}
public func setLabel(_ label: String) {
button.accessibilityLabel = label
}
public func setSystemImage(_ systemImage: String) {
guard self.systemImage != systemImage else {
return
}
self.systemImage = systemImage
applyConfiguration()
}
private func applyConfiguration() {
var configuration: UIButton.Configuration
if #available(iOS 26.0, *) {
configuration = .glass()
configuration.cornerStyle = .capsule
} else {
configuration = .plain()
}
configuration.baseForegroundColor = .label
configuration.contentInsets = .zero
configuration.image = UIImage(systemName: systemImage)
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
pointSize: Self.symbolSize,
weight: .regular
)
button.configuration = configuration
}
@objc private func handlePress() {
onTriggered()
}
}
@@ -0,0 +1,131 @@
import ExpoModulesCore
import UIKit
public final class T3KeyboardCommandsModule: Module {
public func definition() -> ModuleDefinition {
Name("T3KeyboardCommands")
View(T3KeyboardCommandsView.self) {
Prop("enabledCommands") { (view: T3KeyboardCommandsView, commands: [String]) in
view.setEnabledCommands(commands)
}
Events("onCommand")
}
}
}
public final class T3KeyboardCommandsView: ExpoView {
let onCommand = EventDispatcher()
private var enabledCommands = Set<String>()
public override var canBecomeFirstResponder: Bool { true }
public override var keyCommands: [UIKeyCommand]? {
[
enabledCommand("newTask", input: "n", modifiers: .command, action: #selector(newTask), title: "New Task"),
enabledCommand("focusSearch", input: "f", modifiers: .command, action: #selector(focusSearch), title: "Find"),
enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"),
enabledCommand("back", input: "[", modifiers: .command, action: #selector(goBack), title: "Back"),
enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"),
enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"),
enabledCommand("review", input: "r", modifiers: [.command, .shift], action: #selector(openReview), title: "Open Review"),
enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"),
].compactMap { $0 }
}
func setEnabledCommands(_ commands: [String]) {
enabledCommands = Set(commands)
if isFirstResponder {
resignFirstResponder()
}
reclaimFirstResponderIfAvailable()
}
private func enabledCommand(
_ identifier: String,
input: String,
modifiers: UIKeyModifierFlags,
action: Selector,
title: String
) -> UIKeyCommand? {
guard enabledCommands.contains(identifier) else { return nil }
return command(input, modifiers: modifiers, action: action, title: title)
}
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UITextView.textDidEndEditingNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UITextField.textDidEndEditingNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public override func didMoveToWindow() {
super.didMoveToWindow()
reclaimFirstResponderIfAvailable()
}
public override func layoutSubviews() {
super.layoutSubviews()
reclaimFirstResponderIfAvailable()
}
private func command(
_ input: String,
modifiers: UIKeyModifierFlags,
action: Selector,
title: String
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
command.discoverabilityTitle = title
command.wantsPriorityOverSystemBehavior = true
return command
}
@objc private func newTask() { emit("newTask") }
@objc private func focusSearch() { emit("focusSearch") }
@objc private func goBack() { emit("back") }
@objc private func openFiles() { emit("files") }
@objc private func openTerminal() { emit("terminal") }
@objc private func openReview() { emit("review") }
@objc private func handleToggleSidebar() { emit("toggleSidebar") }
private func emit(_ command: String) {
onCommand(["command": command])
}
@objc private func reclaimFirstResponderIfAvailable() {
DispatchQueue.main.async { [weak self] in
guard let self, self.window?.t3FirstResponder == nil else { return }
self.becomeFirstResponder()
}
}
}
private extension UIView {
var t3FirstResponder: UIResponder? {
if isFirstResponder { return self }
for subview in subviews {
if let responder = subview.t3FirstResponder { return responder }
}
return nil
}
}
@@ -0,0 +1,19 @@
Pod::Spec.new do |s|
s.name = 'T3NativeControls'
s.version = '1.0.0'
s.summary = 'Native UIKit controls for T3 Code mobile.'
s.description = 'UIKit-backed controls that match native iOS navigation chrome.'
s.author = 'T3 Tools'
s.homepage = 'https://t3tools.com'
s.platforms = {
:ios => '18.0',
}
s.source = { :path => '.' }
s.static_framework = true
s.dependency 'ExpoModulesCore'
s.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES',
}
s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
end
@@ -0,0 +1,18 @@
import ExpoModulesCore
public final class T3NativeControlsModule: Module {
public func definition() -> ModuleDefinition {
Name("T3NativeControls")
View(T3HeaderButtonView.self) {
Prop("label") { (view: T3HeaderButtonView, label: String) in
view.setLabel(label)
}
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
view.setSystemImage(systemImage)
}
Events("onTriggered")
}
}
}
@@ -5,22 +5,14 @@ public class T3ReviewDiffModule: Module {
Name("T3ReviewDiffSurface")
View(T3ReviewDiffView.self) {
Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
view.setRowsJson(rowsJson)
}
Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
view.setTokensPatchJson(tokensPatchJson)
}
Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
view.setTokensResetKey(tokensResetKey)
}
Prop("contentResetKey") { (view: T3ReviewDiffView, contentResetKey: String) in
view.setContentResetKey(contentResetKey)
}
Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
}
@@ -61,7 +53,42 @@ public class T3ReviewDiffModule: Module {
view.setInitialRowIndex(initialRowIndex)
}
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
Prop("refreshing") { (view: T3ReviewDiffView, refreshing: Bool) in
view.setRefreshing(refreshing)
}
Events(
"onDebug",
"onVisibleFileChange",
"onToggleFile",
"onToggleViewedFile",
"onPressLine",
"onToggleComment",
"onPullToRefresh"
)
AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in
view.scrollToFile(fileId, animated: animated)
}
AsyncFunction("scrollToTop") { (view: T3ReviewDiffView, animated: Bool) in
view.scrollToTop(animated: animated)
}
// Large, frequently changing JSON values cannot be regular Fabric props. Expo's
// prop adapter compares strings on the main thread before invoking a setter, which
// makes a syntax-token patch capable of blocking a frame by itself.
AsyncFunction("setRowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
view.setRowsJson(rowsJson)
}
AsyncFunction("setTokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
view.setTokensPatchJson(tokensPatchJson)
}
}
}
}
@@ -1,7 +1,7 @@
import ExpoModulesCore
import UIKit
private struct ReviewDiffNativeRow: Decodable {
private struct ReviewDiffNativeRow: Decodable, Sendable {
let kind: String
let id: String
let fileId: String?
@@ -21,18 +21,18 @@ private struct ReviewDiffNativeRow: Decodable {
let commentSectionTitle: String?
}
private struct ReviewDiffNativeWordDiffRange: Decodable {
private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
let start: Int
let end: Int
}
private struct ReviewDiffNativeToken: Decodable {
private struct ReviewDiffNativeToken: Decodable, Sendable {
let content: String
let color: String?
let fontStyle: Int?
}
private struct ReviewDiffNativeTokenPatch: Decodable {
private struct ReviewDiffNativeTokenPatch: Decodable, Sendable {
let resetKey: String?
let chunkIndex: Int?
let tokensByRowId: [String: [ReviewDiffNativeToken]]?
@@ -312,6 +312,10 @@ private struct ReviewDiffNativeStyle {
}
public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private let payloadDecodeQueue = DispatchQueue(
label: "com.t3tools.review-diff.payload-decode",
qos: .userInitiated
)
private let scrollView = UIScrollView()
private let contentView = ReviewDiffContentView()
private var rows: [ReviewDiffNativeRow] = []
@@ -323,14 +327,25 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private var lastMetricsDebugKey = ""
private var lastVisibleRangeDebugKey = ""
private var tokensResetKey = ""
private var contentResetKey = ""
private var initialRowIndex: Int?
private var hasAppliedInitialRowIndex = false
private var lastVisibleFileId: String?
private var pendingScrollFileId: String?
private var pendingScrollAnimated = false
private var isProgrammaticScrollActive = false
private var rowsDecodeGeneration = 0
private var tokensDecodeGeneration = 0
let onDebug = EventDispatcher()
let onVisibleFileChange = EventDispatcher()
let onToggleFile = EventDispatcher()
let onToggleViewedFile = EventDispatcher()
let onPressLine = EventDispatcher()
let onToggleComment = EventDispatcher()
let onPullToRefresh = EventDispatcher()
private let pullRefreshControl = UIRefreshControl()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
@@ -345,6 +360,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
scrollView.showsVerticalScrollIndicator = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.backgroundColor = contentView.theme.background
pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
scrollView.refreshControl = pullRefreshControl
addSubview(scrollView)
contentView.backgroundColor = contentView.theme.background
@@ -379,6 +396,13 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
updateViewportFrame()
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// A direct gesture takes ownership from any interrupted programmatic jump.
// Resume visible-file events immediately so the inspector follows the finger.
isProgrammaticScrollActive = false
contentView.isVerticalScrollActive = true
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard !decelerate else {
return
@@ -396,77 +420,125 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
}
func setRowsJson(_ rowsJson: String) {
guard let data = rowsJson.data(using: .utf8) else {
return
}
rowsDecodeGeneration += 1
let generation = rowsDecodeGeneration
do {
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
contentView.rows = rows
hasAppliedInitialRowIndex = false
emitDebug("rows-decoded", [
"rows": rows.count,
"firstKind": rows.first?.kind ?? "none",
])
updateContentMetrics()
} catch {
rows = []
contentView.rows = []
hasAppliedInitialRowIndex = false
updateContentMetrics()
emitDebug("rows-decode-failed", [
"error": error.localizedDescription,
])
payloadDecodeQueue.async { [weak self] in
guard let data = rowsJson.data(using: .utf8) else {
return
}
do {
let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.rowsDecodeGeneration else {
return
}
self.rows = decodedRows
self.contentView.rows = decodedRows
self.hasAppliedInitialRowIndex = false
self.lastVisibleFileId = nil
self.emitDebug("rows-decoded", [
"rows": decodedRows.count,
"firstKind": decodedRows.first?.kind ?? "none",
])
self.updateContentMetrics()
self.applyPendingScrollIfNeeded()
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.rowsDecodeGeneration else {
return
}
self.rows = []
self.contentView.rows = []
self.hasAppliedInitialRowIndex = false
self.lastVisibleFileId = nil
self.pendingScrollFileId = nil
self.updateContentMetrics()
self.emitDebug("rows-decode-failed", ["error": message])
}
}
}
}
func setTokensJson(_ tokensJson: String) {
guard let data = tokensJson.data(using: .utf8) else {
return
}
tokensDecodeGeneration += 1
let generation = tokensDecodeGeneration
do {
contentView.tokensByRowId = try JSONDecoder().decode(
[String: [ReviewDiffNativeToken]].self,
from: data
)
} catch {
contentView.tokensByRowId = [:]
emitDebug("tokens-decode-failed", [
"error": error.localizedDescription,
])
payloadDecodeQueue.async { [weak self] in
guard let data = tokensJson.data(using: .utf8) else {
return
}
do {
let decodedTokens = try JSONDecoder().decode(
[String: [ReviewDiffNativeToken]].self,
from: data
)
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.tokensDecodeGeneration else {
return
}
self.contentView.tokensByRowId = decodedTokens
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.tokensDecodeGeneration else {
return
}
self.contentView.tokensByRowId = [:]
self.emitDebug("tokens-decode-failed", ["error": message])
}
}
}
}
func setTokensPatchJson(_ tokensPatchJson: String) {
guard let data = tokensPatchJson.data(using: .utf8) else {
return
}
let contentResetKey = self.contentResetKey
do {
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
if let resetKey = patch.resetKey, resetKey != tokensResetKey {
tokensResetKey = resetKey
contentView.tokensByRowId = [:]
}
let tokensByRowId = patch.tokensByRowId ?? [:]
if tokensByRowId.isEmpty {
payloadDecodeQueue.async { [weak self] in
guard let data = tokensPatchJson.data(using: .utf8) else {
return
}
contentView.mergeTokensByRowId(tokensByRowId)
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
emitDebug("tokens-patch-decoded", [
"chunkIndex": chunkIndex,
"rows": tokensByRowId.count,
"totalRows": contentView.tokensByRowId.count,
])
do {
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
DispatchQueue.main.async { [weak self] in
guard let self else {
return
}
guard contentResetKey == self.contentResetKey else {
return
}
// A highlighter request from the previous file can finish after the view has
// already reset. Never let that stale patch roll the native token state back.
if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {
return
}
let tokensByRowId = patch.tokensByRowId ?? [:]
if tokensByRowId.isEmpty {
return
}
self.contentView.mergeTokensByRowId(tokensByRowId)
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
self.emitDebug("tokens-patch-decoded", [
"chunkIndex": chunkIndex,
"rows": tokensByRowId.count,
"totalRows": self.contentView.tokensByRowId.count,
])
}
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
self?.emitDebug("tokens-patch-decode-failed", ["error": message])
}
}
} catch {
emitDebug("tokens-patch-decode-failed", [
"error": error.localizedDescription,
])
}
}
@@ -482,6 +554,27 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
])
}
func setContentResetKey(_ contentResetKey: String) {
guard contentResetKey != self.contentResetKey else {
return
}
self.contentResetKey = contentResetKey
rowsDecodeGeneration += 1
tokensDecodeGeneration += 1
contentView.tokensByRowId = [:]
rows = []
contentView.rows = []
hasAppliedInitialRowIndex = false
pendingScrollFileId = nil
isProgrammaticScrollActive = false
scrollView.setContentOffset(.zero, animated: false)
updateContentMetrics()
updateViewportFrame()
lastVisibleFileId = nil
applyInitialRowIndexIfNeeded()
}
func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) {
let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson)
let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds)
@@ -573,6 +666,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.invalidateVisibleViewport()
contentView.setNeedsDisplay()
applyInitialRowIndexIfNeeded()
applyPendingScrollIfNeeded()
emitVisibleFileIfNeeded()
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
if debugKey != lastMetricsDebugKey {
@@ -596,11 +691,41 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
}
private func finishVerticalScroll() {
isProgrammaticScrollActive = false
contentView.isVerticalScrollActive = false
updateViewportFrame()
emitVisibleRange(reason: "scroll-end")
}
private func emitVisibleFileIfNeeded() {
// Keep the explicit destination selected while UIKit animates through the files
// between the old and new offsets. Emitting every intermediate header forces a
// React render per crossing and makes the navigator visibly flash.
guard !isProgrammaticScrollActive else {
return
}
// The top of the combined diff is the explicit "All files" destination.
// Treat it as a first-class selection instead of immediately resolving the
// first file header and undoing the navigator's optimistic selection.
if scrollView.contentOffset.y <= 0.5 {
guard lastVisibleFileId != nil else {
return
}
lastVisibleFileId = nil
onVisibleFileChange(["fileId": NSNull()])
return
}
guard let fileId = contentView.visibleFileId(atVerticalOffset: scrollView.contentOffset.y),
fileId != lastVisibleFileId else {
return
}
lastVisibleFileId = fileId
onVisibleFileChange(["fileId": fileId])
}
private func emitVisibleRange(reason: String) {
guard let range = contentView.currentVisibleRowRange() else {
return
@@ -670,6 +795,33 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
applyInitialRowIndexIfNeeded()
}
func scrollToFile(_ fileId: String, animated: Bool) {
pendingScrollFileId = fileId
pendingScrollAnimated = animated
applyPendingScrollIfNeeded()
}
func scrollToTop(animated: Bool) {
pendingScrollFileId = nil
pendingScrollAnimated = false
setVerticalContentOffset(0, animated: animated)
}
@objc private func handlePullToRefresh() {
onPullToRefresh([:])
}
/// Driven from JS: set to false once the reload completes to dismiss the spinner.
func setRefreshing(_ refreshing: Bool) {
if refreshing {
if !pullRefreshControl.isRefreshing {
pullRefreshControl.beginRefreshing()
}
} else if pullRefreshControl.isRefreshing {
pullRefreshControl.endRefreshing()
}
}
private func applyStyle() {
contentView.style = ReviewDiffNativeStyle
.resolve(stylePayload)
@@ -686,6 +838,38 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
)
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
emitVisibleFileIfNeeded()
}
private func applyPendingScrollIfNeeded() {
guard let fileId = pendingScrollFileId,
bounds.height > 0 else {
return
}
guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else {
if !rows.isEmpty {
pendingScrollFileId = nil
}
return
}
let animated = pendingScrollAnimated
pendingScrollFileId = nil
pendingScrollAnimated = false
setVerticalContentOffset(headerOffset, animated: animated)
}
private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) {
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
let clampedOffset = min(max(targetOffset, 0), maxOffset)
let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5
isProgrammaticScrollActive = shouldAnimate
contentView.isVerticalScrollActive = shouldAnimate
scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)
if !shouldAnimate {
updateViewportFrame()
}
}
private func applyInitialRowIndexIfNeeded() {
@@ -1255,6 +1439,32 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
return rowOffsets[rowIndex]
}
func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? {
guard let firstHeaderRowIndex = fileHeaderRowIndices.first else {
return nil
}
var lowerBound = 0
var upperBound = fileHeaderRowIndices.count
while lowerBound < upperBound {
let midpoint = (lowerBound + upperBound) / 2
let rowIndex = fileHeaderRowIndices[midpoint]
if rowOffsets[rowIndex] <= verticalOffset + 0.5 {
lowerBound = midpoint + 1
} else {
upperBound = midpoint
}
}
let rowIndex = lowerBound > 0
? fileHeaderRowIndices[lowerBound - 1]
: firstHeaderRowIndex
guard rows.indices.contains(rowIndex) else {
return nil
}
return resolvedFileId(for: rows[rowIndex])
}
private func fileHeaderRowIndex(forFileId fileId: String) -> Int? {
fileHeaderRowIndices.first { rowIndex in
rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId
@@ -7,6 +7,12 @@ class T3TerminalModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3TerminalSurface")
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
// logs so a stale native binary is distinguishable from a broken key pipeline.
Constants(
"hardwareKeyRevision" to 2,
)
View(T3TerminalView::class) {
Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->
view.terminalKey = terminalKey
@@ -20,6 +26,10 @@ class T3TerminalModule : Module() {
view.fontSize = fontSize.toFloat()
}
Prop("focusRequest") { view: T3TerminalView, focusRequest: Double ->
view.focusRequest = focusRequest
}
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
view.appearanceScheme = appearanceScheme
}
@@ -62,6 +62,15 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
var themeConfig: String = ""
var focusRequest: Double = 0.0
set(value) {
val previous = field
field = value
if (value != previous && value > 0) {
requestKeyboardFocus()
}
}
var backgroundColorHex: String = "#24292E"
set(value) {
field = value
@@ -113,11 +122,19 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
}
inputView.setOnKeyListener { _, keyCode, event ->
if (event.action != android.view.KeyEvent.ACTION_DOWN) return@setOnKeyListener false
when (keyCode) {
android.view.KeyEvent.KEYCODE_DEL -> {
when {
keyCode == android.view.KeyEvent.KEYCODE_DEL -> {
onInput(mapOf("data" to "\u007F"))
true
}
// Hardware keyboard Ctrl+A..Z -> control bytes 0x01..0x1A (Ctrl+C, Ctrl+Z, ...).
event.isCtrlPressed &&
keyCode in android.view.KeyEvent.KEYCODE_A..android.view.KeyEvent.KEYCODE_Z -> {
onInput(
mapOf("data" to (keyCode - android.view.KeyEvent.KEYCODE_A + 1).toChar().toString()),
)
true
}
else -> false
}
}
@@ -4,6 +4,12 @@ public class T3TerminalModule: Module {
public func definition() -> ModuleDefinition {
Name("T3TerminalSurface")
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
// logs so a stale native binary is distinguishable from a broken key pipeline.
Constants([
"hardwareKeyRevision": 2,
])
View(T3TerminalView.self) {
Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in
view.terminalKey = terminalKey
@@ -17,6 +23,10 @@ public class T3TerminalModule: Module {
view.fontSize = CGFloat(fontSize)
}
Prop("focusRequest") { (view: T3TerminalView, focusRequest: Double) in
view.focusRequest = focusRequest
}
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
view.appearanceScheme = appearanceScheme
}
@@ -22,13 +22,129 @@ private enum GhosttyRuntime {
}
}
/// Encodes hardware-keyboard combos that UITextField never surfaces through its
/// text-editing delegate (control combos, Escape, Tab, arrow keys) into the byte
/// sequences a terminal expects.
///
/// Capture uses UIKeyCommand with `wantsPriorityOverSystemBehavior` rather than
/// `pressesBegan`: while a text field is first responder, iPadOS routes hardware key
/// events through the text-input system, which can consume presses before they reach
/// responder press callbacks. Registered key commands are matched deterministically
/// before that happens.
private enum TerminalHardwareKeyEncoder {
/// Characters that produce a control byte when combined with Ctrl.
private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? "
static func makeKeyCommands(action: Selector) -> [UIKeyCommand] {
var commands: [UIKeyCommand] = []
let specialInputs = [
UIKeyCommand.inputEscape,
UIKeyCommand.inputUpArrow,
UIKeyCommand.inputDownArrow,
UIKeyCommand.inputLeftArrow,
UIKeyCommand.inputRightArrow,
"\t",
]
for input in specialInputs {
commands.append(makeCommand(input: input, modifierFlags: [], action: action))
}
commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action))
for character in controlInputs {
commands.append(makeCommand(input: String(character), modifierFlags: .control, action: action))
commands.append(
makeCommand(input: String(character), modifierFlags: [.control, .shift], action: action)
)
}
return commands
}
private static func makeCommand(
input: String,
modifierFlags: UIKeyModifierFlags,
action: Selector
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action)
command.wantsPriorityOverSystemBehavior = true
return command
}
static func sequence(input: String, modifiers: UIKeyModifierFlags) -> String? {
switch input {
case UIKeyCommand.inputEscape:
return "\u{1B}"
case UIKeyCommand.inputUpArrow:
return "\u{1B}[A"
case UIKeyCommand.inputDownArrow:
return "\u{1B}[B"
case UIKeyCommand.inputRightArrow:
return "\u{1B}[C"
case UIKeyCommand.inputLeftArrow:
return "\u{1B}[D"
case "\t":
return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t"
default:
break
}
guard modifiers.contains(.control) else { return nil }
guard let scalar = input.lowercased().unicodeScalars.first else { return nil }
return controlSequence(for: scalar)
}
private static func controlSequence(for scalar: Unicode.Scalar) -> String? {
switch scalar {
case "a"..."z":
// Ctrl+A..Z -> 0x01..0x1A (Ctrl+C = ETX, Ctrl+Z = SUB, ...).
return UnicodeScalar(scalar.value - 96).map(String.init)
case " ", "@":
return "\u{00}"
case "[":
return "\u{1B}"
case "\\":
return "\u{1C}"
case "]":
return "\u{1D}"
case "^":
return "\u{1E}"
case "_", "-":
return "\u{1F}"
case "?":
return "\u{7F}"
default:
return nil
}
}
}
private final class TerminalInputField: UITextField {
var onDeleteBackward: (() -> Void)?
var onInsert: ((String) -> Void)?
private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands(
action: #selector(handleHardwareKeyCommand(_:))
)
override var keyCommands: [UIKeyCommand]? {
Self.hardwareKeyCommands
}
override func deleteBackward() {
onDeleteBackward?()
super.deleteBackward()
}
@objc
private func handleHardwareKeyCommand(_ command: UIKeyCommand) {
guard let input = command.input else { return }
guard let sequence = TerminalHardwareKeyEncoder.sequence(
input: input,
modifiers: command.modifierFlags
) else { return }
onInsert?(sequence)
}
}
private enum TerminalAppearanceScheme: String {
@@ -108,6 +224,15 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
}
}
var focusRequest: Double = 0 {
didSet {
guard oldValue != focusRequest else { return }
DispatchQueue.main.async { [weak self] in
self?.requestKeyboardFocus()
}
}
}
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
didSet {
guard oldValue != appearanceScheme else { return }
@@ -167,6 +292,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
inputField.onDeleteBackward = { [weak self] in
self?.emitInput("\u{7F}")
}
inputField.onInsert = { [weak self] data in
self?.emitInput(data)
}
focusTapGesture.addTarget(self, action: #selector(handleViewportTap))
terminalViewport.addGestureRecognizer(focusTapGesture)
+31 -20
View File
@@ -5,7 +5,7 @@
"main": "index.ts",
"scripts": {
"dev": "expo start --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear",
"start": "expo start",
"start:dev": "APP_VARIANT=development expo start",
"start:preview": "APP_VARIANT=preview expo start",
@@ -43,12 +43,16 @@
"@clerk/expo": "catalog:",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/ui": "~56.0.8",
"@expo/metro-runtime": "~56.0.15",
"@expo/ui": "~56.0.18",
"@legendapp/list": "3.2.0",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
"@react-native-menu/menu": "^2.0.0",
"@react-navigation/elements": "2.9.26",
"@react-navigation/native": "7.3.4",
"@react-navigation/native-stack": "7.17.6",
"@shikijs/core": "4.2.0",
"@shikijs/engine-javascript": "4.2.0",
"@shikijs/langs": "4.2.0",
@@ -62,38 +66,37 @@
"clsx": "^2.1.1",
"diff": "8.0.3",
"effect": "catalog:",
"expo": "^56.0.0",
"expo-asset": "~56.0.15",
"expo-auth-session": "~56.0.12",
"expo-build-properties": "~56.0.15",
"expo-camera": "~56.0.7",
"expo-clipboard": "~56.0.3",
"expo-constants": "~56.0.16",
"expo": "~56.0.12",
"expo-asset": "~56.0.17",
"expo-auth-session": "~56.0.14",
"expo-build-properties": "~56.0.19",
"expo-camera": "~56.0.8",
"expo-clipboard": "~56.0.4",
"expo-constants": "~56.0.18",
"expo-crypto": "~56.0.4",
"expo-dev-client": "~56.0.16",
"expo-file-system": "~56.0.7",
"expo-font": "~56.0.5",
"expo-dev-client": "~56.0.20",
"expo-file-system": "~56.0.8",
"expo-font": "~56.0.7",
"expo-glass-effect": "~56.0.4",
"expo-haptics": "~56.0.3",
"expo-image-picker": "~56.0.14",
"expo-linking": "~56.0.12",
"expo-image-picker": "~56.0.18",
"expo-linking": "~56.0.14",
"expo-network": "~56.0.5",
"expo-notifications": "~56.0.14",
"expo-notifications": "~56.0.18",
"expo-paste-input": "^0.1.15",
"expo-router": "~56.2.7",
"expo-secure-store": "~56.0.4",
"expo-splash-screen": "~56.0.10",
"expo-symbols": "~56.0.5",
"expo-updates": "~56.0.17",
"expo-symbols": "~56.0.6",
"expo-updates": "~56.0.19",
"expo-web-browser": "~56.0.5",
"expo-widgets": "~56.0.15",
"expo-widgets": "~56.0.19",
"punycode": "^2.3.1",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.85.3",
"react-native-gesture-handler": "~2.31.1",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.21.7",
"react-native-keyboard-controller": "1.21.13",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "0.35.9",
"react-native-reanimated": "4.3.1",
@@ -117,5 +120,13 @@
},
"overrides": {
"react-native-nitro-markdown": "file:deps/react-native-nitro-markdown-0.5.0.tgz"
},
"expo": {
"autolinking": {
"buildFromSource": [
"react-native-screens",
"@react-native-menu/menu"
]
}
}
}
@@ -0,0 +1,81 @@
"use strict";
// Bundle the widget asset catalog into an app-extension (widget) target.
//
// expo-widgets generates the widget target without a Resources build phase, and
// hand-adding a PBXResourcesBuildPhase does NOT get picked up — xcodebuild's
// planner never schedules `actool` for it (verified: even a full re-plan skips
// it). So instead we add a shell-script phase that runs `actool` directly and
// drops the compiled Assets.car into the extension bundle. Marked
// alwaysOutOfDate so the build system always runs it.
//
// Idempotent across re-runs. Returns true when it added the phase, false when
// it was already present. Throws when the target does not exist — that means
// this ran before expo-widgets created the target (plugin ordering bug) and
// silently skipping would ship a widget without its assets.
const PHASE_NAME = "Compile Widget Assets";
// Compiles ExpoWidgetsTarget/Assets.xcassets into the extension's resources dir.
// Uses only Xcode-provided build settings so it works for device + simulator.
const ACTOOL_SCRIPT = [
"set -e",
'CATALOG="${SRCROOT}/ExpoWidgetsTarget/Assets.xcassets"',
'if [ ! -d "$CATALOG" ]; then',
' echo "error: widget asset catalog not found at $CATALOG (expo-widgets wiped it? check plugin ordering in app.config.ts)"',
" exit 1",
"fi",
'DEST="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"',
'mkdir -p "$DEST"',
'xcrun actool "$CATALOG" --compile "$DEST" --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET:-16.0}" --output-format human-readable-text',
].join("\n");
function stripComments(map) {
const out = {};
for (const key of Object.keys(map || {})) {
if (key.endsWith("_comment")) continue;
out[key] = map[key];
}
return out;
}
function findByName(map, name) {
for (const [uuid, value] of Object.entries(stripComments(map))) {
if (value && value.name === name) return { uuid, value };
}
return null;
}
/**
* @param {import('xcode').XcodeProject} proj
* @param {{ targetName: string }} opts
*/
function addWidgetAssetCatalog(proj, opts) {
const objects = proj.hash.project.objects;
const target = findByName(objects.PBXNativeTarget, opts.targetName);
if (!target) {
throw new Error(
`addWidgetAssetCatalog: target "${opts.targetName}" not found — ` +
"withWidgetLogoAsset must be registered before expo-widgets so its " +
"xcodeproj mod runs after the widget target is created.",
);
}
const phases = target.value.buildPhases || [];
const existing = objects.PBXShellScriptBuildPhase || {};
const already = Object.entries(stripComments(existing)).some(
([uuid, value]) =>
value && value.name === `"${PHASE_NAME}"` && phases.some((p) => p.value === uuid),
);
if (already) return false;
const { uuid } = proj.addBuildPhase([], "PBXShellScriptBuildPhase", PHASE_NAME, target.uuid, {
shellPath: "/bin/sh",
shellScript: ACTOOL_SCRIPT,
});
// Always run: input-analysis is exactly what skipped the Resources phase.
objects.PBXShellScriptBuildPhase[uuid].alwaysOutOfDate = 1;
return true;
}
module.exports = { addWidgetAssetCatalog };
@@ -0,0 +1,52 @@
const fs = require("node:fs");
const path = require("node:path");
const { withDangerousMod } = require("expo/config-plugins");
const MARKER = "# t3code: repair cached CocoaPods UUID allocation before SPM integration";
const UUID_REPAIR = `${MARKER}
pods_project = installer.pods_project
existing_uuids = pods_project.objects.map(&:uuid)
uuid_prefix = pods_project.instance_variable_get(:@uuid_prefix)[0, 6]
sequential_uuid = /\\A#{Regexp.escape(uuid_prefix)}([0-9A-F]{7})0\\z/
highest_index = existing_uuids.filter_map do |uuid|
match = sequential_uuid.match(uuid)
match && match[1].to_i(16)
end.max || -1
# Pod::Project generates sequential UUIDs without collision checks because CocoaPods
# normally creates the project in this process. EAS can restore Pods.xcodeproj from
# cache, leaving the allocator behind the loaded objects. React Native's SPM support
# then reuses an existing UUID and silently corrupts the project graph.
next_index = highest_index + 1
pods_project.instance_variable_set(:@generated_uuids, Array.new(next_index))
pods_project.instance_variable_set(:@available_uuids, [])
pods_project.generate_available_uuid_list(1_000)
Pod::UI.puts "T3Code: reset CocoaPods UUID allocator at #{next_index} (#{existing_uuids.length} existing objects)"
`;
module.exports = function withIosCocoaPodsUuidCache(config) {
return withDangerousMod(config, [
"ios",
(nextConfig) => {
const podfilePath = path.join(nextConfig.modRequest.platformProjectRoot, "Podfile");
const podfile = fs.readFileSync(podfilePath, "utf8");
if (podfile.includes(MARKER)) {
return nextConfig;
}
const postInstallStart = "post_install do |installer|\n";
if (!podfile.includes(postInstallStart)) {
throw new Error("Unable to repair CocoaPods UUID allocation: post_install is missing.");
}
fs.writeFileSync(
podfilePath,
podfile.replace(postInstallStart, `${postInstallStart}${UUID_REPAIR}`),
"utf8",
);
return nextConfig;
},
]);
};
@@ -0,0 +1,99 @@
const { withAppDelegate, withInfoPlist } = require("expo/config-plugins");
const SCENE_DELEGATE = `
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(
_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions
) {
guard
let windowScene = scene as? UIWindowScene,
let appDelegate = UIApplication.shared.delegate as? AppDelegate
else {
return
}
let appWindow: UIWindow
if let existingWindow = appDelegate.window {
appWindow = existingWindow
} else {
appWindow = UIWindow(windowScene: windowScene)
appDelegate.window = appWindow
appDelegate.reactNativeFactory?.startReactNative(
withModuleName: "main",
in: appWindow,
launchOptions: nil)
}
window = appWindow
appWindow.windowScene = windowScene
appWindow.makeKeyAndVisible()
if let url = connectionOptions.urlContexts.first?.url {
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
}
if let userActivity = connectionOptions.userActivities.first {
_ = appDelegate.application(
UIApplication.shared,
continue: userActivity,
restorationHandler: { _ in })
}
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard
let url = URLContexts.first?.url,
let appDelegate = UIApplication.shared.delegate as? AppDelegate
else {
return
}
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
_ = appDelegate.application(
UIApplication.shared,
continue: userActivity,
restorationHandler: { _ in })
}
}`;
module.exports = function withIosSceneLifecycle(config) {
config = withInfoPlist(config, (nextConfig) => {
nextConfig.modResults.UIApplicationSceneManifest = {
UIApplicationSupportsMultipleScenes: false,
UISceneConfigurations: {
UIWindowSceneSessionRoleApplication: [
{
UISceneConfigurationName: "Default Configuration",
UISceneDelegateClassName: "$(PRODUCT_MODULE_NAME).SceneDelegate",
},
],
},
};
return nextConfig;
});
return withAppDelegate(config, (nextConfig) => {
if (nextConfig.modResults.language !== "swift") {
throw new Error("The iOS scene lifecycle plugin requires a Swift AppDelegate.");
}
if (!nextConfig.modResults.contents.includes("class SceneDelegate:")) {
nextConfig.modResults.contents += SCENE_DELEGATE;
}
return nextConfig;
});
};
@@ -0,0 +1,68 @@
"use strict";
// Ships the branded T3 mark to the Live Activity / widget extension.
//
// expo-widgets generates ExpoWidgetsTarget without a Resources build phase and
// has no asset support, so this plugin (a) writes an SVG template image set into
// the generated widget asset catalog and (b) wires that catalog into the widget
// target with an actool build phase.
//
// ORDERING: must be listed BEFORE "expo-widgets" in the plugins array. Expo
// chains same-type mods so the last-registered runs FIRST; registering this
// plugin earlier makes its mods run AFTER expo-widgets' mods. That matters
// twice: expo-widgets' dangerous mod rmSync's ios/ExpoWidgetsTarget/ (deleting
// any catalog written before it), and its xcodeproj mod is what creates the
// widget target. Listed after expo-widgets, both steps silently no-op on a
// fresh prebuild — which is how prod build 8 shipped without the logo.
const path = require("path");
const fs = require("fs");
const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");
const { addWidgetAssetCatalog } = require("./lib/addWidgetAssetCatalog.cjs");
const TARGET_NAME = "ExpoWidgetsTarget";
const CATALOG_NAME = "Assets.xcassets";
const IMAGE_SET = "T3Mark.imageset";
const SVG_NAME = "T3Mark.svg";
const CATALOG_CONTENTS = JSON.stringify({ info: { author: "expo", version: 1 } }, null, 2) + "\n";
const IMAGE_SET_CONTENTS =
JSON.stringify(
{
images: [{ idiom: "universal", filename: SVG_NAME }],
info: { author: "expo", version: 1 },
properties: {
"preserves-vector-representation": true,
"template-rendering-intent": "template",
},
},
null,
2,
) + "\n";
function withAssetFiles(config) {
return withDangerousMod(config, [
"ios",
(cfg) => {
const source = path.join(cfg.modRequest.projectRoot, "assets", "widget", SVG_NAME);
const catalogDir = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, CATALOG_NAME);
const imageSetDir = path.join(catalogDir, IMAGE_SET);
fs.mkdirSync(imageSetDir, { recursive: true });
fs.writeFileSync(path.join(catalogDir, "Contents.json"), CATALOG_CONTENTS);
fs.writeFileSync(path.join(imageSetDir, "Contents.json"), IMAGE_SET_CONTENTS);
fs.copyFileSync(source, path.join(imageSetDir, SVG_NAME));
return cfg;
},
]);
}
function withAssetWiring(config) {
return withXcodeProject(config, (cfg) => {
addWidgetAssetCatalog(cfg.modResults, { targetName: TARGET_NAME });
return cfg;
});
}
module.exports = function withWidgetLogoAsset(config) {
return withAssetWiring(withAssetFiles(config));
};
@@ -0,0 +1,30 @@
"use strict";
// One-off: apply the widget asset-catalog wiring to the already-generated
// ios/ project so the current build compiles ExpoWidgetsTarget/Assets.xcassets
// without a full `expo prebuild`. The durable equivalent lives in
// plugins/withWidgetLogoAsset.cjs and runs on prebuild.
const path = require("path");
const fs = require("fs");
const xcodePath = require.resolve("xcode", {
paths: [
require.resolve("@expo/config-plugins", { paths: [require.resolve("expo/package.json")] }),
],
});
const xcode = require(xcodePath);
const { addWidgetAssetCatalog } = require("../plugins/lib/addWidgetAssetCatalog.cjs");
const pbxprojPath = path.join(__dirname, "..", "ios", "T3CodeDev.xcodeproj", "project.pbxproj");
const proj = xcode.project(pbxprojPath);
proj.parseSync();
const added = addWidgetAssetCatalog(proj, { targetName: "ExpoWidgetsTarget" });
if (added) {
fs.writeFileSync(pbxprojPath, proj.writeSync());
console.log("Added widget asset-compile phase to ExpoWidgetsTarget.");
} else {
console.log("No change: phase already present.");
}
+72
View File
@@ -0,0 +1,72 @@
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import * as Linking from "expo-linking";
import * as SplashScreen from "expo-splash-screen";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native";
import { RegistryContext } from "@effect/atom-react";
import { useEffect } from "react";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
import { useThemeColor } from "./lib/useThemeColor";
import "../global.css";
const appLinking = {
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
};
const Navigation = createStaticNavigation(RootStack);
export default function App() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
useEffect(() => {
if (fontsLoaded) SplashScreen.hide();
}, [fontsLoaded]);
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<AppearancePreferencesProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={statusBarBg}
translucent
/>
{/* The navigation theme drives the NATIVE header appearance: native-stack
forwards `dark` as the nav bar's overrideUserInterfaceStyle. Without
this, React Navigation defaults to its light theme and every native
header (glass buttons, title, materials) is forced light even when
the system is in dark mode. */}
<Navigation
linking={appLinking}
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
/>
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</AppearancePreferencesProvider>
</CloudAuthProvider>
</RegistryContext.Provider>
);
}
+463
View File
@@ -0,0 +1,463 @@
import {
createPathConfigForStaticNavigation,
getPathFromState,
NavigationState,
StackActions,
useNavigation,
} from "@react-navigation/native";
import {
createNativeStackNavigator,
createNativeStackScreen,
type NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "./components/AppText";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";
import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet";
import { ReviewSheet } from "./features/review/ReviewSheet";
import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen";
import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet";
import { GitCommitSheet } from "./features/threads/git/GitCommitSheet";
import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet";
import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet";
import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen";
import { ConnectionsRouteScreen } from "./features/connection/ConnectionsRouteScreen";
import { ConnectionsNewRouteScreen } from "./features/connection/ConnectionsNewRouteScreen";
import { HomeRouteScreen } from "./features/home/HomeRouteScreen";
import { AddProjectDestinationRoute } from "./features/projects/AddProjectDestinationRoute";
import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header
// background stay STATIC config while still adapting to appearance changes.
const SHEET_BACKGROUND_COLOR =
Platform.OS === "ios"
? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })
: undefined;
type AppScreenOptions = NativeStackNavigationOptions & {
readonly unstable_navigationItemStyle?: "editor";
};
// Shared header presets. Screens only override genuinely dynamic values (titles,
// subtitles, toolbar items, search callbacks) via NativeStackScreenOptions.
//
// GLASS: transparent header over the screen's primary scroll view, with the iOS 26
// scroll-edge blur sampling the content (Home, Thread, Files tree, settings sheet).
const GLASS_HEADER_OPTIONS: AppScreenOptions = {
headerBackButtonDisplayMode: "minimal",
headerBackTitle: "",
headerLargeTitle: false,
headerShadowVisible: false,
headerShown: true,
headerStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
headerTransparent: Platform.OS === "ios",
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
};
// SOLID: opaque sheet-colored header for surfaces whose content scrolls internally
// (file viewer, terminal, review) — there is nothing for glass to sample there.
const SOLID_HEADER_OPTIONS: AppScreenOptions = {
headerBackButtonDisplayMode: "minimal",
headerBackTitle: "",
headerLargeTitle: false,
headerShadowVisible: false,
headerShown: true,
headerStyle:
SHEET_BACKGROUND_COLOR !== undefined
? // native-stack types this as `string`, but the native side accepts any
// ColorValue including DynamicColorIOS.
{ backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
: undefined,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
headerTransparent: false,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
};
// Solid header variant for screens inside sheets (centered title, no editor style).
const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
...SOLID_HEADER_OPTIONS,
unstable_navigationItemStyle: undefined,
};
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "Settings",
screenOptions: {
...GLASS_HEADER_OPTIONS,
// Sheets read better with the iOS-default centered title (no editor style).
unstable_navigationItemStyle: undefined,
},
screens: {
Settings: createNativeStackScreen({
screen: SettingsRouteScreen,
linking: "",
options: {
title: "Settings",
},
}),
SettingsEnvironments: createNativeStackScreen({
screen: SettingsEnvironmentsRouteScreen,
linking: "environments",
options: {
title: "Environments",
},
}),
SettingsEnvironmentNew: createNativeStackScreen({
screen: ConnectionsNewRouteScreen,
linking: "environment-new",
options: {
title: "Add Environment",
},
}),
SettingsArchive: createNativeStackScreen({
screen: ArchivedThreadsRouteScreen,
linking: "archive",
options: {
title: "Archived Threads",
},
}),
SettingsAppearance: createNativeStackScreen({
screen: SettingsAppearanceRouteScreen,
linking: "appearance",
options: {
title: "Appearance",
},
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
options: {
title: "Sign in",
},
}),
SettingsWaitlist: createNativeStackScreen({
screen: SettingsWaitlistRouteScreen,
linking: "waitlist",
options: {
title: "Join the waitlist",
},
}),
},
});
// Thread routes live FLAT in the root stack (not in a nested navigator). A nested
// stack means a second UINavigationController with its own UINavigationBar, which
// breaks iOS 26's shared-header morphing between Home and Thread (each pair inside
// one bar morphs; across two bars the whole screen slides). Flat linking paths keep
// the same deep-link URLs the nested config produced.
const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
// New-task / add-project flow: nested navigator inside the formSheet (Settings-sheet
// pattern — a plain formSheet screen cannot render a stack header; the header and
// in-sheet pushes come from this nested stack).
const NewTaskSheetStack = createNativeStackNavigator({
initialRouteName: "NewTask",
screenOptions: {
...GLASS_HEADER_OPTIONS,
// Sheets read better with the iOS-default centered title (no editor style).
unstable_navigationItemStyle: undefined,
},
screens: {
NewTask: createNativeStackScreen({
screen: NewTaskRouteScreen,
linking: "",
options: {
title: "Choose project",
},
}),
NewTaskDraft: createNativeStackScreen({
screen: NewTaskDraftRouteScreen,
linking: "draft",
// The draft composer has no scroll view for glass to sample; a solid
// header also lays the content out below the bar (no manual inset).
options: SHEET_SOLID_HEADER_OPTIONS,
}),
AddProject: createNativeStackScreen({
screen: AddProjectSourceRoute,
linking: "add-project",
options: {
title: "Add Project",
},
}),
AddProjectRepository: createNativeStackScreen({
screen: AddProjectRepositoryRoute,
linking: "add-project/repository",
}),
AddProjectDestination: createNativeStackScreen({
screen: AddProjectDestinationRoute,
linking: "add-project/destination",
}),
AddProjectLocal: createNativeStackScreen({
screen: AddProjectLocalRoute,
linking: "add-project/local",
}),
},
});
// Routes presented as sheets/overlays ON TOP of the workspace. They must not
// influence the adaptive workspace layout: opening Settings over Home should
// not flip the sidebar in or change the active thread.
const WORKSPACE_OVERLAY_ROUTES = new Set([
"Connections",
"ConnectionsNew",
"GitBranches",
"GitCommit",
"GitConfirm",
"GitOverview",
"NewTaskSheet",
"SettingsSheet",
"ThreadReviewComment",
]);
/**
* Pathname of the topmost NON-overlay route — the screen the workspace is
* actually "on", regardless of any sheets floating above it.
*/
function workspacePathFromState(state: NavigationState): string {
const routes = state.routes.filter((route) => !WORKSPACE_OVERLAY_ROUTES.has(route.name));
const effectiveState =
routes.length > 0 && routes.length !== state.routes.length
? ({ ...state, routes, index: routes.length - 1 } as NavigationState)
: state;
const path = getPathFromState(effectiveState, navigationPathConfig);
return path.startsWith("/") ? path : `/${path}`;
}
function RootStackLayout(props: {
readonly children: React.ReactNode;
readonly state: NavigationState;
}) {
useAgentNotificationNavigation();
useThreadOutboxDrain();
// Full pathname (sheets included) for keyboard-command scoping; the
// workspace layout only reacts to the underlying non-overlay route.
const path = getPathFromState(props.state, navigationPathConfig);
const pathname = path.startsWith("/") ? path : `/${path}`;
const workspacePathname = workspacePathFromState(props.state);
return (
<HardwareKeyboardCommandProvider pathname={pathname}>
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</ClerkSettingsSheetDetentProvider>
</HardwareKeyboardCommandProvider>
);
}
function NotFoundScreen() {
const navigation = useNavigation();
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
const returnHomeButtonStyle = StyleSheet.flatten([
{
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
},
primaryBgStyle,
]);
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
gap: 16,
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={[{ flex: 1 }, screenBgStyle]}
>
<Text className="text-3xl font-t3-bold text-foreground" selectable>
Route not found
</Text>
<Pressable
style={returnHomeButtonStyle}
onPress={() => navigation.dispatch(StackActions.replace("Home"))}
>
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
</Pressable>
</ScrollView>
);
}
export const RootStack = createNativeStackNavigator({
initialRouteName: "Home",
layout: RootStackLayout,
screenOptions: {
headerShown: false,
},
screens: {
Home: createNativeStackScreen({
screen: HomeRouteScreen,
linking: "",
options: {
...GLASS_HEADER_OPTIONS,
contentStyle: { backgroundColor: "transparent" },
headerBackVisible: false,
title: "Threads",
},
}),
Thread: createNativeStackScreen({
screen: ThreadRouteScreen,
linking: THREAD_LINKING_PREFIX,
options: GLASS_HEADER_OPTIONS,
}),
ThreadTerminal: createNativeStackScreen({
screen: ThreadTerminalRouteScreen,
linking: `${THREAD_LINKING_PREFIX}/terminal`,
options: SOLID_HEADER_OPTIONS,
}),
ThreadReview: createNativeStackScreen({
screen: ReviewSheet,
linking: `${THREAD_LINKING_PREFIX}/review`,
options: SOLID_HEADER_OPTIONS,
}),
ThreadReviewComment: createNativeStackScreen({
screen: ReviewCommentComposerSheet,
linking: `${THREAD_LINKING_PREFIX}/review-comment`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
ThreadFiles: createNativeStackScreen({
screen: ThreadFilesTreeScreen,
linking: `${THREAD_LINKING_PREFIX}/files`,
options: {
...GLASS_HEADER_OPTIONS,
contentStyle:
SHEET_BACKGROUND_COLOR !== undefined
? { backgroundColor: SHEET_BACKGROUND_COLOR }
: undefined,
title: "Files",
},
}),
ThreadFile: createNativeStackScreen({
screen: ThreadFileScreen,
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
options: SOLID_HEADER_OPTIONS,
}),
GitOverview: createNativeStackScreen({
screen: GitOverviewSheet,
linking: `${THREAD_LINKING_PREFIX}/git`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitCommit: createNativeStackScreen({
screen: GitCommitSheet,
linking: `${THREAD_LINKING_PREFIX}/git/commit`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitBranches: createNativeStackScreen({
screen: GitBranchesSheet,
linking: `${THREAD_LINKING_PREFIX}/git/branches`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
},
}),
GitConfirm: createNativeStackScreen({
screen: GitConfirmSheet,
linking: `${THREAD_LINKING_PREFIX}/git-confirm`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.45, 0.7],
sheetGrabberVisible: true,
},
}),
SettingsSheet: createNativeStackScreen({
screen: SettingsSheetStack,
linking: "settings",
options: {
gestureEnabled: true,
headerShown: false,
presentation: "formSheet",
sheetAllowedDetents: [0.7, 0.92],
sheetGrabberVisible: true,
},
}),
Connections: createNativeStackScreen({
screen: ConnectionsRouteScreen,
linking: "connections",
options: {
title: "Environments",
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
},
}),
ConnectionsNew: createNativeStackScreen({
screen: ConnectionsNewRouteScreen,
linking: "connections/new",
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
},
}),
NewTaskSheet: createNativeStackScreen({
screen: NewTaskSheetStack,
linking: "new",
// The whole new-task flow (choose project → draft → add project) shares
// draft state via NewTaskFlowProvider. The expo-router era mounted it in
// app/new/_layout.tsx; this layout wrapper is the native-stack equivalent.
layout: ({ children }) => <NewTaskFlowProvider>{children}</NewTaskFlowProvider>,
options: {
gestureEnabled: true,
headerShown: false,
presentation: "formSheet",
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
},
}),
NotFound: createNativeStackScreen({
screen: NotFoundScreen,
linking: "*",
}),
},
});
type RootStackType = typeof RootStack;
const navigationPathConfig = {
screens: createPathConfigForStaticNavigation(RootStack) ?? {},
};
declare module "@react-navigation/native" {
interface RootNavigator extends RootStackType {}
}
-43
View File
@@ -1,43 +0,0 @@
import { Link } from "expo-router";
import { Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "../components/AppText";
export default function NotFoundRoute() {
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
gap: 16,
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={[{ flex: 1 }, screenBgStyle]}
>
<Text className="text-3xl font-t3-bold text-foreground" selectable>
Route not found
</Text>
<Link href="/" asChild>
<Pressable
style={[
{
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
},
primaryBgStyle,
]}
>
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
</Pressable>
</Link>
</ScrollView>
);
}
-149
View File
@@ -1,149 +0,0 @@
import "../../global.css";
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import { usePathname } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback } from "react";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
import { useWorkspaceState } from "../state/workspace";
import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry";
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
import {
ClerkSettingsSheetDetentProvider,
useClerkSettingsSheetDetent,
} from "../features/cloud/ClerkSettingsSheetDetent";
import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation";
import { useThemeColor } from "../lib/useThemeColor";
function AppNavigator() {
const pathname = usePathname();
const expandedSettingsRouteIsActive =
pathname === "/settings/archive" || pathname === "/settings/auth";
return (
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
<AppNavigatorContent />
</ClerkSettingsSheetDetentProvider>
);
}
function AppNavigatorContent() {
const { state } = useWorkspaceState();
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
useAgentNotificationNavigation();
useThreadOutboxDrain();
const handleSettingsTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
}
},
[collapse],
);
const newTaskScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
};
const connectionSheetScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
};
const settingsSheetScreenOptions = {
...connectionSheetScreenOptions,
sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
};
if (state.isLoadingConnections) {
return <LoadingScreen message="Loading remote workspace…" />;
}
return (
<>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={String(statusBarBg)}
translucent
/>
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen
name="settings"
listeners={{ transitionEnd: handleSettingsTransitionEnd }}
options={settingsSheetScreenOptions}
/>
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
<Stack.Screen name="new" options={newTaskScreenOptions} />
<Stack.Screen
name="threads/[environmentId]/[threadId]"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: "transparent" },
gestureEnabled: true,
headerShown: false,
}}
/>
</Stack>
</>
);
}
export default function RootLayout() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
{fontsLoaded ? (
<AppNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</CloudAuthProvider>
</RegistryContext.Provider>
);
}
@@ -1,29 +0,0 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function ConnectionsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const connSheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
return (
<Stack
screenOptions={{
contentStyle,
headerStyle: { backgroundColor: connSheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
headerShadowVisible: false,
headerBackButtonDisplayMode: "minimal",
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="new" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
-120
View File
@@ -1,120 +0,0 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import { useProjects, useThreadShells } from "../state/entities";
import { useWorkspaceState } from "../state/workspace";
import { buildThreadRoutePath } from "../lib/routes";
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import { HomeHeader } from "../features/home/HomeHeader";
import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
import { useThreadListActions } from "../features/home/useThreadListActions";
interface HomeListOptions {
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const [listOptions, setListOptions] = useState<HomeListOptions>({
selectedEnvironmentId: null,
projectSortOrder:
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
});
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const environments = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(
Order.String,
(environment: { readonly label: string }) => environment.label,
),
),
[savedConnectionsById],
);
const selectedEnvironmentId = environments.some(
(environment) => environment.environmentId === listOptions.selectedEnvironmentId,
)
? listOptions.selectedEnvironmentId
: null;
const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
}, []);
const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
setListOptions((current) => ({ ...current, projectSortOrder }));
}, []);
const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
setListOptions((current) => ({ ...current, threadSortOrder }));
}, []);
const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
setListOptions((current) => ({ ...current, projectGroupingMode }));
}, []);
return (
<>
<HomeHeader
environments={environments}
selectedEnvironmentId={selectedEnvironmentId}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
projectGroupingMode={listOptions.projectGroupingMode}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenSettings={() => router.push("/settings")}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => router.push("/new")}
onThreadSortOrderChange={setThreadSortOrder}
/>
<HomeScreen
catalogState={catalogState}
onAddConnection={() => router.push("/connections/new")}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onOpenEnvironments={() => router.push("/settings/environments")}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
</>
);
}
-50
View File
@@ -1,50 +0,0 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function NewTaskLayout() {
const sheetStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
return (
<NewTaskFlowProvider>
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerLargeTitle: false,
headerShadowVisible: false,
headerStyle: { backgroundColor: sheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
}}
>
<Stack.Screen name="index" options={{ animation: "none", title: "Choose project" }} />
<Stack.Screen
name="add-project/index"
options={{ animation: "slide_from_right", title: "New project" }}
/>
<Stack.Screen
name="add-project/repository"
options={{ animation: "slide_from_right", title: "Repository" }}
/>
<Stack.Screen
name="add-project/destination"
options={{ animation: "slide_from_right", title: "Clone destination" }}
/>
<Stack.Screen
name="add-project/local"
options={{ animation: "slide_from_right", title: "Local folder" }}
/>
<Stack.Screen name="draft" options={{ animation: "slide_from_right", title: "New task" }} />
</Stack>
</NewTaskFlowProvider>
);
}
@@ -1,5 +0,0 @@
import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectDestinationRoute() {
return <AddProjectDestinationScreen />;
}
@@ -1,5 +0,0 @@
import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRoute() {
return <AddProjectSourceScreen />;
}
@@ -1,5 +0,0 @@
import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectLocalRoute() {
return <AddProjectLocalFolderScreen />;
}
@@ -1,23 +0,0 @@
import { Stack, useLocalSearchParams } from "expo-router";
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects";
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRepositoryRoute() {
const params = useLocalSearchParams<{ source?: string | string[] }>();
const source = Array.isArray(params.source) ? params.source[0] : params.source;
const title =
source === "github" ||
source === "gitlab" ||
source === "bitbucket" ||
source === "azure-devops"
? addProjectRemoteSourceLabel(source)
: "Git URL";
return (
<>
<Stack.Screen options={{ title }} />
<AddProjectRepositoryScreen />
</>
);
}
-29
View File
@@ -1,29 +0,0 @@
import { Stack, useLocalSearchParams } from "expo-router";
import { NewTaskDraftScreen } from "../../features/threads/NewTaskDraftScreen";
export default function NewTaskDraftRoute() {
const params = useLocalSearchParams<{
environmentId?: string | string[];
projectId?: string | string[];
title?: string | string[];
}>();
return (
<>
<Stack.Screen
options={{
title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
}}
/>
<NewTaskDraftScreen
initialProjectRef={{
environmentId: Array.isArray(params.environmentId)
? params.environmentId[0]
: params.environmentId,
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
}}
/>
</>
);
}
-62
View File
@@ -1,62 +0,0 @@
import Stack from "expo-router/stack";
import { useCallback } from "react";
import { useResolveClassNames } from "uniwind";
import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function SettingsLayout() {
const { collapse } = useClerkSettingsSheetDetent();
const contentStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
const handleExpandedRouteTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
}
},
[collapse],
);
return (
<Stack
screenOptions={{
contentStyle,
headerBackButtonDisplayMode: "minimal",
headerShadowVisible: false,
headerStyle: { backgroundColor: sheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
}}
>
<Stack.Screen name="index" options={{ animation: "none", title: "Settings" }} />
<Stack.Screen
name="environments"
options={{ animation: "slide_from_right", title: "Environments" }}
/>
<Stack.Screen
name="environment-new"
options={{ animation: "slide_from_right", title: "Add Environment" }}
/>
<Stack.Screen
name="waitlist"
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
/>
<Stack.Screen
name="archive"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Archived Threads" }}
/>
<Stack.Screen
name="auth"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Sign in" }}
/>
</Stack>
);
}
-3
View File
@@ -1,3 +0,0 @@
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
export default ArchivedThreadsRouteScreen;
-33
View File
@@ -1,33 +0,0 @@
import { useAuth } from "@clerk/expo";
import { AuthView, UserProfileView } from "@clerk/expo/native";
import { Redirect, Stack } from "expo-router";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
export default function SettingsAuthRouteScreen() {
return hasCloudPublicConfig() ? (
<ConfiguredSettingsAuthRouteScreen />
) : (
<Redirect href="/settings" />
);
}
function ConfiguredSettingsAuthRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
return (
<>
<Stack.Screen options={{ title: isSignedIn ? "Account" : "Sign in" }} />
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} />
) : (
<AuthView isDismissible={false} />
)
) : null}
</View>
</>
);
}
@@ -1 +0,0 @@
export { default } from "../connections/new";
@@ -1,107 +0,0 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export default function ThreadLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
headerTitle: "",
}}
/>
<Stack.Screen
name="git"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.85],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="git-confirm"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.4],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="review"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files changed",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/index"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/[...path]"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "File",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review-comment"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.72, 0.92],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="terminal"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: "#050505" },
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerShadowVisible: false,
}}
/>
</Stack>
);
}
@@ -1,5 +0,0 @@
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFileRoute() {
return <ThreadFileScreen />;
}
@@ -1,5 +0,0 @@
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFilesIndexRoute() {
return <ThreadFilesTreeScreen />;
}
@@ -1,5 +0,0 @@
import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
export default function GitConfirmRoute() {
return <GitConfirmSheet />;
}
@@ -1,58 +0,0 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export const unstable_settings = {
anchor: "index",
};
export default function GitSheetLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerShown: false,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen
name="commit"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Commit changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="branches"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Branches & worktrees",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Review changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
</Stack>
);
}
@@ -1,5 +0,0 @@
import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
export default function GitBranchesRoute() {
return <GitBranchesSheet />;
}
@@ -1,5 +0,0 @@
import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
export default function GitCommitRoute() {
return <GitCommitSheet />;
}
@@ -1,5 +0,0 @@
import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
export default function GitRoute() {
return <GitOverviewSheet />;
}
@@ -1,18 +0,0 @@
import { Redirect, useLocalSearchParams } from "expo-router";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
export default function ReviewRoute() {
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
return (
<Redirect
href={{
pathname: "/threads/[environmentId]/[threadId]/review",
params: { environmentId, threadId },
}}
/>
);
}
@@ -1,5 +0,0 @@
import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
export default function ThreadRoute() {
return <ThreadRouteScreen />;
}
@@ -1,5 +0,0 @@
import { ReviewCommentComposerSheet } from "../../../../features/review/ReviewCommentComposerSheet";
export default function ReviewCommentRoute() {
return <ReviewCommentComposerSheet />;
}
@@ -1,10 +0,0 @@
import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
export default function ReviewRoute() {
return (
<ReviewHighlighterProvider>
<ReviewSheet />
</ReviewHighlighterProvider>
);
}
@@ -1,5 +0,0 @@
import { ThreadTerminalRouteScreen } from "../../../../features/terminal/ThreadTerminalRouteScreen";
export default function ThreadTerminalRoute() {
return <ThreadTerminalRouteScreen />;
}
+2 -3
View File
@@ -1,4 +1,3 @@
import type { Ref } from "react";
import {
Text as RNText,
TextInput as RNTextInput,
@@ -21,7 +20,7 @@ export function AppText({ className, ...props }: AppTextProps) {
export type AppTextInputProps = RNTextInputProps & {
readonly className?: string;
readonly ref?: Ref<RNTextInput>;
readonly ref?: React.Ref<RNTextInput>;
};
/**
@@ -40,7 +39,7 @@ export function AppTextInput({
<RNTextInput
ref={ref}
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
"min-h-13.5 rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
className,
)}
placeholderTextColor={placeholderTextColor ?? placeholderColor}
+1 -1
View File
@@ -75,7 +75,7 @@ export function ControlPill(props: {
}
export function ControlPillMenu(
props: Omit<ComponentProps<typeof MenuView>, "children" | "style" | "themeVariant"> & {
props: Omit<ComponentProps<typeof MenuView>, "children" | "themeVariant"> & {
readonly children: ReactNode;
},
) {
+23 -1
View File
@@ -7,11 +7,33 @@ export function EmptyState(props: {
readonly detail: string;
readonly actionLabel?: string;
readonly onAction?: () => void;
readonly variant?: "card" | "plain";
}) {
if (props.variant === "plain") {
return (
<View className="items-center px-8 py-8">
<Text className="text-center text-xl font-t3-bold text-foreground">{props.title}</Text>
<Text className="mt-2 text-center font-sans text-base leading-normal text-foreground-muted">
{props.detail}
</Text>
{props.actionLabel && props.onAction ? (
<Pressable
className="mt-5 rounded-full bg-primary px-5 py-3 active:opacity-70"
onPress={props.onAction}
>
<Text className="text-sm font-t3-bold text-primary-foreground">
{props.actionLabel}
</Text>
</Pressable>
) : null}
</View>
);
}
return (
<View className="rounded-[22px] border border-border bg-card p-5">
<Text className="font-t3-bold text-lg text-foreground">{props.title}</Text>
<Text className="mt-2 font-sans text-sm leading-[21px] text-foreground-muted">
<Text className="mt-2 font-sans text-sm leading-relaxed text-foreground-muted">
{props.detail}
</Text>
{props.actionLabel && props.onAction ? (
+1 -1
View File
@@ -4,7 +4,7 @@ import { AppText as Text } from "./AppText";
export function ErrorBanner(props: { readonly message: string }) {
return (
<View className="rounded-2xl border border-rose-300/70 bg-rose-100/80 px-3.5 py-3 dark:border-rose-400/28 dark:bg-rose-500/12">
<Text className="font-t3-medium text-sm leading-[18px] text-rose-700 dark:text-rose-300">
<Text className="font-t3-medium text-sm text-rose-700 dark:text-rose-300">
{props.message}
</Text>
</View>
+6 -1
View File
@@ -1,4 +1,6 @@
import { Connection } from "@t3tools/client-runtime/connection";
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
@@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
type ConnectionLayerSource =
| typeof Connection.layer
| typeof snapshotLoaderLayer
| typeof runtimeContextLayer
| typeof connectionPlatformLayer;
const connectionLayer = Connection.layer.pipe(
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
);
+11 -8
View File
@@ -16,8 +16,8 @@ import {
} from "@t3tools/client-runtime/connection";
import {
EnvironmentId,
OrchestrationThread,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -32,7 +32,10 @@ import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
// v2 stores the snapshot sequence alongside the thread so a warm cache can
// resume via `afterSequence` instead of re-downloading the full thread body.
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const StoredShellSnapshot = Schema.Struct({
@@ -45,7 +48,7 @@ const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
thread: OrchestrationThread,
snapshot: OrchestrationThreadDetailSnapshot,
});
const LegacyStoredShellSnapshot = Schema.Struct({
@@ -355,18 +358,18 @@ export const connectionStorageLayer = Layer.effectContext(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
? Option.some(stored.snapshot)
: Option.none();
}),
saveThread: (environmentId, thread) =>
saveThread: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const file = yield* threadSnapshotFile(environmentId, snapshot.thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
threadId: snapshot.thread.id,
snapshot,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
yield* Effect.try({
@@ -1,12 +1,12 @@
import { useEffect, useRef } from "react";
import * as Notifications from "expo-notifications";
import { useRouter } from "expo-router";
import { useLinkTo } from "@react-navigation/native";
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
export function useAgentNotificationNavigation(): void {
const router = useRouter();
const linkTo = useLinkTo();
const handledResponseIds = useRef(new Set<string>());
useEffect(() => {
@@ -14,7 +14,7 @@ export function useAgentNotificationNavigation(): void {
routeAgentNotificationResponseOnce({
handledResponseIds: handledResponseIds.current,
response,
navigate: (deepLink) => router.push(deepLink as never),
navigate: linkTo,
});
};
@@ -28,5 +28,5 @@ export function useAgentNotificationNavigation(): void {
return () => {
subscription.remove();
};
}, [router]);
}, [linkTo]);
}
@@ -2,11 +2,20 @@ import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
import type { Preferences } from "../../lib/storage";
// Development builds are Xcode-signed and receive sandbox APNs tokens;
// preview and production builds are distribution-signed and use production
// APNs. The relay routes each device's pushes accordingly.
export function resolveApsEnvironment(appVariant: unknown): "sandbox" | "production" {
return appVariant === "development" ? "sandbox" : "production";
}
export function makeRelayDeviceRegistrationRequest(input: {
readonly deviceId: string;
readonly label: string;
readonly iosMajorVersion: number;
readonly appVersion?: string;
readonly bundleId?: string;
readonly apsEnvironment?: "sandbox" | "production";
readonly pushToken?: string;
readonly pushToStartToken?: string;
readonly notificationsEnabled: boolean;
@@ -19,6 +28,8 @@ export function makeRelayDeviceRegistrationRequest(input: {
platform: "ios",
iosMajorVersion: input.iosMajorVersion,
appVersion: input.appVersion,
...(input.bundleId ? { bundleId: input.bundleId } : {}),
...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}),
...(input.pushToken ? { pushToken: input.pushToken } : {}),
...(input.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
preferences: {
@@ -16,15 +16,23 @@ import { verifyDpopProof } from "@t3tools/shared/dpop";
import type { SavedRemoteConnection } from "../../lib/connection";
import { cryptoLayer } from "../cloud/dpop";
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
clearAgentAwarenessRegistrationRecord,
loadAgentAwarenessRegistrationRecord,
loadOrCreateAgentAwarenessDeviceId,
saveAgentAwarenessRegistrationRecord,
} from "../../lib/storage";
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
import {
AgentAwarenessOperationError,
__resetAgentAwarenessRemoteRegistrationForTest,
getAgentAwarenessRegistrationStatus,
refreshActiveLiveActivityRemoteRegistration,
refreshAgentAwarenessRegistration,
normalizeAgentAwarenessRelayBaseUrl,
registerAgentAwarenessConnection,
registerLiveActivityPushToken,
releaseAgentAwarenessRelayTokenProvider,
setAgentAwarenessRelayTokenProvider,
shouldRegisterAgentAwarenessDeviceForProvider,
unregisterAgentAwarenessConnection,
@@ -41,6 +49,16 @@ const backgroundRuntime = vi.hoisted(() => ({
readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
}>,
}));
const appStateMock = vi.hoisted(() => ({
listeners: [] as Array<(state: string) => void>,
}));
const registrationRecordStore = vi.hoisted(() => ({
current: null as {
readonly identity: string;
readonly signature: string;
readonly pushToStartToken?: string;
} | null,
}));
vi.mock("expo-constants", () => ({
default: {
@@ -100,6 +118,19 @@ vi.mock("react-native", () => ({
OS: "ios",
Version: "18.0",
},
AppState: {
addEventListener: (_event: string, listener: (state: string) => void) => {
appStateMock.listeners.push(listener);
return {
remove: () => {
const index = appStateMock.listeners.indexOf(listener);
if (index >= 0) {
appStateMock.listeners.splice(index, 1);
}
},
};
},
},
}));
vi.mock("../../lib/runtime", () => ({
@@ -114,7 +145,18 @@ vi.mock("../../lib/runtime", () => ({
vi.mock("../../lib/storage", () => ({
loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadPreferences: vi.fn(() => Promise.resolve({})),
loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),
loadAgentAwarenessRegistrationRecord: vi.fn(() =>
Promise.resolve(registrationRecordStore.current),
),
saveAgentAwarenessRegistrationRecord: vi.fn((record: { identity: string; signature: string }) => {
registrationRecordStore.current = record;
return Promise.resolve();
}),
clearAgentAwarenessRegistrationRecord: vi.fn(() => {
registrationRecordStore.current = null;
return Promise.resolve();
}),
}));
function proofIat(proof: string): number {
@@ -176,6 +218,12 @@ describe("makeRelayDeviceRegistrationRequest", () => {
backgroundRuntime.pending.length = 0;
Constants.expoConfig!.extra = {};
__resetAgentAwarenessRemoteRegistrationForTest();
appStateMock.listeners.length = 0;
registrationRecordStore.current = null;
vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();
vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
widgetMocks.getInstances.mockReset();
widgetMocks.getInstances.mockReturnValue([]);
});
@@ -213,6 +261,31 @@ describe("makeRelayDeviceRegistrationRequest", () => {
});
});
it("registers the app's APNs routing so the relay targets the right bundle", () => {
expect(
makeRelayDeviceRegistrationRequest({
deviceId: "device-1",
label: "Julius's iPhone",
iosMajorVersion: 18,
appVersion: "1.0.0",
bundleId: "com.t3tools.t3code.preview",
apsEnvironment: resolveApsEnvironment("preview"),
notificationsEnabled: true,
preferences: {},
}),
).toMatchObject({
bundleId: "com.t3tools.t3code.preview",
apsEnvironment: "production",
});
});
it("routes development builds to the APNs sandbox", () => {
expect(resolveApsEnvironment("development")).toBe("sandbox");
expect(resolveApsEnvironment("preview")).toBe("production");
expect(resolveApsEnvironment("production")).toBe("production");
expect(resolveApsEnvironment(undefined)).toBe("production");
});
it("marks notification delivery disabled when APNs permission is unavailable", () => {
expect(
makeRelayDeviceRegistrationRequest({
@@ -329,6 +402,53 @@ describe("makeRelayDeviceRegistrationRequest", () => {
},
);
it.effect(
"re-registers active Live Activity tokens when the app returns to the foreground",
() => {
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* runBackgroundOperations();
activity.getPushToken.mockClear();
expect(appStateMock.listeners).toHaveLength(1);
for (const listener of appStateMock.listeners) {
listener("background");
}
yield* runBackgroundOperations();
expect(activity.getPushToken).not.toHaveBeenCalled();
for (const listener of appStateMock.listeners) {
listener("active");
}
yield* runBackgroundOperations();
expect(activity.getPushToken).toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
},
);
it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {
const end = vi.fn(() => Promise.resolve());
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
end,
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
expect(appStateMock.listeners).toHaveLength(1);
setAgentAwarenessRelayTokenProvider(null);
expect(end).toHaveBeenCalledWith("immediate");
expect(appStateMock.listeners).toHaveLength(0);
});
it.effect("refreshes APNs registration for connected environments after settings changes", () => {
registerAgentAwarenessConnection(savedConnection());
return Effect.gen(function* () {
@@ -395,6 +515,174 @@ describe("makeRelayDeviceRegistrationRequest", () => {
nowEpochSeconds: proofIat(dpop),
}),
).toMatchObject({ ok: true });
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("marks registration failed when device registration cannot complete", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
new Error("registration failed"),
);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
// Drive the registration directly so the assertion does not depend on the
// background queue draining; refreshAgentAwarenessRegistration swallows the
// error but must record the failed status so the settings toggles cannot
// read as enabled.
yield* refreshAgentAwarenessRegistration();
expect(getAgentAwarenessRegistrationStatus()).toBe("failed");
}).pipe(Effect.provide(relayTestLayer));
});
it("clears registration status on cloud sign-out", () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
setAgentAwarenessRelayTokenProvider(null);
expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
expect(clearAgentAwarenessRegistrationRecord).toHaveBeenCalled();
});
it("releases the provider without ending activities or clearing the registration", () => {
const end = vi.fn(() => Promise.resolve());
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
end,
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
registrationRecordStore.current = { identity: "", signature: "sig" };
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
expect(appStateMock.listeners).toHaveLength(1);
releaseAgentAwarenessRelayTokenProvider();
expect(appStateMock.listeners).toHaveLength(0);
expect(end).not.toHaveBeenCalled();
expect(clearAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
expect(registrationRecordStore.current).not.toBeNull();
});
it.effect("resets a pending status to unknown when relay config is missing", () => {
// No relay url configured: registration can neither run nor ever succeed,
// so the status must not stick at "pending".
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("keeps a registered status when a later refresh fails", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
// The relay still holds the accepted registration; a transient refresh
// failure must not flip the settings toggles off.
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
new Error("transient failure"),
);
yield* refreshAgentAwarenessRegistration();
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("does not re-register the same account when nothing has changed", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* refreshAgentAwarenessRegistration();
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
expect(registrationRecordStore.current).not.toBeNull();
// Second attempt with an identical payload must skip the relay entirely,
// so no new registration record is written.
vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
yield* refreshAgentAwarenessRegistration();
expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("dedupes rapid activity-token re-registrations within the replay window", () => {
// Fetch counts are unreliable here (the module-level relay layer captures
// the first test's fetch), so assert on the flow's own seams: a real
// registration attempt loads the device id, a deduped one short-circuits
// before it.
const fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
return Promise.resolve(
Response.json(
url.endsWith("/v1/client/dpop-token")
? {
access_token: "relay-dpop-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 300,
scope: "mobile:registration",
}
: { ok: true },
),
);
});
vi.stubGlobal("fetch", fetchMock);
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
// Drains the sign-in refresh, which registers the activity token.
yield* runBackgroundOperations();
expect(activity.getPushToken).toHaveBeenCalled();
// A burst refresh (foreground / connection update seconds later) must
// dedupe: it reads the token but never proceeds to a registration
// attempt (which would load the device id first).
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockClear();
yield* refreshActiveLiveActivityRemoteRegistration();
expect(loadOrCreateAgentAwarenessDeviceId).not.toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("re-registers when the stored account identity differs", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
registrationRecordStore.current = { identity: "someone-else", signature: "stale" };
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* refreshAgentAwarenessRegistration();
expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
});
@@ -1,12 +1,13 @@
import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
import { type LiveActivity } from "expo-widgets";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Platform } from "react-native";
import { AppState, Platform } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import {
type RelayDeviceRegistrationRequest,
type RelayAgentActivitySnapshotResponse,
type RelayLiveActivityRegistrationRequest,
} from "@t3tools/contracts/relay";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
@@ -20,13 +21,16 @@ import {
import type { SavedRemoteConnection } from "../../lib/connection";
import { runtime } from "../../lib/runtime";
import {
clearAgentAwarenessRegistrationRecord,
loadAgentAwarenessDeviceId,
loadAgentAwarenessRegistrationRecord,
loadOrCreateAgentAwarenessDeviceId,
loadPreferences,
saveAgentAwarenessRegistrationRecord,
} from "../../lib/storage";
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
@@ -42,6 +46,8 @@ const AgentAwarenessOperation = Schema.Literals([
"read-live-activity-push-token",
"load-live-activity-registration-identifier",
"list-active-live-activities",
"load-live-activity-prime-preferences",
"prime-live-activity",
]);
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
@@ -58,8 +64,49 @@ export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentA
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
let pushToStartSubscription: { remove: () => void } | null = null;
// Activity tokens the relay recently accepted, by acceptance time. The refresh
// runs on sign-in, every app foreground, and every environment-connection
// update, which arrive in bursts and spammed identical registrations. But the
// registration is not a pure no-op: the relay replays the current aggregate to
// this device on every accepted registration, and that replay is the
// foreground reconciliation that repairs drifted or orphaned activities. So
// dedupe only within a short window — bursts collapse to one request, while a
// foreground after real time away still triggers a replay. Cleared on
// sign-out/identity change alongside the device registration state.
const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
const registeredActivityPushTokens = new Map<string, number>();
let pushTokenSubscription: { remove: () => void } | null = null;
let appStateSubscription: { remove: () => void } | null = null;
// Whether the relay has actually accepted this device's registration. The
// notification/Live Activity settings toggles must reflect this rather than
// only local iOS permission or saved preferences: if the registration request
// never succeeded, the device cannot receive anything, so the switches must
// not read as enabled.
export type AgentAwarenessRegistrationStatus = "unknown" | "pending" | "registered" | "failed";
let registrationStatus: AgentAwarenessRegistrationStatus = "unknown";
const registrationStatusListeners = new Set<() => void>();
function setRegistrationStatus(next: AgentAwarenessRegistrationStatus): void {
if (registrationStatus === next) {
return;
}
registrationStatus = next;
for (const listener of registrationStatusListeners) {
listener();
}
}
export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistrationStatus {
return registrationStatus;
}
export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void {
registrationStatusListeners.add(listener);
return () => {
registrationStatusListeners.delete(listener);
};
}
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
let relayTokenProvider: (() => Promise<string | null>) | null = null;
let relayTokenProviderIdentity: string | null = null;
@@ -74,7 +121,6 @@ let pendingDeviceRegistration: {
} | null = null;
interface DeviceRegistrationInput {
readonly pushToStartToken?: string;
readonly observedPushToken?: string;
}
@@ -120,32 +166,66 @@ export function setAgentAwarenessRelayTokenProvider(
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
registeredActivityPushTokens.clear();
}
relayTokenProvider = provider;
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
if (!provider) {
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
appStateSubscription?.remove();
appStateSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
// Without a signed-in user the relay can no longer update or end these
// activities, so they would sit orphaned on the lock screen.
endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
setRegistrationStatus("unknown");
// Sign-out is the only thing that invalidates a stored registration, so the
// next sign-in re-registers.
void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
logRegistrationError("clear registration record on sign-out failed", error);
});
return;
}
ensurePushToStartListener();
ensurePushTokenListener();
ensureAppStateListener();
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity registration after cloud sign-in failed",
);
if (isExistingIdentity) {
// Same account re-activating (e.g. Clerk token refresh) normally needs no
// re-registration — but if the previous attempt never succeeded, this is
// the only trigger that will retry it before the next cold start.
if (registrationStatus !== "registered") {
enqueueDeviceRegistration({}, "device registration retry after cloud session refresh failed");
}
return;
}
enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
}
// Detach the provider and native listeners without the destructive sign-out
// cleanup. For provider teardown while the user is still signed in (e.g. the
// auth bridge unmounting/remounting), ending lock-screen activities and wiping
// the persisted registration would be wrong — the relay still holds a valid
// registration and the next mount reuses it.
export function releaseAgentAwarenessRelayTokenProvider(): void {
relayTokenProvider = null;
relayTokenProviderIdentity = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
appStateSubscription?.remove();
appStateSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
}
function iosMajorVersion(): number {
const version = Platform.Version;
if (typeof version === "number") {
@@ -211,6 +291,27 @@ const relayToken = (
});
});
// Stable fingerprint of everything the relay stores for this device. When it
// matches the last accepted registration for the same account, re-registering
// is a no-op, so a launch that changed nothing skips the request entirely.
function registrationSignature(body: RelayDeviceRegistrationRequest): string {
return [
body.deviceId,
body.pushToken ?? "",
body.bundleId ?? "",
body.apsEnvironment ?? "",
body.appVersion ?? "",
body.label,
body.iosMajorVersion,
body.preferences.notificationsEnabled,
body.preferences.liveActivitiesEnabled,
body.preferences.notifyOnApproval,
body.preferences.notifyOnInput,
body.preferences.notifyOnCompletion,
body.preferences.notifyOnFailure,
].join("|");
}
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
expectedGeneration: number,
@@ -223,7 +324,13 @@ function registerDeviceWithRelay(
});
return;
}
if (!readRelayConfig()) return;
const relayConfig = readRelayConfig();
if (!relayConfig) {
// Nothing is in flight and nothing can succeed until configuration
// appears; "pending" would otherwise stick forever.
setRegistrationStatus("unknown");
return;
}
const token = yield* relayToken("read-device-registration-relay-token");
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled after auth lookup", {
@@ -234,6 +341,37 @@ function registerDeviceWithRelay(
}
if (!token) {
logRegistrationDebug("relay device registration skipped; user is not signed in");
setRegistrationStatus("unknown");
return;
}
// Skip the request when this account already registered an identical
// payload; the relay upsert would be a no-op. The record is only cleared on
// sign-out, so a device stays registered across launches without re-hitting
// the relay every time the app opens.
const identity = relayTokenProviderIdentity ?? "";
const persisted = yield* Effect.tryPromise({
try: () => loadAgentAwarenessRegistrationRecord(),
catch: (cause) => cause,
}).pipe(Effect.orElseSucceed(() => null));
if (expectedGeneration !== deviceRegistrationGeneration) {
// Signed out while the record loaded — do not resurrect the cleared
// record or report the previous account's registration as current.
logRegistrationDebug("device registration cancelled after record lookup", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
const payload = body;
// The relay URL participates so pointing the app at a different relay
// invalidates the record and re-registers there.
const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
if (persisted && persisted.identity === identity && persisted.signature === signature) {
setRegistrationStatus("registered");
logRegistrationDebug("relay device registration skipped; already registered for account", {
expectedGeneration,
});
return;
}
@@ -243,8 +381,27 @@ function registerDeviceWithRelay(
});
yield* client.registerDevice({
clerkToken: token,
payload: body,
payload,
});
if (expectedGeneration !== deviceRegistrationGeneration) {
// Signed out while the request was in flight: the sign-out path already
// reset the status and cleared the record for the next account, so a
// stale success must not overwrite either.
logRegistrationDebug("device registration completed after sign-out; result discarded", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
setRegistrationStatus("registered");
yield* Effect.promise(() =>
saveAgentAwarenessRegistrationRecord({
identity,
signature,
}).catch((error: unknown) => {
logRegistrationError("persist registration record failed", error);
}),
);
logRegistrationDebug("relay device registration request completed", {
expectedGeneration,
});
@@ -278,6 +435,91 @@ function unregisterDeviceWithRelay(input: {
});
}
// Arms the lock-screen card the moment the user starts agent work from this
// phone, while the app is still foregrounded and the fresh activity's token
// can be registered immediately. The seeded row is a best-effort placeholder;
// the relay's registration replay repaints it with the authoritative
// aggregate within seconds. No-ops when a card is already armed.
export function armAgentAwarenessLiveActivityForLocalWork(input: {
readonly threadTitle: string;
readonly projectTitle: string;
}): void {
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
return;
}
void loadPreferences()
.catch(() => null)
.then((preferences) => {
if (preferences?.liveActivitiesEnabled === false) {
return;
}
armAgentAwarenessLiveActivityForLocalWorkNow(input);
});
}
function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
readonly threadTitle: string;
readonly projectTitle: string;
}): void {
try {
if (AgentActivity.getInstances().length > 0) {
return;
}
const nowIso = new Date(Date.now()).toISOString();
const activity = AgentActivity.start({
title: "T3 Code",
subtitle: "Agent work in progress",
activeCount: 1,
updatedAt: nowIso,
activities: [
{
environmentId: "",
threadId: "",
projectTitle: input.projectTitle,
threadTitle: input.threadTitle,
modelTitle: "",
phase: "starting",
status: "Connecting",
updatedAt: nowIso,
deepLink: "/",
},
],
});
logRegistrationDebug("live activity card armed for local work", {
threadTitle: input.threadTitle,
});
runRegistrationInBackground(
registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid),
"live activity arming after local task start failed",
);
} catch (error) {
logRegistrationError("live activity arming failed", error);
}
}
function readAgentActivitySnapshot(): Effect.Effect<
RelayAgentActivitySnapshotResponse | null,
never,
ManagedRelay.ManagedRelayClient
> {
return Effect.gen(function* () {
if (!readRelayConfig()) return null;
const token = yield* relayToken("read-live-activity-registration-relay-token");
if (!token) {
return null;
}
const client = yield* ManagedRelay.ManagedRelayClient;
return yield* client.getAgentActivitySnapshot({ clerkToken: token });
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
logRegistrationError("agent activity snapshot read failed", error);
return null;
}),
),
);
}
function registerLiveActivityWithRelay(
body: RelayLiveActivityRegistrationRequest,
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
@@ -332,14 +574,8 @@ function mergeDeviceRegistrationInput(
current: DeviceRegistrationInput,
next: DeviceRegistrationInput,
): DeviceRegistrationInput {
return {
...((next.pushToStartToken ?? current.pushToStartToken)
? { pushToStartToken: next.pushToStartToken ?? current.pushToStartToken }
: {}),
...((next.observedPushToken ?? current.observedPushToken)
? { observedPushToken: next.observedPushToken ?? current.observedPushToken }
: {}),
};
const observedPushToken = next.observedPushToken ?? current.observedPushToken;
return observedPushToken ? { observedPushToken } : {};
}
function registrationAddsInformation(
@@ -347,8 +583,7 @@ function registrationAddsInformation(
next: DeviceRegistrationInput,
): boolean {
return (
(next.pushToStartToken !== undefined && next.pushToStartToken !== current.pushToStartToken) ||
(next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken)
next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken
);
}
@@ -363,8 +598,10 @@ function startPendingDeviceRegistration(): void {
logRegistrationDebug("device registration started", {
generation,
hasObservedPushToken: next.input.observedPushToken !== undefined,
hasPushToStartToken: next.input.pushToStartToken !== undefined,
});
if (registrationStatus !== "registered") {
setRegistrationStatus("pending");
}
const registration = {
input: next.input,
operation: Promise.resolve(),
@@ -375,6 +612,13 @@ function startPendingDeviceRegistration(): void {
runtime.runPromiseExit(registerDevice(next.input, generation)),
);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
// A transient failure on a later refresh (e.g. token rotation) leaves
// the prior accepted registration intact on the relay, so an already
// registered device stays "registered" rather than flipping the
// settings toggles off.
if (registrationStatus !== "registered") {
setRegistrationStatus("failed");
}
logRegistrationError(next.context, squashAtomCommandFailure(result));
}
logRegistrationDebug("device registration finished", { generation });
@@ -444,14 +688,16 @@ function registerDevice(
expectedGeneration,
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
});
const bundleId = Constants.expoConfig?.ios?.bundleIdentifier?.trim();
yield* registerDeviceWithRelay(
makeRelayDeviceRegistrationRequest({
deviceId,
label: Constants.deviceName?.trim() || "iOS device",
iosMajorVersion: iosMajorVersion(),
appVersion: Constants.expoConfig?.version,
...(bundleId ? { bundleId } : {}),
apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant),
...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
...(input?.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
preferences,
}),
@@ -460,27 +706,12 @@ function registerDevice(
});
}
function registerDeviceForCurrentUser(
pushToStartToken?: string,
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return registerDevice(pushToStartToken ? { pushToStartToken } : undefined);
}
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
enqueueDeviceRegistration({ pushToStartToken }, "push-to-start token registration failed");
}
function ensurePushToStartListener(): void {
if (pushToStartSubscription || !canRegisterRemoteLiveActivities()) {
return;
}
pushToStartSubscription = addPushToStartTokenListener((event) => {
const token = event.activityPushToStartToken;
if (token) {
registerPushToStartTokenForCurrentUser(token);
}
});
function registerDeviceForCurrentUser(): Effect.Effect<
void,
unknown,
ManagedRelay.ManagedRelayClient
> {
return registerDevice(undefined);
}
function ensurePushTokenListener(): void {
@@ -498,14 +729,51 @@ function ensurePushTokenListener(): void {
});
}
// Re-registering activity tokens on foreground makes the relay replay the
// current aggregate to this device, which updates content that drifted while
// pushes could not be delivered and ends orphaned activities whose end push
// never arrived. (Deduped by ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS: rapid
// foreground/sign-in bursts collapse to one registration, but returning after
// real time away still replays.)
function ensureAppStateListener(): void {
if (appStateSubscription || !canRegisterRemoteLiveActivities()) {
return;
}
appStateSubscription = AppState.addEventListener("change", (state) => {
if (state !== "active") {
return;
}
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity reconciliation after app foreground failed",
);
});
}
function endLocalLiveActivities(context: string): void {
if (!canRegisterRemoteLiveActivities()) {
return;
}
try {
for (const activity of AgentActivity.getInstances()) {
activity.end("immediate").catch((error: unknown) => {
logRegistrationError(context, error);
});
}
} catch (error) {
logRegistrationError(context, error);
}
}
export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void {
if (!canRegisterRemoteLiveActivities()) {
return;
}
environmentConnections.set(connection.environmentId, connection);
ensurePushToStartListener();
ensurePushTokenListener();
ensureAppStateListener();
enqueueDeviceRegistration({}, "device registration failed");
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
@@ -523,10 +791,10 @@ export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId)
export function unregisterAllAgentAwarenessConnections(): void {
environmentConnections.clear();
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
appStateSubscription?.remove();
appStateSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
@@ -541,6 +809,11 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
return registerDeviceForCurrentUser().pipe(
Effect.catch((error) =>
Effect.sync(() => {
// Same rationale as the queued path: a failed refresh does not undo an
// already accepted registration.
if (registrationStatus !== "registered") {
setRegistrationStatus("failed");
}
logRegistrationError("device registration refresh failed", error);
}),
),
@@ -549,10 +822,10 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
environmentConnections.clear();
pushToStartSubscription?.remove();
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
appStateSubscription?.remove();
appStateSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
@@ -562,6 +835,9 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
registrationStatus = "unknown";
registrationStatusListeners.clear();
registeredActivityPushTokens.clear();
}
export function unregisterAgentAwarenessDeviceForCurrentUser(
@@ -649,6 +925,13 @@ function registerLiveActivityPushTokenValue(input: {
readonly activityPushToken: string;
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
if (
acceptedAt !== undefined &&
Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
) {
return true;
}
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
@@ -662,6 +945,7 @@ function registerLiveActivityPushTokenValue(input: {
activityPushToken: input.activityPushToken,
});
if (registered) {
registeredActivityPushTokens.set(input.activityPushToken, Date.now());
logRegistrationDebug("live activity push token registered", {
tokenSuffix: input.activityPushToken.slice(-8),
});
@@ -694,7 +978,7 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
return;
}
const activities = yield* Effect.try({
let activities = yield* Effect.try({
try: () => AgentActivity.getInstances(),
catch: (cause) =>
new AgentAwarenessOperationError({
@@ -710,6 +994,79 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
),
);
// The relay tracks exactly one card per device; if concurrent arming ever
// produced extras, end them so only one keeps receiving updates.
if (activities.length > 1) {
for (const extra of activities.slice(1)) {
extra.end("immediate").catch((error: unknown) => {
logRegistrationError("duplicate live activity cleanup failed", error);
});
}
activities = activities.slice(0, 1);
}
// Activities are only ever created here, in the foreground, where the
// update token can be observed and registered immediately — the relay
// never remote-starts one (background push-to-start wakes proved too
// unreliable to hand the token over). Arming is conditional: the relay is
// asked what the card would show first, so an idle open never creates an
// empty lock-screen card, and an armed card is born with the real
// aggregate instead of a placeholder.
if (activities.length === 0) {
const preferences = yield* Effect.tryPromise({
try: () => loadPreferences(),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-live-activity-prime-preferences",
cause,
}),
}).pipe(Effect.orElseSucceed(() => null));
// The toggle defaults to on: an unset preference (fresh install) must
// prime, so only an explicit false blocks it.
if (preferences?.liveActivitiesEnabled !== false) {
const snapshot = yield* readAgentActivitySnapshot();
// The snapshot request yields; an arm-on-send may have created the
// card in the meantime. Re-check so two cards are never started.
const armedMeanwhile = yield* Effect.try({
try: () => AgentActivity.getInstances(),
catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
}).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
if (armedMeanwhile.length > 0) {
activities = [...armedMeanwhile];
} else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
const aggregate = snapshot.aggregate;
const primed = yield* Effect.try({
try: () =>
AgentActivity.start({
title: aggregate.title,
subtitle: aggregate.subtitle,
activeCount: aggregate.activeCount,
updatedAt: aggregate.updatedAt,
activities: aggregate.activities,
}),
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "prime-live-activity",
cause,
}),
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
logRegistrationError("live activity priming failed", error);
return null;
}),
),
);
if (primed) {
logRegistrationDebug("live activity card primed", {
activeCount: aggregate.activeCount,
});
activities = [primed];
}
}
}
}
const registrationResults = yield* Effect.forEach(activities, (activity) =>
registerLiveActivityPushToken({ activity }).pipe(
Effect.map((registered) => !registered),
@@ -1,7 +1,7 @@
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useFocusEffect } from "expo-router";
import { useFocusEffect } from "@react-navigation/native";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -2,23 +2,22 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { LegendList } from "@legendapp/list/react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import * as Haptics from "expo-haptics";
import { Stack } from "expo-router";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "expo-symbols";
import { useCallback, useRef } from "react";
import { useCallback, useMemo, useRef, type ComponentProps } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
RefreshControl,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
@@ -26,11 +25,8 @@ import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "../home/thread-swipe-actions";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
export interface ArchivedThreadsHeaderEnvironment {
@@ -52,84 +48,185 @@ const THREAD_ACTIONS: MenuAction[] = [
},
];
type ArchivedThreadListItem =
| {
readonly kind: "project";
readonly key: string;
readonly environmentLabel: string | null;
readonly project: EnvironmentProject;
}
| {
readonly kind: "thread";
readonly key: string;
readonly environmentLabel: string | null;
readonly isFirst: boolean;
readonly isLast: boolean;
readonly thread: EnvironmentThreadShell;
};
function ArchivedThreadsHeader(props: {
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly sortOrder: ArchivedThreadSortOrder;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onRefresh: () => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
}) {
const { width } = useWindowDimensions();
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
const usesNativeChrome = Platform.OS === "ios";
const usesCompactMailToolbar = Platform.OS === "ios" && width < 700;
const archiveFilterMenu = {
title: "Archived thread options",
items: [
{
type: "submenu" as const,
title: "Environment",
items: [
{
type: "action" as const,
title: "All environments",
state: props.selectedEnvironmentId === null ? ("on" as const) : ("off" as const),
onPress: () => props.onEnvironmentChange(null),
},
...props.environments.map((environment) => ({
type: "action" as const,
title: environment.label,
state:
props.selectedEnvironmentId === environment.environmentId
? ("on" as const)
: ("off" as const),
onPress: () => props.onEnvironmentChange(environment.environmentId),
})),
],
},
{
type: "submenu" as const,
title: "Sort by archived date",
items: [
{
type: "action" as const,
title: "Newest first",
state: props.sortOrder === "newest" ? ("on" as const) : ("off" as const),
onPress: () => props.onSortOrderChange("newest"),
},
{
type: "action" as const,
title: "Oldest first",
state: props.sortOrder === "oldest" ? ("on" as const) : ("off" as const),
onPress: () => props.onSortOrderChange("oldest"),
},
],
},
],
};
return (
<>
<Stack.Screen
{/* Static header config (glass preset + title) lives in Stack.tsx; only
dynamic toolbar/search wiring is set here. */}
<NativeStackScreenOptions
options={{
title: "Archived Threads",
headerSearchBarOptions: {
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
placeholder: "Search archived threads",
placement: "stacked",
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
},
unstable_headerToolbarItems: usesCompactMailToolbar
? () => [
createNativeMailSearchToolbarItem({
composeButtonId: "archived-refresh",
composeSystemImageName: "arrow.clockwise",
filterMenu: archiveFilterMenu,
filterButtonId: "archived-filter",
filterSystemImageName: hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease",
onComposePress: props.onRefresh,
onSearchTextChange: props.onSearchQueryChange,
placeholder: "Search",
searchTextChangeId: "archived-search-text",
}),
]
: undefined,
headerSearchBarOptions: usesCompactMailToolbar
? undefined
: {
...(usesNativeChrome
? {
allowToolbarIntegration: true,
placement: "integratedButton" as const,
}
: {
placement: "stacked" as const,
}),
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
placeholder: "Search archived threads",
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
accessibilityLabel="Filter and sort archived threads"
icon={
hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Archived thread options"
>
<Stack.Toolbar.Menu title="Environment">
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
>
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
{props.environments.map((environment) => (
<Stack.Toolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
{usesCompactMailToolbar ? null : (
<NativeHeaderToolbar placement="right">
{usesNativeChrome ? (
<NativeHeaderToolbar.Button
accessibilityLabel="Refresh archived threads"
icon="arrow.clockwise"
onPress={props.onRefresh}
separateBackground
/>
) : null}
<NativeHeaderToolbar.Menu
accessibilityLabel="Filter and sort archived threads"
icon={
hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Archived thread options"
>
<NativeHeaderToolbar.Menu title="Environment">
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
>
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
{props.environments.map((environment) => (
<NativeHeaderToolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
<Stack.Toolbar.Menu title="Sort by archived date">
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "newest"}
onPress={() => props.onSortOrderChange("newest")}
>
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "oldest"}
onPress={() => props.onSortOrderChange("oldest")}
>
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
<NativeHeaderToolbar.Menu title="Sort by archived date">
<NativeHeaderToolbar.Label>Sort by archived date</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.sortOrder === "newest"}
onPress={() => props.onSortOrderChange("newest")}
>
<NativeHeaderToolbar.Label>Newest first</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
isOn={props.sortOrder === "oldest"}
onPress={() => props.onSortOrderChange("oldest")}
>
<NativeHeaderToolbar.Label>Oldest first</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar>
)}
</>
);
}
@@ -164,30 +261,25 @@ function ProjectGroupLabel(props: {
function ArchivedThreadRow(props: {
readonly environmentLabel: string | null;
readonly isFirst: boolean;
readonly isLast: boolean;
readonly onDelete: () => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
readonly onUnarchive: () => void;
readonly thread: EnvironmentThreadShell;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const cardColor = useThemeColor("--color-card");
const iconColor = useThemeColor("--color-icon-subtle");
const separatorColor = useThemeColor("--color-separator");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
Boolean(part),
);
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
}
fullSwipeArmedRef.current = armed;
}, []);
const handleMenuAction = useCallback(
(event: { nativeEvent: { event: string } }) => {
if (event.nativeEvent.event === "unarchive") {
@@ -200,114 +292,84 @@ function ArchivedThreadRow(props: {
);
return (
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
childrenContainerStyle={{ backgroundColor: cardColor }}
containerStyle={{ backgroundColor: cardColor }}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
if (swipeableRef.current) {
props.onSwipeableClose(swipeableRef.current);
}
<ThreadSwipeable
backgroundColor={cardColor}
fullSwipeWidth={windowWidth - 32}
onDelete={props.onDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
onSwipeableOpenStartDrag={() => {
if (swipeableRef.current) {
props.onSwipeableWillOpen(swipeableRef.current);
}
}}
onSwipeableWillOpen={() => {
const methods = swipeableRef.current;
if (!methods) return;
props.onSwipeableWillOpen(methods);
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
props.onDelete();
}
}}
overshootFriction={1}
overshootRight
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={cardColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={props.thread.title}
>
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
{() => (
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
borderTopLeftRadius: props.isFirst ? 20 : 0,
borderTopRightRadius: props.isFirst ? 20 : 0,
borderBottomLeftRadius: props.isLast ? 20 : 0,
borderBottomRightRadius: props.isLast ? 20 : 0,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconColor}
type="monochrome"
/>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
className="min-w-0 flex-1 text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"], minWidth: 30, textAlign: "right" }}
>
{timestamp}
</Text>
</View>
) : null}
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconColor}
type="monochrome"
/>
<Text
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
</Text>
</View>
) : null}
</View>
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Actions for ${props.thread.title}`}
accessibilityRole="button"
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
hitSlop={6}
>
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
</Pressable>
</ControlPillMenu>
</View>
</ReanimatedSwipeable>
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Actions for ${props.thread.title}`}
accessibilityRole="button"
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
hitSlop={6}
>
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
</Pressable>
</ControlPillMenu>
</View>
)}
</ThreadSwipeable>
);
}
@@ -317,7 +379,7 @@ function ArchiveError(props: { readonly message: string; readonly onRetry: () =>
<Text className="text-base font-t3-bold text-danger-foreground">
Could not load every archive
</Text>
<Text className="mt-1 text-sm leading-[18px] text-foreground-muted">{props.message}</Text>
<Text className="mt-1 text-sm text-foreground-muted">{props.message}</Text>
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
<Text className="text-sm font-t3-bold text-danger-foreground">Try again</Text>
</Pressable>
@@ -340,8 +402,41 @@ export function ArchivedThreadsScreen(props: {
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
}) {
const { onDeleteThread, onUnarchiveThread } = props;
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const archiveScrollGesture = useMemo(() => Gesture.Native(), []);
const refreshTint = useThemeColor("--color-icon");
const environmentLabelsById = useMemo(
() =>
new Map(
props.environments.map((environment) => [environment.environmentId, environment.label]),
),
[props.environments],
);
const listItems = useMemo<ReadonlyArray<ArchivedThreadListItem>>(() => {
const items: ArchivedThreadListItem[] = [];
for (const group of props.groups) {
const environmentLabel = environmentLabelsById.get(group.project.environmentId) ?? null;
items.push({
kind: "project",
key: `${group.key}:project`,
environmentLabel,
project: group.project,
});
group.threads.forEach((thread, index) => {
items.push({
kind: "thread",
key: `${thread.environmentId}:${thread.id}`,
environmentLabel,
isFirst: index === 0,
isLast: index === group.threads.length - 1,
thread,
});
});
}
return items;
}, [environmentLabelsById, props.groups]);
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
openSwipeableRef.current.close();
@@ -355,82 +450,103 @@ export function ArchivedThreadsScreen(props: {
}, []);
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
const renderListItem = useCallback(
({ item }: { item: ArchivedThreadListItem }) => {
if (item.kind === "project") {
return (
<View className="pt-4">
<ProjectGroupLabel environmentLabel={item.environmentLabel} project={item.project} />
</View>
);
}
return (
<ArchivedThreadRow
environmentLabel={item.environmentLabel}
isFirst={item.isFirst}
isLast={item.isLast}
onDelete={() => onDeleteThread(item.thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => onUnarchiveThread(item.thread)}
simultaneousSwipeGesture={archiveScrollGesture}
thread={item.thread}
/>
);
},
[
archiveScrollGesture,
handleSwipeableClose,
handleSwipeableWillOpen,
onDeleteThread,
onUnarchiveThread,
],
);
const listEmptyComponent = useMemo(() => {
if (isInitialLoad) {
return (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-sm text-foreground-muted">Loading archive...</Text>
</View>
);
}
return (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
);
}, [isFiltered, isInitialLoad, refreshTint]);
return (
<View className="flex-1 bg-sheet">
<ArchivedThreadsHeader
environments={props.environments}
onEnvironmentChange={props.onEnvironmentChange}
onRefresh={props.onRefresh}
onSearchQueryChange={props.onSearchQueryChange}
onSortOrderChange={props.onSortOrderChange}
selectedEnvironmentId={props.selectedEnvironmentId}
sortOrder={props.sortOrder}
/>
<ScrollView
className="flex-1"
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
onRefresh={props.onRefresh}
refreshing={props.isLoading && !isInitialLoad}
tintColor={String(refreshTint)}
/>
}
showsVerticalScrollIndicator={false}
>
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
{isInitialLoad ? (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
</View>
) : props.groups.length === 0 ? (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
) : (
props.groups.map((group) => {
const environmentLabel =
props.environments.find(
(environment) => environment.environmentId === group.project.environmentId,
)?.label ?? null;
return (
<View key={group.key} collapsable={false}>
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{group.threads.map((thread, index) => (
<ArchivedThreadRow
key={`${thread.environmentId}:${thread.id}`}
environmentLabel={environmentLabel}
isLast={index === group.threads.length - 1}
onDelete={() => props.onDeleteThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => props.onUnarchiveThread(thread)}
thread={thread}
/>
))}
</View>
</View>
);
})
)}
</ScrollView>
<GestureDetector gesture={archiveScrollGesture}>
<LegendList
className="flex-1"
contentContainerStyle={{
paddingBottom: 32,
paddingHorizontal: 16,
paddingTop: 4,
}}
contentInsetAdjustmentBehavior="automatic"
data={listItems}
estimatedItemSize={62}
getItemType={(item) => item.kind}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
keyExtractor={(item) => item.key}
ListEmptyComponent={listEmptyComponent}
ListHeaderComponent={
props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null
}
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
onRefresh={props.onRefresh}
refreshing={props.isLoading && !isInitialLoad}
tintColor={String(refreshTint)}
/>
}
renderItem={renderListItem}
showsVerticalScrollIndicator={false}
/>
</GestureDetector>
</View>
);
}
@@ -14,6 +14,7 @@ import { runtime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import { useAtomCommand } from "../../state/use-atom-command";
import {
releaseAgentAwarenessRelayTokenProvider,
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
@@ -143,7 +144,11 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
useEffect(
() => () => {
previousTokenProviderRef.current = null;
deactivateCloudRelayAccount();
// Unmounting is not a sign-out: the user is usually still signed in, so
// detach the provider without ending lock-screen activities or wiping the
// persisted registration (a remount reuses both).
releaseAgentAwarenessRelayTokenProvider();
setManagedRelaySession(appAtomRegistry, null);
},
[],
);
@@ -2,7 +2,6 @@ import { useWaitlist } from "@clerk/expo";
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { useState } from "react";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
@@ -36,8 +35,10 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
if (waitlist.id) {
return (
<View style={styles.content}>
<Text style={[styles.title, { color: colors.foreground }]}>You are on the waitlist</Text>
<Text style={[styles.body, styles.confirmationBody, { color: colors.secondaryForeground }]}>
<Text className="text-center font-t3-bold text-xl text-foreground">
You are on the waitlist
</Text>
<Text className="text-center font-sans text-base text-foreground-secondary">
We will email you when your T3 Cloud access is ready.
</Text>
<SignInAction onPress={props.onSignIn} />
@@ -47,17 +48,18 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
return (
<View style={styles.content}>
<Text style={[styles.body, { color: colors.secondaryForeground }]}>
<Text className="font-sans text-base text-foreground-secondary">
Enter your email and we will let you know when access is ready.
</Text>
<View style={styles.field}>
<Text style={[styles.label, { color: colors.secondaryForeground }]}>Email address</Text>
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
<TextInput
accessibilityLabel="Email address"
autoCapitalize="none"
autoComplete="email"
autoCorrect={false}
className="font-sans text-lg text-foreground"
keyboardType="email-address"
onChangeText={(value) => {
setEmailAddress(value);
@@ -73,7 +75,6 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
backgroundColor: colors.input,
borderColor:
fieldError || requestError ? colors.dangerForeground : colors.inputBorder,
color: colors.foreground,
},
]}
textContentType="emailAddress"
@@ -82,7 +83,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
{fieldError || requestError ? (
<Text
accessibilityLiveRegion="polite"
style={[styles.error, { color: colors.dangerForeground }]}
className="font-sans text-sm text-danger-foreground"
selectable
>
{fieldError ?? requestError}
@@ -107,7 +108,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
]}
>
{isSubmitting ? <ActivityIndicator color={colors.primaryForeground} size="small" /> : null}
<Text style={[styles.buttonText, { color: colors.primaryForeground }]}>
<Text className="font-t3-bold text-base text-primary-foreground">
{isSubmitting ? "Joining" : "Join the waitlist"}
</Text>
</Pressable>
@@ -118,12 +119,11 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}
function SignInAction(props: { readonly onPress: () => void }) {
const colors = useCloudWaitlistColors();
return (
<View style={styles.signInRow}>
<Text style={[styles.body, { color: colors.secondaryForeground }]}>Already have access?</Text>
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
<Text style={[styles.signInText, { color: colors.foreground }]}>Sign in</Text>
<Text className="font-t3-bold text-base text-foreground">Sign in</Text>
</Pressable>
</View>
);
@@ -132,35 +132,18 @@ function SignInAction(props: { readonly onPress: () => void }) {
function useCloudWaitlistColors() {
return {
dangerForeground: String(useThemeColor("--color-danger-foreground")),
foreground: String(useThemeColor("--color-foreground")),
input: String(useThemeColor("--color-input")),
inputBorder: String(useThemeColor("--color-input-border")),
placeholder: String(useThemeColor("--color-placeholder")),
primary: String(useThemeColor("--color-primary")),
primaryForeground: String(useThemeColor("--color-primary-foreground")),
secondaryForeground: String(useThemeColor("--color-foreground-secondary")),
};
}
const styles = StyleSheet.create({
body: {
fontFamily: "DMSans_400Regular",
...MOBILE_TYPOGRAPHY.body,
},
buttonText: {
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.body.fontSize,
},
content: {
gap: 18,
},
confirmationBody: {
textAlign: "center",
},
error: {
fontFamily: "DMSans_400Regular",
...MOBILE_TYPOGRAPHY.footnote,
},
field: {
gap: 8,
},
@@ -168,16 +151,10 @@ const styles = StyleSheet.create({
borderCurve: "continuous",
borderRadius: 16,
borderWidth: 1,
fontFamily: "DMSans_400Regular",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
minHeight: 54,
paddingHorizontal: 16,
paddingVertical: 14,
},
label: {
fontFamily: "DMSans_700Bold",
...MOBILE_TYPOGRAPHY.footnote,
},
primaryButton: {
alignItems: "center",
borderRadius: 999,
@@ -195,13 +172,4 @@ const styles = StyleSheet.create({
justifyContent: "center",
paddingTop: 4,
},
signInText: {
fontFamily: "DMSans_700Bold",
...MOBILE_TYPOGRAPHY.body,
},
title: {
fontFamily: "DMSans_700Bold",
...MOBILE_TYPOGRAPHY.title,
textAlign: "center",
},
});
+41 -9
View File
@@ -8,12 +8,7 @@ import * as Schema from "effect/Schema";
import * as ExpoCrypto from "expo-crypto";
import * as SecureStore from "expo-secure-store";
import { p256 } from "@noble/curves/nist";
import {
computeDpopAccessTokenHash,
computeDpopJwkThumbprint,
DpopPublicJwk,
normalizeDpopHtu,
} from "@t3tools/shared/dpop";
import { DpopPublicJwk, normalizeDpopHtu } from "@t3tools/shared/dpopCommon";
import * as Layer from "effect/Layer";
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
@@ -107,6 +102,40 @@ function sha256Digest(
);
}
function base64UrlSha256(
data: Uint8Array,
message: string,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return sha256Digest(data, message).pipe(Effect.map(Encoding.encodeBase64Url));
}
function dpopThumbprintInput(jwk: DpopPublicJwk): string {
return JSON.stringify({
crv: jwk.crv,
kty: jwk.kty,
x: jwk.x,
y: jwk.y,
});
}
function computeDpopJwkThumbprintEffect(
jwk: DpopPublicJwk,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return base64UrlSha256(
new TextEncoder().encode(dpopThumbprintInput(jwk)),
"Could not hash the DPoP public key thumbprint.",
);
}
function computeDpopAccessTokenHashEffect(
accessToken: string,
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
return base64UrlSha256(
new TextEncoder().encode(accessToken),
"Could not hash the DPoP access token.",
);
}
function secureRandomBytes(
byteCount: number,
message: string,
@@ -153,7 +182,7 @@ export function generateDpopProofKeyPair(): Effect.Effect<
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
catch: cloudDpopError("Generated DPoP public key is invalid."),
});
const thumbprint = computeDpopJwkThumbprint(publicJwk);
const thumbprint = yield* computeDpopJwkThumbprintEffect(publicJwk);
return {
privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk),
publicJwk,
@@ -189,9 +218,10 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
},
catch: cloudDpopError("Stored DPoP proof key is invalid."),
});
const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk);
return {
...restored,
thumbprint: computeDpopJwkThumbprint(restored.publicJwk),
thumbprint,
};
}
const generated = yield* generateDpopProofKeyPair();
@@ -243,7 +273,9 @@ export function createDpopProof(input: {
Effect.map(Encoding.encodeBase64Url),
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
);
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
const ath = input.accessToken
? yield* computeDpopAccessTokenHashEffect(input.accessToken)
: null;
const payload = yield* encodeDpopJwtPayloadJson({
htm: input.method.toUpperCase(),
htu,
@@ -76,16 +76,16 @@ export function ConnectionEnvironmentRow(props: {
/>
<View className="flex-1 gap-0.5">
<Text className="text-base font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
<Text className="text-base font-t3-bold leading-snug text-foreground" numberOfLines={1}>
{props.environment.environmentLabel}
</Text>
<Text className="text-xs leading-[16px] text-foreground-muted" numberOfLines={1}>
<Text className="text-xs text-foreground-muted" numberOfLines={1}>
{props.environment.displayUrl}
</Text>
{statusLabel ? (
<Text
className={cn(
"text-xs leading-[16px]",
"text-xs",
hasConnectionFailure ? "text-rose-500 dark:text-rose-400" : "text-foreground-muted",
)}
numberOfLines={props.expanded ? undefined : 1}
@@ -134,7 +134,7 @@ export function ConnectionEnvironmentRow(props: {
className="gap-3 px-4 pb-4"
>
{props.environment.isRelayManaged ? (
<Text className="text-sm leading-[18px] text-foreground-muted">
<Text className="text-sm text-foreground-muted">
Managed by T3 Cloud. Tunnel details update automatically.
</Text>
) : (
@@ -1,5 +1,6 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useState } from "react";
import { Alert, ScrollView, View } from "react-native";
@@ -8,21 +9,26 @@ 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 { ConnectionSheetButton } from "./ConnectionSheetButton";
import { extractPairingUrlFromQrPayload } from "./pairing";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pairing";
import { buildPairingUrl, parsePairingUrl } from "./pairing";
export default function ConnectionsNewRouteScreen() {
type ConnectionsNewRouteParams = {
readonly mode?: string;
};
export function ConnectionsNewRouteScreen({
route,
}: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
const {
connectionPairingUrl,
onChangeConnectionPairingUrl,
onConnectPress,
pairingConnectionError,
} = useRemoteConnections();
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
const navigation = useNavigation();
const params = route.params ?? {};
const insets = useSafeAreaInsets();
const [hostInput, setHostInput] = useState("");
const [codeInput, setCodeInput] = useState("");
@@ -31,6 +37,7 @@ export default function ConnectionsNewRouteScreen() {
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const headerIconColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
@@ -116,21 +123,25 @@ export default function ConnectionsNewRouteScreen() {
onChangeConnectionPairingUrl(pairingUrl);
const result = await onConnectPress(pairingUrl);
if (AsyncResult.isSuccess(result)) {
dismissRoute(router);
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.dispatch(StackActions.replace("Home"));
}
} else {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, navigation]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
<NativeStackScreenOptions
options={{
title: showScanner ? "Scan QR Code" : "Add Environment",
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button
icon={showScanner ? "xmark" : "qrcode.viewfinder"}
onPress={() => {
if (showScanner) {
@@ -140,8 +151,9 @@ export default function ConnectionsNewRouteScreen() {
}
}}
separateBackground
tintColor={headerIconColor}
/>
</Stack.Toolbar>
</NativeHeaderToolbar>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
@@ -171,7 +183,7 @@ export default function ConnectionsNewRouteScreen() {
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
<Text className="text-center text-sm leading-normal text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
<ConnectionSheetButton
@@ -1,4 +1,5 @@
import { Stack, useRouter } from "expo-router";
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useNavigation } from "@react-navigation/native";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
@@ -9,16 +10,16 @@ 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";
import { ConnectionEnvironmentRow } from "./ConnectionEnvironmentRow";
export default function ConnectionsRouteScreen() {
export function ConnectionsRouteScreen() {
const {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onUpdateEnvironment,
} = useRemoteConnections();
const router = useRouter();
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
@@ -31,18 +32,13 @@ export default function ConnectionsRouteScreen() {
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: "Environments",
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button
icon="plus"
onPress={() => router.push("/connections/new")}
onPress={() => navigation.navigate("ConnectionsNew")}
separateBackground
/>
</Stack.Toolbar>
</NativeHeaderToolbar>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
@@ -85,7 +81,7 @@ export default function ConnectionsRouteScreen() {
type="monochrome"
/>
</View>
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
<Text className="text-center text-sm leading-normal text-foreground-muted">
No environments connected yet.{"\n"}Tap{" "}
<Text className="font-t3-bold text-foreground">+</Text> to add one.
</Text>
@@ -73,10 +73,10 @@ export function EnvironmentConnectionNotice(props: {
/>
)}
<Text className="text-center text-lg font-t3-bold leading-[22px] text-foreground">
<Text className="text-center text-lg font-t3-bold text-foreground">
{noticeTitle(props.connection.phase, props.environmentLabel)}
</Text>
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
<Text className="text-center text-sm leading-normal text-foreground-muted">
{noticeDetail(props.connection.phase, props.resourceName, props.connection.error)}
{props.connection.traceId ? (
<>
@@ -33,11 +33,14 @@ describe("resolveNativeReviewDiffView", () => {
expect(expoMocks.requireNativeView).not.toHaveBeenCalled();
});
it("returns the native review diff view when the view config is installed", async () => {
it("returns the payload bridge when the native review diff view is installed", async () => {
setExpoViewConfigAvailable();
expoMocks.requireNativeView.mockReturnValue(nativeView);
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
expect(resolveNativeReviewDiffView()).toBe(nativeView);
const resolvedView = resolveNativeReviewDiffView();
expect(resolvedView).not.toBeNull();
expect(resolvedView).not.toBe(nativeView);
expect(resolveNativeReviewDiffView()).toBe(resolvedView);
expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3ReviewDiffSurface");
});
@@ -78,3 +81,20 @@ describe("resolveNativeReviewDiffView", () => {
expect(consoleError).toHaveBeenCalledTimes(1);
});
});
describe("isPendingNativeViewRegistration", () => {
it("recognizes registration races for the installed native view name", async () => {
const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");
expect(
isPendingNativeViewRegistration(
new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),
),
).toBe(true);
expect(
isPendingNativeViewRegistration(
new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
),
).toBe(false);
});
});
@@ -1,10 +1,18 @@
import type { ComponentType } from "react";
import {
createElement,
useEffect,
useImperativeHandle,
useRef,
type ComponentType,
type Ref,
} from "react";
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { requireNativeView } from "expo";
import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
const NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES = 60;
interface ExpoGlobalWithViewConfig {
readonly expo?: {
@@ -103,6 +111,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly tokensJson?: string;
readonly tokensPatchJson?: string;
readonly tokensResetKey?: string;
readonly contentResetKey?: string;
readonly collapsedFileIdsJson?: string;
readonly viewedFileIdsJson?: string;
readonly selectedRowIdsJson?: string;
@@ -113,7 +122,13 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly rowHeight: number;
readonly contentWidth: number;
readonly initialRowIndex?: number;
readonly refreshing?: boolean;
readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
readonly onPullToRefresh?: (event: NativeSyntheticEvent<Record<string, never>>) => void;
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
readonly onVisibleFileChange?: (
event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
) => void;
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
readonly onPressLine?: (
@@ -129,18 +144,130 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
}
let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
export interface NativeReviewDiffViewHandle {
readonly scrollToFile: (fileId: string, animated?: boolean) => Promise<void>;
readonly scrollToTop: (animated?: boolean) => Promise<void>;
}
interface NativeReviewDiffViewRef {
readonly setRowsJson: (rowsJson: string) => Promise<void>;
readonly setTokensJson: (tokensJson: string) => Promise<void>;
readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<void>;
readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
readonly scrollToTop: (animated: boolean) => Promise<void>;
}
type NativeReviewDiffRawViewProps = Omit<
NativeReviewDiffViewProps,
"nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson"
> & {
readonly ref?: Ref<NativeReviewDiffViewRef>;
};
let cachedNativeReviewDiffRawView: ComponentType<NativeReviewDiffRawViewProps> | undefined;
let nativeReviewDiffViewResolutionFailed = false;
type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
export function isPendingNativeViewRegistration(error: unknown): boolean {
return (
error instanceof Error &&
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`)
);
}
function useNativeReviewDiffPayload(
nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
method: NativeReviewDiffPayloadMethod,
payload: string | undefined,
) {
useEffect(() => {
if (payload === undefined) {
return;
}
let cancelled = false;
let frame: number | null = null;
let attempts = 0;
const dispatch = () => {
if (cancelled) {
return;
}
const view = nativeRef.current;
const command = view?.[method];
if (!view || !command) {
if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
attempts += 1;
frame = requestAnimationFrame(dispatch);
}
return;
}
void command.call(view, payload).catch((error: unknown) => {
if (
!cancelled &&
attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
isPendingNativeViewRegistration(error)
) {
attempts += 1;
frame = requestAnimationFrame(dispatch);
return;
}
console.error(`[native-review-diff] ${method} failed`, error);
});
};
// Fabric attaches the React ref before Expo registers the native tag used by
// view functions. Starting on the next frame avoids racing that registration.
frame = requestAnimationFrame(dispatch);
return () => {
cancelled = true;
if (frame !== null) {
cancelAnimationFrame(frame);
}
};
}, [method, nativeRef, payload]);
}
function getExpoViewConfig(moduleName: string) {
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
moduleName,
);
}
function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
const { nativeViewRef, rowsJson, tokensJson, tokensPatchJson, ...nativeProps } = props;
const nativeRef = useRef<NativeReviewDiffViewRef>(null);
useNativeReviewDiffPayload(nativeRef, "setRowsJson", rowsJson);
useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
useNativeReviewDiffPayload(nativeRef, "setTokensPatchJson", tokensPatchJson);
useImperativeHandle(
nativeViewRef,
() => ({
scrollToFile: async (fileId, animated = true) => {
await nativeRef.current?.scrollToFile(fileId, animated);
},
scrollToTop: async (animated = true) => {
await nativeRef.current?.scrollToTop(animated);
},
}),
[],
);
const RawNativeView = cachedNativeReviewDiffRawView;
if (!RawNativeView) {
return null;
}
return createElement(RawNativeView, { ...nativeProps, ref: nativeRef });
}
export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
if (cachedNativeReviewDiffView) {
return cachedNativeReviewDiffView;
if (cachedNativeReviewDiffRawView) {
return NativeReviewDiffView;
}
if (nativeReviewDiffViewResolutionFailed) {
@@ -152,7 +279,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
}
try {
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
NATIVE_REVIEW_DIFF_MODULE_NAME,
);
} catch (cause) {
@@ -166,5 +293,5 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
return null;
}
return cachedNativeReviewDiffView ?? null;
return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;
}
@@ -1,15 +1,19 @@
import { useCallback, useMemo } from "react";
import { useCallback, useMemo, useState } from "react";
import {
Markdown,
type CustomRenderers,
type NodeStyleOverrides,
type PartialMarkdownTheme,
} from "react-native-nitro-markdown";
import { ScrollView, Text as NativeText, View } from "react-native";
import { RefreshControl, ScrollView, Text as NativeText, View } from "react-native";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import {
resolveMarkdownFontSizes,
resolveNativeMarkdownTypography,
} from "../../lib/appearancePreferences";
import { useThemeColor } from "../../lib/useThemeColor";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import {
hasNativeSelectableMarkdownText,
SelectableMarkdownText,
@@ -24,6 +28,15 @@ interface MarkdownPreviewStyles {
}
function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
const { appearance } = useAppearancePreferences();
const markdownFontSizes = useMemo(
() => resolveMarkdownFontSizes(appearance.baseFontSize),
[appearance.baseFontSize],
);
const nativeMarkdownTypography = useMemo(
() => resolveNativeMarkdownTypography(appearance.baseFontSize),
[appearance.baseFontSize],
);
const body = String(useThemeColor("--color-md-body"));
const strong = String(useThemeColor("--color-md-strong"));
const link = String(useThemeColor("--color-md-link"));
@@ -74,7 +87,8 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
text: {
color: body,
fontFamily: "DMSans_400Regular",
...MOBILE_TYPOGRAPHY.body,
fontSize: markdownFontSizes.m,
lineHeight: markdownFontSizes.bodyLineHeight,
},
heading: {
color: strong,
@@ -124,7 +138,9 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
skillTextColor: codeText,
quoteMarkerColor: blockquoteBorder,
dividerColor: horizontalRule,
...MOBILE_TYPOGRAPHY.body,
fontSize: nativeMarkdownTypography.fontSize,
lineHeight: nativeMarkdownTypography.lineHeight,
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
@@ -138,18 +154,46 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
codeText,
horizontalRule,
link,
markdownFontSizes,
nativeMarkdownTypography,
strong,
]);
}
export function FileMarkdownPreview(props: { readonly markdown: string }) {
export function FileMarkdownPreview(props: {
readonly markdown: string;
readonly onRefresh?: () => Promise<void> | void;
}) {
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullToRefresh = useCallback(async () => {
if (!props.onRefresh) {
return;
}
setIsPullRefreshing(true);
try {
await props.onRefresh();
} finally {
setIsPullRefreshing(false);
}
}, [props.onRefresh]);
const styles = useMarkdownPreviewStyles();
const onLinkPress = useCallback((href: string) => {
void tryOpenExternalUrl(href, "markdown-link");
}, []);
return (
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
<ScrollView
className="flex-1 bg-sheet"
contentContainerStyle={{ padding: 18 }}
refreshControl={
props.onRefresh ? (
<RefreshControl
refreshing={isPullRefreshing}
onRefresh={() => void handlePullToRefresh()}
/>
) : undefined
}
>
<View className="mx-auto w-full max-w-[760px]">
{hasNativeSelectableMarkdownText() ? (
<SelectableMarkdownText
@@ -1,7 +1,15 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
FlatList,
Platform,
Pressable,
RefreshControl,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
@@ -11,9 +19,25 @@ import {
buildFileTree,
defaultExpandedTreePaths,
flattenFileTree,
type FileTreeNode,
type VisibleFileTreeNode,
} from "./fileTree";
const fileTreeCache = new WeakMap<ReadonlyArray<ProjectEntry>, ReadonlyArray<FileTreeNode>>();
const FILE_TREE_INITIAL_RENDER_COUNT = 20;
const FILE_TREE_RENDER_BATCH_SIZE = 12;
const OPTIMISTIC_SELECTION_TIMEOUT_MS = 1_000;
function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
const cached = fileTreeCache.get(entries);
if (cached !== undefined) {
return cached;
}
const tree = buildFileTree(entries);
fileTreeCache.set(entries, tree);
return tree;
}
function ancestorPaths(path: string): ReadonlyArray<string> {
const parts = path.split("/").filter(Boolean);
const ancestors: string[] = [];
@@ -25,19 +49,24 @@ function ancestorPaths(path: string): ReadonlyArray<string> {
const FileTreeRow = memo(function FileTreeRow(props: {
readonly item: VisibleFileTreeNode;
readonly selectedPath: string | null;
readonly selected: boolean;
readonly expanded: boolean;
readonly iconColor: string;
readonly onPressDirectory: (path: string) => void;
readonly onPreviewFile?: (path: string) => void;
readonly onPressFile: (path: string) => void;
}) {
const { node, depth } = props.item;
const selected = node.kind === "file" && node.path === props.selectedPath;
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={node.path}
onPressIn={() => {
if (node.kind === "file") {
props.onPreviewFile?.(node.path);
}
}}
onPress={() => {
if (node.kind === "directory") {
props.onPressDirectory(node.path);
@@ -47,7 +76,7 @@ const FileTreeRow = memo(function FileTreeRow(props: {
}}
className={cn(
"mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
selected && "bg-subtle-strong",
props.selected && "bg-subtle-strong",
)}
style={{ paddingLeft: 8 + depth * 18 }}
>
@@ -64,8 +93,10 @@ const FileTreeRow = memo(function FileTreeRow(props: {
<PierreEntryIcon path={node.path} kind={node.kind} size={17} />
<Text
className={cn(
"min-w-0 flex-1 text-sm leading-[19px]",
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
"min-w-0 flex-1 text-sm leading-normal",
props.selected
? "font-t3-bold text-foreground"
: "font-t3-medium text-foreground-secondary",
)}
numberOfLines={1}
>
@@ -86,13 +117,30 @@ export function FileTreeBrowser(props: {
readonly isPending: boolean;
readonly searchQuery: string;
readonly selectedPath: string | null;
readonly onPreviewFile?: (path: string) => void;
readonly onRefresh: () => void;
readonly onSelectFile: (path: string) => void;
}) {
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
const [pendingSelection, setPendingSelection] = useState<{
readonly path: string;
readonly selectedPathAtPress: string | null;
} | null>(null);
const insets = useSafeAreaInsets();
// Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
// observed adjustedContentInset bottom (~102) seen in the native trace.
const headerInset = Platform.OS === "ios" ? insets.top + 44 : 0;
const iconColor = String(useThemeColor("--color-icon-muted"));
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
const controlledSelectedPathRef = useRef(controlledSelectedPath);
const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
controlledSelectedPathRef.current = controlledSelectedPath;
const tree = useMemo(() => buildFileTree(props.entries), [props.entries]);
const selectedPath =
pendingSelection?.selectedPathAtPress === controlledSelectedPath
? pendingSelection.path
: controlledSelectedPath;
const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]);
const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
const visibleNodes = useMemo(
() =>
@@ -114,17 +162,30 @@ export function FileTreeBrowser(props: {
}, [defaultExpanded]);
useEffect(() => {
if (!props.selectedPath) {
if (!controlledSelectedPath) {
return;
}
setExpandedPaths((current) => {
const ancestors = ancestorPaths(controlledSelectedPath);
if (ancestors.every((ancestor) => current.has(ancestor))) {
return current;
}
const next = new Set(current);
for (const ancestor of ancestorPaths(props.selectedPath ?? "")) {
for (const ancestor of ancestors) {
next.add(ancestor);
}
return next;
});
}, [props.selectedPath]);
}, [controlledSelectedPath]);
useEffect(
() => () => {
if (pendingSelectionTimeoutRef.current !== null) {
clearTimeout(pendingSelectionTimeoutRef.current);
}
},
[],
);
const toggleDirectory = useCallback((path: string) => {
setExpandedPaths((current) => {
@@ -137,53 +198,86 @@ export function FileTreeBrowser(props: {
return next;
});
}, []);
const handleSelectFile = useCallback(
(path: string) => {
if (pendingSelectionTimeoutRef.current !== null) {
clearTimeout(pendingSelectionTimeoutRef.current);
}
setPendingSelection({
path,
selectedPathAtPress: controlledSelectedPathRef.current,
});
pendingSelectionTimeoutRef.current = setTimeout(() => {
pendingSelectionTimeoutRef.current = null;
setPendingSelection((current) => (current?.path === path ? null : current));
}, OPTIMISTIC_SELECTION_TIMEOUT_MS);
onSelectFile(path);
},
[onSelectFile],
);
const renderItem = useCallback(
({ item }: { readonly item: VisibleFileTreeNode }) => (
<FileTreeRow
item={item}
selected={item.node.kind === "file" && item.node.path === selectedPath}
expanded={expandedPaths.has(item.node.path)}
iconColor={iconColor}
onPressDirectory={toggleDirectory}
onPreviewFile={onPreviewFile}
onPressFile={handleSelectFile}
/>
),
[expandedPaths, handleSelectFile, iconColor, onPreviewFile, selectedPath, toggleDirectory],
);
if (props.error && props.entries.length === 0) {
return (
<View className="flex-1 bg-sheet px-4 py-5">
<Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
<Text className="mt-1 text-xs leading-normal text-foreground-muted">{props.error}</Text>
</View>
);
}
// SPIKE: render the FlatList as the screen's DIRECT content (no wrapping View), and
// mirror the Home ScrollView exactly — `contentInsetAdjustmentBehavior: "automatic"`
// with NO manual contentInset. iOS only applies the nav-bar top inset + scroll-edge
// blur to a scroll view in the screen's primary position; a scroll view buried in
// flex-1 Views is ignored, which is why the tree rendered under the header with no blur.
return (
<View className="flex-1 bg-sheet">
{props.error && props.entries.length === 0 ? (
<FlatList
style={{ flex: 1 }}
data={visibleNodes}
keyExtractor={(item) => item.node.path}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
scrollIndicatorInsets={
Platform.OS === "ios" ? { top: headerInset, left: 0, right: 0, bottom: 0 } : undefined
}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT}
maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE}
updateCellsBatchingPeriod={16}
windowSize={5}
contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
refreshControl={<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />}
renderItem={renderItem}
ListEmptyComponent={
<View className="px-4 py-5">
<Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
<Text className="mt-1 text-xs leading-[18px] text-foreground-muted">{props.error}</Text>
</View>
) : (
<FlatList
data={visibleNodes}
keyExtractor={(item) => item.node.path}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
contentContainerStyle={{ paddingVertical: 8 }}
refreshControl={
<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
}
renderItem={({ item }) => (
<FileTreeRow
item={item}
selectedPath={props.selectedPath}
expanded={expandedPaths.has(item.node.path)}
iconColor={iconColor}
onPressDirectory={toggleDirectory}
onPressFile={props.onSelectFile}
/>
{props.isPending ? (
<ActivityIndicator size="small" />
) : (
<>
<Text className="text-sm font-t3-bold text-foreground">No files found</Text>
<Text className="mt-1 text-xs leading-normal text-foreground-muted">
{props.searchQuery.trim().length > 0
? "Try a different search."
: "The workspace file index is empty."}
</Text>
</>
)}
ListEmptyComponent={
<View className="px-4 py-5">
{props.isPending ? (
<ActivityIndicator size="small" />
) : (
<>
<Text className="text-sm font-t3-bold text-foreground">No files found</Text>
<Text className="mt-1 text-xs leading-[18px] text-foreground-muted">
{props.searchQuery.trim().length > 0
? "Try a different search."
: "The workspace file index is empty."}
</Text>
</>
)}
</View>
}
/>
)}
</View>
</View>
}
/>
);
}
@@ -1,8 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { ComponentType } from "react";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
FlatList,
ScrollView,
Text as NativeText,
useColorScheme,
useWindowDimensions,
View,
} from "react-native";
import { AppText as Text } from "../../components/AppText";
import { LoadingStrip } from "../../components/LoadingStrip";
@@ -11,71 +18,62 @@ import {
resolveNativeReviewDiffView,
} from "../diffs/nativeReviewDiffSurface";
import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
import {
REVIEW_DIFF_LINE_HEIGHT,
REVIEW_MONO_FONT_FAMILY,
renderVisibleWhitespace,
} from "../review/reviewDiffRendering";
import { REVIEW_MONO_FONT_FAMILY, renderVisibleWhitespace } from "../review/reviewDiffRendering";
import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
import { cn } from "../../lib/cn";
import { MOBILE_CODE_SURFACE } from "../../lib/typography";
import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
import {
buildNativeSourceRows,
buildNativeSourceTokens,
NATIVE_SOURCE_CONTENT_WIDTH,
NATIVE_SOURCE_ROW_HEIGHT,
NATIVE_SOURCE_STYLE,
nativeSourceRowId,
} from "./nativeSourceFileAdapter";
import { prepareSourceFileDocument } from "./source-file-document";
import { sourceHighlightAtom } from "./sourceHighlightingState";
const SOURCE_LINE_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
const SOURCE_LINE_NUMBER_WIDTH = MOBILE_CODE_SURFACE.gutterWidth;
const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
interface SourceFileSurfaceProps {
readonly contents: string;
readonly path: string;
readonly initialLine?: number | null;
/** Enables native pull-to-refresh on the source surface. */
readonly onRefresh?: () => Promise<void> | void;
}
type SourceHighlightStatus = "highlighting" | "ready" | "error";
function splitSourceLines(contents: string): ReadonlyArray<string> {
return contents.replace(/\r\n?/g, "\n").split("\n");
}
const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
readonly codeSurface: ResolvedMobileCodeSurface;
readonly index: number;
readonly line: string;
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
readonly highlighted: boolean;
readonly wordBreak: boolean;
}) {
return (
<View
className={cn("flex-row", props.highlighted && "bg-primary/10")}
style={{ minHeight: SOURCE_LINE_HEIGHT }}
style={{ minHeight: props.codeSurface.rowHeight }}
>
<NativeText
className="select-none pr-3 text-right text-foreground-tertiary"
style={{
width: SOURCE_LINE_NUMBER_WIDTH,
width: props.codeSurface.gutterWidth,
fontFamily: REVIEW_MONO_FONT_FAMILY,
fontSize: MOBILE_CODE_SURFACE.lineNumberFontSize,
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
fontSize: props.codeSurface.lineNumberFontSize,
lineHeight: props.codeSurface.rowHeight,
}}
>
{props.index + 1}
</NativeText>
<NativeText
selectable
numberOfLines={1}
className="font-normal text-foreground"
numberOfLines={props.wordBreak ? undefined : 1}
className="flex-1 font-normal text-foreground"
style={{
fontFamily: REVIEW_MONO_FONT_FAMILY,
fontSize: MOBILE_CODE_SURFACE.fontSize,
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
minWidth: 320,
fontSize: props.codeSurface.fontSize,
lineHeight: props.codeSurface.rowHeight,
minWidth: props.wordBreak ? undefined : 320,
}}
>
{props.tokens && props.tokens.length > 0
@@ -119,11 +117,8 @@ const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
function useSourceFileModel(props: SourceFileSurfaceProps) {
const colorScheme = useColorScheme();
const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light";
const normalizedContents = useMemo(
() => props.contents.replace(/\r\n?/g, "\n"),
[props.contents],
);
const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]);
const document = useMemo(() => prepareSourceFileDocument(props.contents), [props.contents]);
const { contents: normalizedContents, lines, rowsJson } = document;
const targetIndex =
props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
@@ -140,7 +135,7 @@ function useSourceFileModel(props: SourceFileSurfaceProps) {
? "ready"
: "highlighting";
return { lines, status, targetIndex, theme, tokens };
return { lines, rowsJson, status, targetIndex, theme, tokens };
}
function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
@@ -162,39 +157,63 @@ function NativeSourceFileSurface(
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
},
) {
const { NativeView } = props;
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
const { NativeView, onRefresh } = props;
const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
const { width: viewportWidth } = useWindowDimensions();
const { rowsJson, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullToRefresh = useCallback(async () => {
if (!onRefresh) {
return;
}
setIsPullRefreshing(true);
try {
await onRefresh();
} finally {
setIsPullRefreshing(false);
}
}, [onRefresh]);
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
const selectedRowIdsJson = useMemo(
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
[targetIndex],
);
const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
const styleJson = useMemo(() => JSON.stringify(nativeSourceStyle), [nativeSourceStyle]);
const contentWidth = codeWordBreak
? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
: NATIVE_SOURCE_CONTENT_WIDTH;
return (
<View className="relative flex-1 bg-card">
<View className="relative flex-1 bg-sheet">
<SourceHighlightStatusView status={status} />
<NativeView
key={props.path}
collapsable={false}
testID="source-native-code-view"
style={{ flex: 1 }}
appearanceScheme={theme}
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
contentResetKey={props.path}
contentWidth={contentWidth}
initialRowIndex={targetIndex ?? -1}
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
rowHeight={nativeSourceStyle.rowHeight ?? codeSurface.rowHeight}
rowsJson={rowsJson}
selectedRowIdsJson={selectedRowIdsJson}
styleJson={NATIVE_SOURCE_STYLE_JSON}
styleJson={styleJson}
themeJson={themeJson}
tokensJson={tokensJson}
{...(onRefresh
? {
refreshing: isPullRefreshing,
onPullToRefresh: () => void handlePullToRefresh(),
}
: {})}
/>
</View>
);
}
function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
const listRef = useRef<FlatList<string>>(null);
@@ -211,39 +230,53 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
const renderLine = useCallback(
({ item, index }: { item: string; index: number }) => (
<HighlightedSourceLine
codeSurface={codeSurface}
index={index}
line={item}
tokens={tokens?.[index] ?? null}
highlighted={index === targetIndex}
wordBreak={codeWordBreak}
/>
),
[targetIndex, tokens],
[codeSurface, codeWordBreak, targetIndex, tokens],
);
const list = (
<FlatList
ref={listRef}
data={lines}
keyExtractor={(_line, index) => String(index)}
initialNumToRender={80}
maxToRenderPerBatch={80}
windowSize={12}
{...(codeWordBreak
? {}
: {
getItemLayout: (_data, index) => ({
length: codeSurface.rowHeight,
offset: codeSurface.rowHeight * index,
index,
}),
})}
contentContainerStyle={{
minWidth: codeWordBreak ? undefined : "100%",
paddingBottom: codeSurface.rowHeight,
paddingTop: 8,
}}
renderItem={renderLine}
/>
);
return (
<View className="relative flex-1 bg-card">
<View className="relative flex-1 bg-sheet">
<SourceHighlightStatusView status={status} />
<ScrollView horizontal bounces={false} className="flex-1">
<FlatList
ref={listRef}
data={lines}
keyExtractor={(_line, index) => String(index)}
initialNumToRender={80}
maxToRenderPerBatch={80}
windowSize={12}
getItemLayout={(_data, index) => ({
length: SOURCE_LINE_HEIGHT,
offset: SOURCE_LINE_HEIGHT * index,
index,
})}
contentContainerStyle={{
minWidth: "100%",
paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
paddingTop: 8,
}}
renderItem={renderLine}
/>
</ScrollView>
{codeWordBreak ? (
list
) : (
<ScrollView horizontal bounces={false} className="flex-1">
{list}
</ScrollView>
)}
</View>
);
}
@@ -1,8 +1,15 @@
import Stack from "expo-router/stack";
import { SymbolView } from "expo-symbols";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, Text as RNText, View } from "react-native";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
ScrollView,
useColorScheme,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import {
EnvironmentId,
@@ -12,22 +19,31 @@ import {
} from "@t3tools/contracts";
import { AppText as Text } from "../../components/AppText";
import { CopyTextButton } from "../../components/CopyTextButton";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { cn } from "../../lib/cn";
import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useEnvironmentQuery } from "../../state/query";
import { projectEnvironment } from "../../state/projects";
import {
useAdaptiveWorkspaceLayout,
useAdaptiveWorkspacePaneRole,
useRegisterWorkspaceInspector,
} from "../layout/AdaptiveWorkspaceLayout";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
import { SourceFileSurface } from "./SourceFileSurface";
import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
import {
@@ -72,196 +88,6 @@ function defaultViewMode(path: string | null): FileViewMode {
: "source";
}
function ModeButton(props: {
readonly active: boolean;
readonly icon: "doc.text" | "eye";
readonly label: string;
readonly onPress: () => void;
}) {
const iconColor = String(
useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"),
);
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.active }}
className={cn(
"h-8 flex-row items-center justify-center gap-1.5 rounded-full px-3 active:opacity-70",
props.active ? "bg-primary" : "bg-subtle",
)}
onPress={props.onPress}
>
<SymbolView name={props.icon} size={13} tintColor={iconColor} type="monochrome" />
<Text
className={cn(
"text-xs font-t3-bold",
props.active ? "text-primary-foreground" : "text-foreground-muted",
)}
>
{props.label}
</Text>
</Pressable>
);
}
function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) {
const gradientId = `file-breadcrumb-${props.side}-fade`;
const isLeft = props.side === "left";
return (
<View
pointerEvents="none"
className={cn("absolute inset-y-0 w-7", isLeft ? "left-0" : "right-0")}
>
<Svg width="100%" height="100%">
<Defs>
<LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
<Stop offset="0%" stopColor={props.color} stopOpacity={isLeft ? 1 : 0} />
<Stop offset="100%" stopColor={props.color} stopOpacity={isLeft ? 0 : 1} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
</Svg>
</View>
);
}
function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) {
const iconColor = String(useThemeColor("--color-icon-muted"));
const cardColor = String(useThemeColor("--color-card"));
const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 });
const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false });
const breadcrumbs = useMemo(
() => fileBreadcrumbs(props.projectName, props.relativePath),
[props.projectName, props.relativePath],
);
const updateFadeVisibility = useCallback(
(metrics: Partial<(typeof scrollMetrics)["current"]>) => {
Object.assign(scrollMetrics.current, metrics);
const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current;
const maxOffset = Math.max(0, contentWidth - viewportWidth);
const next = {
left: maxOffset > 1 && offsetX > 1,
right: maxOffset > 1 && offsetX < maxOffset - 1,
};
setFadeVisibility((current) =>
current.left === next.left && current.right === next.right ? current : next,
);
},
[],
);
return (
<View className="min-w-0 flex-1">
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
onContentSizeChange={(contentWidth) => {
updateFadeVisibility({ contentWidth });
}}
onLayout={(event) => {
updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width });
}}
onScroll={(event) => {
updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x });
}}
scrollEventThrottle={16}
>
<View className="h-8 flex-row items-center">
{breadcrumbs.map((crumb, index) => (
<View key={crumb.path || "project"} className="flex-row items-center">
{index > 0 ? (
<SymbolView
name="chevron.right"
size={10}
tintColor={iconColor}
type="monochrome"
/>
) : null}
<Text
className={cn(
"max-w-[180px] px-1 text-xs",
crumb.kind === "file"
? "font-t3-bold text-foreground"
: "font-t3-medium text-foreground-muted",
)}
numberOfLines={1}
>
{crumb.label}
</Text>
</View>
))}
</View>
</ScrollView>
{fadeVisibility.left ? <BreadcrumbFade color={cardColor} side="left" /> : null}
{fadeVisibility.right ? <BreadcrumbFade color={cardColor} side="right" /> : null}
</View>
);
}
function FilePreviewHeader(props: {
readonly activeMode: FileViewMode;
readonly showModeSelector: boolean;
readonly externalPreviewUri?: string | null;
readonly projectName: string;
readonly relativePath: string;
readonly onSetMode: (mode: FileViewMode) => void;
}) {
const iconColor = String(useThemeColor("--color-icon-muted"));
return (
<View className="border-b border-border bg-card px-3 py-2">
<View className="flex-row items-center gap-2">
<FileBreadcrumbs projectName={props.projectName} relativePath={props.relativePath} />
<CopyTextButton
accessibilityLabel="Copy file path"
text={props.relativePath}
tintColor={iconColor}
buttonSize={32}
iconSize={13}
/>
</View>
{props.showModeSelector ? (
<View className="mt-2 flex-row items-center gap-2">
<ModeButton
active={props.activeMode === "preview"}
icon="eye"
label="Preview"
onPress={() => props.onSetMode("preview")}
/>
<ModeButton
active={props.activeMode === "source"}
icon="doc.text"
label="Source"
onPress={() => props.onSetMode("source")}
/>
{props.externalPreviewUri !== undefined ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Open preview in Safari"
disabled={props.externalPreviewUri === null}
hitSlop={8}
className={cn(
"ml-auto h-8 w-8 items-center justify-center rounded-full bg-subtle active:opacity-70",
props.externalPreviewUri === null && "opacity-40",
)}
onPress={() => {
if (typeof props.externalPreviewUri === "string") {
void tryOpenExternalUrl(props.externalPreviewUri, "file-preview");
}
}}
>
<SymbolView name="safari" size={15} tintColor={iconColor} type="monochrome" />
</Pressable>
) : null}
</View>
) : null}
</View>
);
}
function FileContent(props: {
readonly activeMode: FileViewMode;
readonly previewUri: string | null;
@@ -270,6 +96,7 @@ function FileContent(props: {
readonly relativePath: string;
readonly initialLine: number | null;
readonly truncated: boolean;
readonly onRefresh?: () => Promise<void> | void;
}) {
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
const isBrowserFile = isBrowserPreviewFile(props.relativePath);
@@ -293,7 +120,7 @@ function FileContent(props: {
if (props.fileError && props.fileContents === null) {
return (
<View className="flex-1 items-center justify-center bg-card px-6">
<View className="flex-1 items-center justify-center bg-sheet px-6">
<EmptyState title="File unavailable" detail={props.fileError} />
</View>
);
@@ -301,7 +128,7 @@ function FileContent(props: {
if (props.fileContents === null) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<View className="flex-1 items-center justify-center gap-3 bg-sheet px-6">
<ActivityIndicator />
<Text className="text-center text-sm text-foreground-muted">Loading file...</Text>
</View>
@@ -309,35 +136,47 @@ function FileContent(props: {
}
return (
<View className="flex-1 bg-card">
<View className="flex-1 bg-sheet">
{props.truncated ? (
<View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
<Text className="text-2xs font-t3-bold uppercase text-amber-700 dark:text-amber-300">
Partial file
</Text>
<Text className="text-xs leading-[17px] text-amber-800 dark:text-amber-200">
<Text className="text-xs leading-snug text-amber-800 dark:text-amber-200">
Preview limited to the first 1 MB of a truncated file.
</Text>
</View>
) : null}
{props.activeMode === "preview" && isMarkdown ? (
<FileMarkdownPreview markdown={props.fileContents} />
<FileMarkdownPreview markdown={props.fileContents} onRefresh={props.onRefresh} />
) : (
<SourceFileSurface
contents={props.fileContents}
path={props.relativePath}
initialLine={props.initialLine}
onRefresh={props.onRefresh}
/>
)}
</View>
);
}
function useThreadFilesWorkspace() {
const params = useLocalSearchParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
type ThreadFilesRouteScreenProps = StaticScreenProps<{
readonly environmentId: string;
readonly threadId: string;
}>;
type ThreadFileRouteScreenProps = StaticScreenProps<{
readonly environmentId: string;
readonly threadId: string;
readonly path: string[];
readonly line?: string;
}>;
function useThreadFilesWorkspace(params: {
readonly environmentId?: string | string[];
readonly threadId?: string | string[];
}) {
const routeEnvironmentId = firstRouteParam(params.environmentId);
const routeThreadId = firstRouteParam(params.threadId);
const { selectedThread, selectedThreadProject } = useThreadSelection();
@@ -364,7 +203,7 @@ function useThreadFilesWorkspace() {
function FilesUnavailable() {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<Stack.Screen options={{ title: "Files" }} />
<NativeStackScreenOptions options={{ title: "Files" }} />
<EmptyState
title="Files unavailable"
detail="This thread does not have an active workspace path."
@@ -373,40 +212,6 @@ function FilesUnavailable() {
);
}
function FilesHeaderTitle(props: { readonly projectName: string }) {
const foregroundColor = String(useThemeColor("--color-foreground"));
const secondaryForegroundColor = String(useThemeColor("--color-foreground-secondary"));
return (
<View style={{ alignItems: "center", maxWidth: 220 }}>
<RNText
numberOfLines={1}
style={{
color: foregroundColor,
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
fontWeight: "900",
letterSpacing: -0.4,
}}
>
Files
</RNText>
<RNText
numberOfLines={1}
style={{
color: secondaryForegroundColor,
fontFamily: "DMSans_500Medium",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "500",
letterSpacing: 0.2,
}}
>
{props.projectName}
</RNText>
</View>
);
}
function FilesToolbarBottomFade() {
const sheetColor = String(useThemeColor("--color-sheet"));
@@ -442,12 +247,20 @@ function FilesToolbarBottomFade() {
);
}
export function ThreadFilesTreeScreen() {
const router = useRouter();
export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useNavigation();
const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
useAdaptiveWorkspaceLayout();
const [searchQuery, setSearchQuery] = useState("");
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const colorScheme = useColorScheme();
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
props.route.params,
);
const revealedInspectorRef = useRef(false);
const entriesQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null
environmentId !== null && cwd !== null && !fileInspector.supported
? projectEnvironment.listEntries({
environmentId,
input: { cwd },
@@ -455,18 +268,87 @@ export function ThreadFilesTreeScreen() {
: null,
);
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
const handleReturnToThread = useCallback(() => {
if (navigation.canGoBack()) {
navigation.goBack();
return;
}
if (environmentId !== null && threadId !== null) {
navigation.dispatch(
StackActions.replace("Thread", {
environmentId: String(environmentId),
threadId: String(threadId),
}),
);
}
}, [environmentId, navigation, threadId]);
const handleSelectFile = useCallback(
(path: string) => {
if (environmentId === null || threadId === null) {
return;
}
router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
const params = {
environmentId: String(environmentId),
threadId: String(threadId),
path: path.split("/").filter((segment) => segment.length > 0),
};
const navigationAction = resolveFileSelectionNavigationAction({
hasPersistentFileInspector: fileInspector.supported,
});
if (navigationAction === "replace") {
navigation.dispatch(StackActions.replace("ThreadFile", params));
return;
}
navigation.navigate("ThreadFile", params);
},
[environmentId, router, threadId],
[environmentId, fileInspector.supported, navigation, threadId],
);
const renderInspector = useCallback(
(headerInset: number) =>
environmentId !== null && cwd !== null ? (
<ThreadFileNavigatorPane
cwd={cwd}
environmentId={environmentId}
headerInset={headerInset}
projectName={projectName}
selectedPath={null}
onSelectFile={handleSelectFile}
/>
) : null,
[cwd, environmentId, handleSelectFile, projectName],
);
const handlePreviewFile = useCallback(
(relativePath: string) => {
if (environmentId === null || cwd === null) {
return;
}
preloadWorkspaceFileContents({
cwd,
environmentId,
relativePath,
theme: highlightTheme,
});
},
[cwd, environmentId, highlightTheme],
);
useEffect(() => {
if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
revealedInspectorRef.current = true;
showAuxiliaryPane("inspector");
}
}, [cwd, fileInspector.supported, showAuxiliaryPane]);
if (selectedThread === null || environmentId === null || threadId === null) {
if (fileInspector.supported) {
return (
<ThreadRouteScreen
onReturnToThread={handleReturnToThread}
renderInspector={renderInspector}
route={props.route}
/>
);
}
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
}
@@ -474,62 +356,95 @@ export function ThreadFilesTreeScreen() {
return <FilesUnavailable />;
}
if (fileInspector.supported) {
return (
<ThreadRouteScreen
onReturnToThread={handleReturnToThread}
renderInspector={renderInspector}
route={props.route}
/>
);
}
const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
return (
<View className="flex-1 bg-sheet">
<Stack.Screen
<>
{/* Static header config (glass preset, title, contentStyle) lives in Stack.tsx.
Only genuinely dynamic options are set here. */}
<NativeStackScreenOptions
options={{
title: "Files",
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTitle: () => <FilesHeaderTitle projectName={projectName} />,
headerSearchBarOptions: {
allowToolbarIntegration: true,
autoCapitalize: "none",
hideNavigationBar: false,
placeholder: "Search files",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
},
unstable_headerSubtitle:
Platform.OS === "ios" && projectName.length > 0 ? projectName : undefined,
// No refresh button: the list already supports pull-to-refresh.
unstable_headerToolbarItems: usesCompactMailToolbar
? () => [
createNativeMailSearchToolbarItem({
onSearchTextChange: setSearchQuery,
placeholder: "Search files",
searchTextChangeId: "files-search-text",
}),
]
: undefined,
headerSearchBarOptions: usesCompactMailToolbar
? undefined
: {
allowToolbarIntegration: true,
autoCapitalize: "none",
hideNavigationBar: false,
placeholder: "Search files",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
accessibilityLabel="Refresh files"
icon="arrow.clockwise"
onPress={entriesQuery.refresh}
/>
</Stack.Toolbar>
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
</Stack.Toolbar>
{layout.usesSplitView ? (
<NativeHeaderToolbar placement="left">
<NativeHeaderToolbar.Button
accessibilityLabel={panes.primarySidebarVisible ? "Maximize files" : "Show threads"}
icon={
panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
}
onPress={togglePrimarySidebar}
separateBackground
/>
</NativeHeaderToolbar>
) : null}
{usesCompactMailToolbar ? null : (
<NativeHeaderToolbar placement="bottom">
<NativeHeaderToolbar.SearchBarSlot />
</NativeHeaderToolbar>
)}
<FileTreeBrowser
entries={entriesData?.entries ?? []}
error={entriesQuery.error}
isPending={entriesQuery.isPending}
searchQuery={searchQuery}
selectedPath={null}
onPreviewFile={handlePreviewFile}
onRefresh={entriesQuery.refresh}
onSelectFile={handleSelectFile}
/>
<FilesToolbarBottomFade />
</View>
</>
);
}
export function ThreadFileScreen() {
const params = useLocalSearchParams<{
line?: string | string[];
path?: string | string[];
}>();
export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useNavigation();
const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
const iconColor = useThemeColor("--color-icon");
const params = props.route.params;
const relativePath = normalizeRoutePath(params.path);
const targetLine = normalizeRouteLine(firstRouteParam(params.line));
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
props.route.params,
);
const [modeOverride, setModeOverride] = useState<{
readonly path: string;
readonly mode: FileViewMode;
@@ -568,6 +483,43 @@ export function ThreadFileScreen() {
);
const fileData = fileQuery.data as ProjectReadFileResult | null;
const handleSelectFile = useCallback(
(path: string) => {
navigation.navigate("ThreadFile", {
environmentId: String(environmentId),
threadId: String(threadId),
path: path.split("/").filter(Boolean),
});
},
[environmentId, navigation, threadId],
);
const renderInspector = useCallback(
(headerInset: number) =>
fileInspector.supported && environmentId !== null && cwd !== null ? (
<ThreadFileNavigatorPane
cwd={cwd}
environmentId={environmentId}
headerInset={headerInset}
projectName={projectName}
selectedPath={relativePath}
onSelectFile={handleSelectFile}
/>
) : undefined,
[cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
);
// The workspace inspector column spans the full window height. On iOS the
// pane brings its own nested native header; elsewhere it pads itself below
// the top inset.
const safeAreaInsets = useSafeAreaInsets();
const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
// Hand the file navigator to the workspace so it renders beside the
// navigator, outside this screen's native header.
const renderWorkspaceInspector = useCallback(
() => renderInspector(inspectorHeaderInset),
[inspectorHeaderInset, renderInspector],
);
useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
if (selectedThread === null || environmentId === null || threadId === null) {
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
}
@@ -579,38 +531,104 @@ export function ThreadFileScreen() {
if (relativePath === null) {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<Stack.Screen options={{ title: "Files" }} />
<NativeStackScreenOptions options={{ title: "Files" }} />
<EmptyState title="File unavailable" detail="This file path is invalid." />
</View>
);
}
const parentDir = relativePath.split("/").slice(0, -1).join("/");
const headerSubtitle = [projectName, parentDir].filter(Boolean).join(" · ");
return (
<ReviewHighlighterProvider>
<View className="flex-1 bg-sheet">
<Stack.Screen options={{ title: basename(relativePath) }} />
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="arrow.clockwise"
onPress={() => {
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
setPreviewRevision((current) => current + 1);
return;
}
fileQuery.refresh();
}}
/>
</Stack.Toolbar>
<FilePreviewHeader
activeMode={resolvedActiveMode}
showModeSelector={canPreview && !isImageFile}
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
projectName={projectName}
relativePath={relativePath}
onSetMode={(mode) => {
setModeOverride({ path: relativePath, mode });
<NativeStackScreenOptions
options={{
// Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS: solid
// sheet-colored header — this route's content scrolls internally, so
// there is nothing for glass to sample). Only dynamic values here.
headerTintColor: iconColor,
headerTitle: basename(relativePath),
title: basename(relativePath),
unstable_headerSubtitle:
Platform.OS === "ios" && headerSubtitle.length > 0 ? headerSubtitle : undefined,
}}
/>
<WorkspaceSidebarToolbar>
{fileInspector.supported ? (
<NativeHeaderToolbar.Button
accessibilityLabel="Return to chat"
icon="chevron.left"
onPress={() => {
navigation.dispatch(
StackActions.replace("Thread", {
environmentId: String(environmentId),
threadId: String(threadId),
}),
);
}}
/>
) : null}
</WorkspaceSidebarToolbar>
<NativeHeaderToolbar placement="right">
{fileInspector.supported ? (
<NativeHeaderToolbar.Button
accessibilityLabel={
panes.auxiliaryPaneVisible ? "Hide file navigator" : "Show file navigator"
}
icon="sidebar.right"
onPress={toggleAuxiliaryPane}
separateBackground
/>
) : null}
<NativeHeaderToolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
{canPreview && !isImageFile ? (
<NativeHeaderToolbar.Menu inline>
<NativeHeaderToolbar.MenuAction
icon="eye"
isOn={resolvedActiveMode === "preview"}
onPress={() => setModeOverride({ path: relativePath, mode: "preview" })}
>
Preview
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
icon="doc.text"
isOn={resolvedActiveMode === "source"}
onPress={() => setModeOverride({ path: relativePath, mode: "source" })}
>
Source
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
) : null}
<NativeHeaderToolbar.MenuAction
icon="doc.on.doc"
onPress={() => copyTextWithHaptic(relativePath)}
>
Copy path
</NativeHeaderToolbar.MenuAction>
{isBrowserFile && typeof assetPreviewUri === "string" ? (
<NativeHeaderToolbar.MenuAction
icon="safari"
onPress={() => {
void tryOpenExternalUrl(assetPreviewUri, "file-preview");
}}
>
Open in Safari
</NativeHeaderToolbar.MenuAction>
) : null}
{resolvedActiveMode === "preview" && (isBrowserFile || isImageFile) ? (
<NativeHeaderToolbar.MenuAction
icon="arrow.clockwise"
onPress={() => {
setPreviewRevision((current) => current + 1);
}}
>
Refresh
</NativeHeaderToolbar.MenuAction>
) : null}
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
@@ -619,6 +637,7 @@ export function ThreadFileScreen() {
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
onRefresh={() => fileQuery.refresh()}
/>
</View>
</ReviewHighlighterProvider>
@@ -24,7 +24,7 @@ export function WorkspaceFileWebPreview(props: { readonly uri: string | null })
{loadError ? (
<View className="border-b border-border bg-card px-4 py-2">
<Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>
<Text className="mt-0.5 text-xs leading-[17px] text-foreground-muted">{loadError}</Text>
<Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text>
</View>
) : null}
<WebView
@@ -3,26 +3,38 @@ import type {
NativeReviewDiffStyle,
NativeReviewDiffToken,
} from "../diffs/nativeReviewDiffSurface";
import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
import { resolveMobileCodeSurface } from "../../lib/appearancePreferences";
import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "../../lib/typography";
import type { SourceHighlightTokens } from "./sourceHighlightingState";
export const NATIVE_SOURCE_ROW_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
export const NATIVE_SOURCE_CONTENT_WIDTH = 32_000;
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = {
rowHeight: NATIVE_SOURCE_ROW_HEIGHT,
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
changeBarWidth: 0,
gutterWidth: MOBILE_CODE_SURFACE.gutterWidth,
codePadding: MOBILE_CODE_SURFACE.codePadding,
textVerticalInset: MOBILE_CODE_SURFACE.textVerticalInset,
codeFontSize: MOBILE_CODE_SURFACE.fontSize,
codeFontWeight: "regular",
lineNumberFontSize: MOBILE_CODE_SURFACE.lineNumberFontSize,
lineNumberFontWeight: "regular",
emptyStateFontSize: MOBILE_TYPOGRAPHY.label.fontSize,
emptyStateFontWeight: "medium",
};
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = createNativeSourceStyle(
resolveMobileCodeSurface(MOBILE_CODE_SURFACE.fontSize),
);
export function createNativeSourceStyle(
codeSurface: ResolvedMobileCodeSurface,
): NativeReviewDiffStyle {
return {
rowHeight: codeSurface.rowHeight,
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
changeBarWidth: 0,
gutterWidth: codeSurface.gutterWidth,
codePadding: codeSurface.codePadding,
textVerticalInset: codeSurface.textVerticalInset,
codeFontSize: codeSurface.fontSize,
codeFontWeight: "regular",
lineNumberFontSize: codeSurface.lineNumberFontSize,
lineNumberFontWeight: "regular",
emptyStateFontSize: Math.round(
MOBILE_TYPOGRAPHY.label.fontSize * (codeSurface.fontSize / MOBILE_CODE_SURFACE.fontSize),
),
emptyStateFontWeight: "medium",
};
}
const SOURCE_FILE_ID = "source-file";
@@ -0,0 +1,74 @@
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { appAtomRegistry } from "../../state/atom-registry";
import { projectEnvironment } from "../../state/projects";
import { isBrowserPreviewFile, isImagePreviewFile } from "./filePath";
import { prepareSourceFileDocument } from "./source-file-document";
import { sourceHighlightAtom } from "./sourceHighlightingState";
import type { ReviewDiffTheme } from "../review/shikiReviewHighlighter";
const inFlightPreloads = new Map<string, Promise<void>>();
const MAX_HIGHLIGHT_PRELOAD_CHARACTERS = 256 * 1024;
function preloadKey(input: {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly relativePath: string;
}): string {
return JSON.stringify([input.environmentId, input.cwd, input.relativePath]);
}
export function preloadWorkspaceFileContents(input: {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly relativePath: string;
readonly theme: ReviewDiffTheme;
}): void {
if (isBrowserPreviewFile(input.relativePath) || isImagePreviewFile(input.relativePath)) {
return;
}
const key = preloadKey(input);
if (inFlightPreloads.has(key)) {
return;
}
const preload = executeAtomQuery(
appAtomRegistry,
projectEnvironment.readFile({
environmentId: input.environmentId,
input: { cwd: input.cwd, relativePath: input.relativePath },
}),
{
label: "workspace file preload",
reportDefect: false,
reportFailure: false,
},
)
.then(async (result) => {
if (result._tag === "Success") {
const document = prepareSourceFileDocument(result.value.contents);
if (document.contents.length <= MAX_HIGHLIGHT_PRELOAD_CHARACTERS) {
await executeAtomQuery(
appAtomRegistry,
sourceHighlightAtom({
path: input.relativePath,
contents: document.contents,
theme: input.theme,
}),
{
label: "workspace source highlight preload",
reportDefect: false,
reportFailure: false,
},
);
}
}
})
.finally(() => {
inFlightPreloads.delete(key);
});
inFlightPreloads.set(key, preload);
}
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vite-plus/test";
import { prepareSourceFileDocument } from "./source-file-document";
describe("prepareSourceFileDocument", () => {
it("normalizes and serializes source rows once for repeated consumers", () => {
const first = prepareSourceFileDocument("const value = 1;\r\n\tvalue;\r");
const second = prepareSourceFileDocument("const value = 1;\r\n\tvalue;\r");
const rows = JSON.parse(first.rowsJson) as ReadonlyArray<{ readonly content: string }>;
expect(first.contents).toBe("const value = 1;\n\tvalue;\n");
expect(first.lines).toEqual(["const value = 1;", "\tvalue;", ""]);
expect(rows.map((row) => row.content)).toEqual(["const value = 1;", " value;", ""]);
expect(second).toBe(first);
});
});
@@ -0,0 +1,54 @@
import { buildNativeSourceRows } from "./nativeSourceFileAdapter";
const MAX_CACHED_DOCUMENTS = 8;
const MAX_CACHED_CHARACTERS = 4 * 1024 * 1024;
export interface SourceFileDocument {
readonly contents: string;
readonly lines: ReadonlyArray<string>;
readonly rowsJson: string;
}
const documentCache = new Map<string, SourceFileDocument>();
let cachedCharacterCount = 0;
function removeOldestCachedDocument(): void {
const oldestKey = documentCache.keys().next().value;
if (typeof oldestKey !== "string") {
return;
}
const document = documentCache.get(oldestKey);
documentCache.delete(oldestKey);
cachedCharacterCount -= (document?.contents.length ?? 0) + (document?.rowsJson.length ?? 0);
}
export function prepareSourceFileDocument(contents: string): SourceFileDocument {
const cached = documentCache.get(contents);
if (cached !== undefined) {
documentCache.delete(contents);
documentCache.set(contents, cached);
return cached;
}
const normalizedContents = contents.replace(/\r\n?/g, "\n");
const lines = normalizedContents.split("\n");
const document = {
contents: normalizedContents,
lines,
rowsJson: JSON.stringify(buildNativeSourceRows(lines)),
} satisfies SourceFileDocument;
const characterCount = document.contents.length + document.rowsJson.length;
if (characterCount <= MAX_CACHED_CHARACTERS) {
while (
documentCache.size >= MAX_CACHED_DOCUMENTS ||
cachedCharacterCount + characterCount > MAX_CACHED_CHARACTERS
) {
removeOldestCachedDocument();
}
documentCache.set(contents, document);
cachedCharacterCount += characterCount;
}
return document;
}
@@ -88,7 +88,7 @@ describe("sourceHighlightingState", () => {
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
});
firstUnmount();
await new Promise((resolve) => setTimeout(resolve, 25));
await new Promise((resolve) => setTimeout(resolve, 100));
const secondUnmount = registry.mount(atom);
await vi.waitFor(() => {
@@ -0,0 +1,175 @@
import type { EnvironmentId, ProjectListEntriesResult } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState, type ComponentProps } from "react";
import { Platform, Pressable, useColorScheme, View, type NativeSyntheticEvent } from "react-native";
import {
Screen,
ScreenStack,
ScreenStackHeaderConfig,
ScreenStackHeaderSearchBarView,
SearchBar,
} from "react-native-screens";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
import { useThemeColor } from "../../lib/useThemeColor";
import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
export function ThreadFileNavigatorPane(props: {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly headerInset: number;
readonly projectName: string;
readonly selectedPath: string | null;
readonly onSelectFile: (path: string) => void;
}) {
const [searchQuery, setSearchQuery] = useState("");
const colorScheme = useColorScheme();
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
const iconColor = String(useThemeColor("--color-icon-muted"));
const foregroundColor = String(useThemeColor("--color-foreground"));
const sheetColor = String(useThemeColor("--color-sheet"));
const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
const entriesQuery = useEnvironmentQuery(
projectEnvironment.listEntries({
environmentId: props.environmentId,
input: { cwd: props.cwd },
}),
);
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
const handlePreviewFile = useCallback(
(relativePath: string) => {
preloadWorkspaceFileContents({
cwd: props.cwd,
environmentId: props.environmentId,
relativePath,
theme: highlightTheme,
});
},
[highlightTheme, props.cwd, props.environmentId],
);
const nativeHeaderRightBarButtonItems = useMemo(
() =>
[
{
accessibilityLabel: "Refresh files",
icon: { name: "arrow.clockwise", type: "sfSymbol" as const },
identifier: "thread-file-navigator-refresh",
onPress: entriesQuery.refresh,
sharesBackground: false,
tintColor: foregroundColor,
type: "button" as const,
width: 44,
},
] as ComponentProps<typeof ScreenStackHeaderConfig>["headerRightBarButtonItems"],
[entriesQuery.refresh, foregroundColor],
);
const fileTree = (
<FileTreeBrowser
entries={entriesData?.entries ?? []}
error={entriesQuery.error}
isPending={entriesQuery.isPending}
searchQuery={searchQuery}
selectedPath={props.selectedPath}
onPreviewFile={handlePreviewFile}
onRefresh={entriesQuery.refresh}
onSelectFile={props.onSelectFile}
/>
);
if (Platform.OS === "ios") {
return (
<View className="flex-1 border-l border-border bg-sheet">
<ScreenStack style={{ flex: 1 }}>
<Screen
activityState={2}
enabled
isNativeStack
screenId="thread-file-navigator-native"
scrollEdgeEffects={headerScrollEdgeEffects}
style={{ backgroundColor: sheetColor, flex: 1 }}
>
{fileTree}
<ScreenStackHeaderConfig
backgroundColor="rgba(0,0,0,0)"
color={foregroundColor}
headerRightBarButtonItems={nativeHeaderRightBarButtonItems}
hideBackButton
hideShadow={false}
navigationItemStyle="editor"
subtitle={props.projectName}
title="Files"
titleColor={foregroundColor}
titleFontSize={17}
titleFontWeight="700"
translucent
>
<ScreenStackHeaderSearchBarView>
<SearchBar
allowToolbarIntegration
autoCapitalize="none"
barTintColor={sheetColor}
hideNavigationBar={false}
hideWhenScrolling={false}
obscureBackground={false}
onCancelButtonPress={() => {
setSearchQuery("");
}}
onChangeText={(event: NativeSyntheticEvent<{ readonly text?: string }>) => {
setSearchQuery(event.nativeEvent.text ?? "");
}}
placement="integratedButton"
placeholder="Search files"
textColor={foregroundColor}
tintColor={foregroundColor}
/>
</ScreenStackHeaderSearchBarView>
</ScreenStackHeaderConfig>
</Screen>
</ScreenStack>
</View>
);
}
return (
<View className="flex-1 border-l border-border bg-sheet">
<View className="border-b border-border" style={{ paddingTop: props.headerInset }}>
<View className="h-12 flex-row items-center gap-2 px-3">
<View className="min-w-0 flex-1">
<Text className="text-sm font-t3-bold text-foreground">Files</Text>
<Text className="text-xs text-foreground-muted" numberOfLines={1}>
{props.projectName}
</Text>
</View>
<Pressable
accessibilityRole="button"
accessibilityLabel="Refresh files"
hitSlop={8}
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
onPress={entriesQuery.refresh}
>
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
</Pressable>
</View>
<View className="flex-row items-center gap-2 border-t border-border px-3 py-2">
<SymbolView name="magnifyingglass" size={15} tintColor={iconColor} type="monochrome" />
<TextInput
accessibilityLabel="Search files"
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="while-editing"
className="min-h-10 flex-1 rounded-xl py-2 text-sm"
placeholder="Search files"
value={searchQuery}
onChangeText={setSearchQuery}
/>
</View>
</View>
{fileTree}
</View>
);
}
+170 -204
View File
@@ -3,60 +3,30 @@ import type {
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import { Stack } from "expo-router";
import { Text as RNText, View } from "react-native";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useRef } from "react";
import { Platform } from "react-native";
import type { SearchBarCommands } from "react-native-screens";
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
import { useThemeColor } from "../../lib/useThemeColor";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import type { HomeProjectSortOrder } from "./homeThreadList";
import {
buildHomeListFilterMenu,
type HomeListFilterMenuEnvironment,
} from "./home-list-filter-menu";
import {
hasCustomHomeListOptions,
PROJECT_GROUPING_OPTIONS,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
} from "./home-list-options";
export interface HomeHeaderEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
}
const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
const THREAD_SORT_OPTIONS: ReadonlyArray<{
readonly value: SidebarThreadSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
readonly value: SidebarProjectGroupingMode;
readonly label: string;
readonly subtitle: string;
}> = [
{
value: "repository",
label: "Group by repository",
subtitle: "Combine matching repositories across environments",
},
{
value: "repository_path",
label: "Group by repository path",
subtitle: "Combine only matching paths within a repository",
},
{
value: "separate",
label: "Keep separate",
subtitle: "Show every project path separately",
},
];
export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment;
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
export function HomeHeader(props: {
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
@@ -72,174 +42,170 @@ export function HomeHeader(props: {
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
const searchBarRef = useRef<SearchBarCommands>(null);
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const hasCustomListOptions =
props.selectedEnvironmentId !== null ||
props.projectSortOrder !== DEFAULT_SIDEBAR_PROJECT_SORT_ORDER ||
props.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
props.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE;
const hasCustomListOptions = hasCustomHomeListOptions(props);
const focusSearch = useCallback(() => {
searchBarRef.current?.focus();
return searchBarRef.current !== null;
}, []);
useHardwareKeyboardCommand("focusSearch", focusSearch);
const filterMenu = buildHomeListFilterMenu(props);
return (
<>
<Stack.Screen
<NativeStackScreenOptions
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
// Static header config (glass, title, fonts) lives in Stack.tsx
// (GLASS_HEADER_OPTIONS). Only dynamic values are set here.
headerTintColor: iconColor,
headerTitle: "",
headerSearchBarOptions: {
placeholder: "Search threads",
hideNavigationBar: false,
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
allowToolbarIntegration: true,
},
unstable_headerRightItems:
Platform.OS === "ios"
? () => [
withNativeGlassHeaderItem({
accessibilityLabel: "Open settings",
icon: { name: "ellipsis", type: "sfSymbol" } as const,
identifier: "home-settings",
label: "",
onPress: props.onOpenSettings,
type: "button",
}),
]
: undefined,
unstable_headerToolbarItems:
Platform.OS === "ios"
? () => [
createNativeMailSearchToolbarItem({
composeButtonId: "home-new-task",
composeSystemImageName: "square.and.pencil",
filterMenu,
filterButtonId: "home-filter",
filterSystemImageName: hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease",
onComposePress: props.onStartNewTask,
onSearchTextChange: props.onSearchQueryChange,
placeholder: "Search",
searchTextChangeId: "home-search-text",
}),
]
: undefined,
headerSearchBarOptions:
Platform.OS === "ios"
? undefined
: {
ref: searchBarRef,
allowToolbarIntegration: true,
hideNavigationBar: false,
placeholder: "Search",
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
},
}}
/>
<Stack.Toolbar placement="left">
<Stack.Toolbar.View hidesSharedBackground>
<View
style={{
width: 128,
height: 32,
flexDirection: "row",
alignItems: "center",
gap: 8,
}}
{Platform.OS === "ios" ? null : (
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button
accessibilityLabel="Open settings"
icon="gearshape"
onPress={props.onOpenSettings}
separateBackground
/>
</NativeHeaderToolbar>
)}
{Platform.OS === "ios" ? null : (
<NativeHeaderToolbar placement="bottom">
<NativeHeaderToolbar.Menu
accessibilityLabel="Filter and sort threads"
icon={
hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
title="Thread list options"
separateBackground
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
color: iconColor,
letterSpacing: -0.4,
}}
>
T3 Code
</RNText>
<View
style={{
backgroundColor: subtleColor,
borderRadius: 99,
paddingHorizontal: 8,
paddingVertical: 3,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.micro.fontSize,
color: mutedColor,
letterSpacing: 1.1,
textTransform: "uppercase",
}}
<NativeHeaderToolbar.MenuAction onPress={props.onOpenSettings}>
<NativeHeaderToolbar.Label>Settings</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.Menu title="Environment">
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
subtitle="Show threads from every environment"
>
Alpha
</RNText>
</View>
</View>
</Stack.Toolbar.View>
</Stack.Toolbar>
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
{props.environments.map((environment) => (
<NativeHeaderToolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
accessibilityLabel="Filter and sort threads"
icon={
hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Thread list options"
>
<Stack.Toolbar.Menu title="Environment">
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
subtitle="Show threads from every environment"
>
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
{props.environments.map((environment) => (
<Stack.Toolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<NativeHeaderToolbar.Menu title="Sort projects">
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.projectSortOrder === option.value}
onPress={() => props.onProjectSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
<Stack.Toolbar.Menu title="Sort projects">
<Stack.Toolbar.Label>Sort projects</Stack.Toolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.projectSortOrder === option.value}
onPress={() => props.onProjectSortOrderChange(option.value)}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<NativeHeaderToolbar.Menu title="Sort threads">
<NativeHeaderToolbar.Label>Sort threads</NativeHeaderToolbar.Label>
{THREAD_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.threadSortOrder === option.value}
onPress={() => props.onThreadSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
<Stack.Toolbar.Menu title="Sort threads">
<Stack.Toolbar.Label>Sort threads</Stack.Toolbar.Label>
{THREAD_SORT_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.threadSortOrder === option.value}
onPress={() => props.onThreadSortOrderChange(option.value)}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu title="Group projects">
<Stack.Toolbar.Label>Group projects</Stack.Toolbar.Label>
{PROJECT_GROUPING_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.projectGroupingMode === option.value}
onPress={() => props.onProjectGroupingModeChange(option.value)}
subtitle={option.subtitle}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
<Stack.Toolbar.Button
accessibilityLabel="Open settings"
icon="gearshape"
onPress={props.onOpenSettings}
separateBackground
/>
</Stack.Toolbar>
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
<Stack.Toolbar.Button
accessibilityLabel="New task"
icon="square.and.pencil"
onPress={props.onStartNewTask}
separateBackground
/>
</Stack.Toolbar>
<NativeHeaderToolbar.Menu title="Group projects">
<NativeHeaderToolbar.Label>Group projects</NativeHeaderToolbar.Label>
{PROJECT_GROUPING_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.projectGroupingMode === option.value}
onPress={() => props.onProjectGroupingModeChange(option.value)}
subtitle={option.subtitle}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar.Menu>
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
<NativeHeaderToolbar.SearchBarSlot />
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
<NativeHeaderToolbar.Button
accessibilityLabel="New task"
icon="square.and.pencil"
onPress={props.onStartNewTask}
separateBackground
/>
</NativeHeaderToolbar>
)}
</>
);
}
@@ -0,0 +1,149 @@
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useMemo, useState } from "react";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { HomeScreen } from "./HomeScreen";
import { HomeHeader } from "./HomeHeader";
import { useHomeListOptions } from "./home-list-options";
import { usePendingTaskListActions } from "./usePendingTaskListActions";
import { useThreadListActions } from "./useThreadListActions";
/* ─── Route screen ───────────────────────────────────────────────────── */
export function HomeRouteScreen() {
const { layout } = useAdaptiveWorkspaceLayout();
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const navigation = useNavigation();
const [searchQuery, setSearchQuery] = useState("");
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(
Order.String,
(environment: { readonly label: string }) => environment.label,
),
),
[savedConnectionsById],
);
const availableEnvironmentIds = useMemo(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
);
const {
options: listOptions,
setSelectedEnvironmentId,
setProjectGroupingMode,
setProjectSortOrder,
setThreadSortOrder,
} = useHomeListOptions(availableEnvironmentIds);
const selectedEnvironmentId = listOptions.selectedEnvironmentId;
// In split layouts the persistent sidebar IS the thread list — Home becomes
// an empty detail pane so selecting a thread never transitions layouts.
if (layout.usesSplitView) {
return (
<>
<NativeStackScreenOptions options={{ title: "", headerTitle: "" }} />
<WorkspaceSidebarToolbar
afterSidebarButton={
<NativeHeaderToolbar.Button
accessibilityLabel="New task"
icon="square.and.pencil"
onPress={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
/>
}
/>
<WorkspaceEmptyDetail
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
/>
</>
);
}
return (
<>
{/* Restore the compact title in case the split branch blanked it. */}
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
<HomeHeader
environments={environments}
selectedEnvironmentId={selectedEnvironmentId}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
projectGroupingMode={listOptions.projectGroupingMode}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
/>
<HomeScreen
catalogState={catalogState}
environments={environments}
onAddConnection={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
navigation.navigate("Thread", {
environmentId: thread.environmentId,
threadId: thread.id,
});
}}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
onNewThreadInProject={(project) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
pendingTasks={pendingTasks}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
</>
);
}
+280 -446
View File
@@ -1,3 +1,8 @@
import {
LegendList,
type LegendListRef,
type LegendListRenderItemProps,
} from "@legendapp/list/react-native";
import {
type EnvironmentProject,
type EnvironmentThreadShell,
@@ -7,101 +12,74 @@ import type {
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
Easing,
LinearTransition,
type ExitAnimationsValues,
withDelay,
withTiming,
} from "react-native-reanimated";
import { ActivityIndicator, Platform, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
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 { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "../threads/threadPresentation";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import { scopedProjectKey } from "../../lib/scopedEntities";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "./thread-swipe-actions";
PendingTaskListRow,
ThreadListGroupHeader,
ThreadListRow,
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import {
buildHomeListLayout,
DEFAULT_GROUP_DISPLAY_STATE,
homeListItemsAreEqual,
nextGroupDisplayState,
type HomeGroupDisplayAction,
type HomeGroupDisplayState,
type HomeListItem,
} from "./homeListItems";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
/* ─── Types ──────────────────────────────────────────────────────────── */
interface HomeScreenProps {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onSearchQueryChange: (query: string) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
}
/* ─── Status indicator colors ────────────────────────────────────────── */
/* ─── Layout constants ───────────────────────────────────────────────── */
function statusColors(thread: EnvironmentThreadShell): { 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;
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
function threadRowExit(values: ExitAnimationsValues) {
"worklet";
return {
initialValues: {
height: values.currentHeight,
opacity: 1,
originX: values.currentOriginX,
},
animations: {
height: withDelay(
90,
withTiming(0, {
duration: 170,
easing: Easing.inOut(Easing.cubic),
}),
),
opacity: withDelay(80, withTiming(0, { duration: 100 })),
originX: withTiming(values.currentOriginX - values.windowWidth, {
duration: 190,
easing: Easing.out(Easing.cubic),
}),
},
};
}
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
/** Height of the floating custom header on non-iOS platforms. */
const CUSTOM_HEADER_HEIGHT = 78;
function deriveEmptyState(props: {
readonly catalogState: WorkspaceState;
@@ -166,287 +144,28 @@ function deriveEmptyState(props: {
};
}
/* ─── Project group header ───────────────────────────────────────────── */
function ProjectGroupLabel(props: {
readonly project: EnvironmentProject;
readonly title: string;
readonly totalThreadCount: number;
readonly isExpanded: boolean;
readonly onToggleExpand: () => void;
}) {
const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
return (
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
environmentId={props.project.environmentId}
size={18}
projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
<Text
className="flex-1 text-xs font-t3-medium uppercase text-foreground-muted"
style={{ letterSpacing: 0.5 }}
numberOfLines={1}
>
{props.title}
</Text>
{hiddenCount > 0 ? (
<Pressable onPress={props.onToggleExpand} hitSlop={8}>
<Text
className="text-xs font-t3-medium text-foreground-muted"
style={{ letterSpacing: 0.4 }}
>
{props.isExpanded ? "Show less" : `${hiddenCount} more`}
</Text>
</Pressable>
) : null}
</View>
);
}
/* ─── Thread row ─────────────────────────────────────────────────────── */
function ThreadRow(props: {
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly onPress: () => void;
readonly onArchive: () => void;
readonly onDelete: () => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly isLast: boolean;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const separatorColor = useThemeColor("--color-separator");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const cardColor = useThemeColor("--color-card");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const { bg, fg } = statusColors(props.thread);
const tone = threadStatusTone(props.thread);
const timestamp = relativeTime(
props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt,
);
const branch = props.thread.branch;
const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
Boolean(part),
);
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
}
fullSwipeArmedRef.current = armed;
}, []);
return (
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
childrenContainerStyle={{ backgroundColor: cardColor }}
containerStyle={{ backgroundColor: cardColor }}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
if (swipeableRef.current) {
props.onSwipeableClose(swipeableRef.current);
}
}}
onSwipeableOpenStartDrag={() => {
if (swipeableRef.current) {
props.onSwipeableWillOpen(swipeableRef.current);
}
}}
onSwipeableWillOpen={() => {
const methods = swipeableRef.current;
if (!methods) {
return;
}
props.onSwipeableWillOpen(methods);
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
props.onDelete();
}
}}
overshootFriction={1}
overshootRight
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={cardColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
accessibilityLabel: `Archive ${props.thread.title}`,
icon: "archivebox",
label: "Archive",
onPress: props.onArchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
>
<Pressable
accessibilityHint="Swipe left for archive and delete actions"
accessibilityLabel={props.thread.title}
accessibilityRole="button"
className="bg-card"
onPress={() => {
swipeableRef.current?.close();
props.onPress();
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
<View
style={{
flexDirection: "row",
paddingLeft: 16,
paddingRight: 16,
paddingVertical: 10,
gap: 12,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
}}
>
<View
style={{
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 2,
}}
>
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
</View>
<View style={{ flex: 1, gap: 3 }}>
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-base font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<View className="flex-row items-center gap-2">
<View
className={tone.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-3xs font-t3-bold ${tone.textClassName}`}>
{tone.label}
</Text>
</View>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
</View>
{subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconSubtleColor}
type="monochrome"
/>
<Text
className="text-2xs text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitleParts.join(" · ")}
</Text>
</View>
) : null}
</View>
</View>
</Pressable>
</ReanimatedSwipeable>
);
function HomeTopContentSpacer(props: { readonly topInset: number }) {
return <View style={{ height: props.topInset + CUSTOM_HEADER_HEIGHT }} />;
}
/* ─── Main screen ────────────────────────────────────────────────────── */
function staleCatalogPillLabel(props: { readonly catalogState: WorkspaceState }): string {
if (props.catalogState.networkStatus === "offline") {
return "You are offline";
}
const connectingEnvironments = props.catalogState.connectingEnvironments;
if (connectingEnvironments.length === 1) {
return `Reconnecting to ${connectingEnvironments[0]!.environmentLabel}`;
}
if (connectingEnvironments.length > 1) {
return `Reconnecting ${connectingEnvironments.length} environments`;
}
return "Not connected";
}
function StaleCatalogStatusPill(props: {
readonly catalogState: WorkspaceState;
readonly onPress: () => void;
}) {
const iconColor = useThemeColor("--color-icon-muted");
const label = staleCatalogPillLabel(props);
const isReconnecting = props.catalogState.connectingEnvironments.length > 0;
return (
<Pressable
accessibilityRole="button"
onPress={props.onPress}
className="flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
style={{
shadowColor: "#000",
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.12,
shadowRadius: 24,
}}
>
{isReconnecting ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="wifi.slash"
size={15}
tintColor={iconColor}
type="monochrome"
weight="semibold"
/>
)}
<Text className="max-w-[260px] text-sm font-t3-bold text-foreground" numberOfLines={1}>
{label}
</Text>
</Pressable>
);
}
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
>(() => new Map());
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const toggleExpanded = useCallback((key: string) => {
setExpandedProjects((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
setGroupDisplayStates((previous) => {
const next = new Map(previous);
next.set(
key,
nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
);
return next;
});
}, []);
@@ -464,11 +183,19 @@ export function HomeScreen(props: HomeScreenProps) {
}
}, []);
const handleScrollBeginDrag = useCallback(() => {
openSwipeableRef.current?.close();
}, []);
const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
onScrollBeginDrag: handleScrollBeginDrag,
});
const projectGroups = useMemo(
() =>
buildHomeThreadGroups({
projects: props.projects,
threads: props.threads,
pendingTasks: props.pendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
@@ -476,6 +203,7 @@ export function HomeScreen(props: HomeScreenProps) {
projectGroupingMode: props.projectGroupingMode,
}),
[
props.pendingTasks,
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
@@ -486,135 +214,241 @@ export function HomeScreen(props: HomeScreenProps) {
],
);
const hasSearchQuery = props.searchQuery.trim().length > 0;
const listLayout = useMemo(
() =>
buildHomeListLayout({
groups: projectGroups,
displayStates: groupDisplayStates,
showAllThreads: hasSearchQuery,
}),
[projectGroups, groupDisplayStates, hasSearchQuery],
);
const projectCwdByKey = useMemo(() => {
const map = new Map<string, string>();
for (const project of props.projects) {
map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);
}
return map;
}, [props.projects]);
const extraData = useMemo(
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
[props.savedConnectionsById, projectCwdByKey],
);
const renderItem = useCallback(
({ item }: LegendListRenderItemProps<HomeListItem>) => {
switch (item.type) {
case "header":
return (
<ThreadListGroupHeader
variant="compact"
collapsed={item.collapsed}
isFirst={item.isFirst}
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
// Aggregated groups (same repo across machines) have no single
// target project, and `pending-project:` groups hold a placeholder
// built from queued-task metadata rather than a real project shell,
// so the quick new-thread button is single-real-project only.
newThreadTarget={item.group.newThreadTarget}
onNewThread={props.onNewThreadInProject}
project={item.group.representative}
threadCount={item.group.threads.length + item.group.pendingTasks.length}
title={item.group.title}
/>
);
case "pending-task":
return (
<PendingTaskListRow
variant="compact"
pendingTask={item.pendingTask}
environmentLabel={
props.savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null
}
isLast={item.isLast}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
);
case "thread": {
const thread = item.thread;
return (
<ThreadListRow
variant="compact"
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
null
}
isLast={item.isLast}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onSelectThread={props.onSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
);
}
case "show-more":
return (
<ThreadListShowMoreRow
variant="compact"
hiddenCount={item.hiddenCount}
canShowLess={item.canShowLess}
groupKey={item.groupKey}
onGroupAction={updateGroupDisplay}
/>
);
}
},
[
handleSwipeableClose,
handleSwipeableWillOpen,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
props.onDeleteThread,
props.onNewThreadInProject,
props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
updateGroupDisplay,
],
);
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
/* Empty states */
const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
const hasAnyThreads =
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
const hasResults = projectGroups.length > 0;
const selectedEnvironmentLabel =
props.selectedEnvironmentId === null
? null
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
const hasSearchQuery = props.searchQuery.trim().length > 0;
const shouldShowConnectionStatus =
props.catalogState.networkStatus === "offline" ||
props.catalogState.hasConnectingEnvironment ||
(props.catalogState.hasLoadedShellSnapshot && !props.catalogState.hasReadyEnvironment);
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
projectCount: props.projects.length,
});
const connectionStatus =
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
</View>
) : null;
return (
<View className="flex-1 bg-screen">
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
className="flex-1"
contentContainerStyle={{
paddingHorizontal: 16,
paddingTop: 8,
paddingBottom: 24,
gap: 20,
if (!hasAnyThreads) {
return (
<View
className="flex-1 items-center justify-center bg-screen px-8"
style={{
paddingBottom: Math.max(insets.bottom, 24),
paddingTop: Platform.OS === "ios" ? insets.top + 72 : insets.top,
}}
>
{!hasAnyThreads ? (
<View>
<EmptyState
title={emptyState.title}
detail={emptyState.detail}
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
/>
{emptyState.loading ? (
<View className="absolute right-5 top-5">
<ActivityIndicator color={accentColor} />
</View>
) : null}
</View>
) : !hasResults && hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : !hasResults && selectedEnvironmentLabel ? (
<View className="w-full max-w-[430px]">
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
title={emptyState.title}
detail={emptyState.detail}
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
variant="plain"
/>
) : !hasResults ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding session."
/>
) : (
projectGroups.map((group) => {
const isExpanded = expandedProjects.has(group.key);
const visibleThreads = isExpanded
? group.threads
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
{emptyState.loading ? (
<View className="mt-4 items-center">
<ActivityIndicator color={accentColor} />
</View>
) : null}
</View>
{connectionStatus}
</View>
);
}
return (
<Animated.View
key={group.key}
collapsable={false}
exiting={threadRowExit}
layout={THREAD_LAYOUT_TRANSITION}
style={{ overflow: "hidden" }}
>
<ProjectGroupLabel
isExpanded={isExpanded}
onToggleExpand={() => toggleExpanded(group.key)}
project={group.representative}
title={group.title}
totalThreadCount={group.threads.length}
/>
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{visibleThreads.map((thread, i) => {
const threadKey = `${thread.environmentId}:${thread.id}`;
return (
<Animated.View
key={threadKey}
collapsable={false}
exiting={threadRowExit}
layout={THREAD_LAYOUT_TRANSITION}
style={{ overflow: "hidden" }}
>
<ThreadRow
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ??
null
}
isLast={i === visibleThreads.length - 1}
onArchive={() => props.onArchiveThread(thread)}
onDelete={() => props.onDeleteThread(thread)}
onPress={() => props.onSelectThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
</Animated.View>
);
})}
</View>
</Animated.View>
);
})
)}
</ScrollView>
{shouldShowConnectionStatus ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<StaleCatalogStatusPill
catalogState={props.catalogState}
const listHeader = (
<>
{Platform.OS === "ios" ? null : <HomeTopContentSpacer topInset={insets.top} />}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View style={{ paddingBottom: 16 }}>
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</>
);
const listEmpty = !hasResults ? (
hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : selectedEnvironmentLabel ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : (
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
)
) : null;
return (
<View className="flex-1 bg-screen">
{/* Sticky headers are deliberately not wired up: LegendList's JS sticky
implementation mispositions pinned headers at mount under iOS
automatic content insets (headers render one nav-inset too low until
the first scroll event) and blanks non-pinned headers after
collapse/expand data changes. The flattened layout still exposes
`stickyHeaderIndices` if this gets revisited. */}
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<LegendList
ref={listRef}
data={listLayout.items}
renderItem={renderItem}
keyExtractor={keyExtractor}
itemsAreEqual={homeListItemsAreEqual}
drawDistance={500}
estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
extraData={extraData}
ListHeaderComponent={listHeader}
ListEmptyComponent={listEmpty}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
{...scrollGateHandlers}
recycleItems
scrollEventThrottle={16}
contentContainerStyle={{
paddingBottom: Platform.OS === "ios" ? Math.max(insets.bottom, 24) + 24 : 24,
}}
scrollIndicatorInsets={
Platform.OS === "ios"
? {
bottom: Math.max(insets.bottom, 16) + 24,
top: 0,
}
: undefined
}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
Loaded 100 of 344 files, more files were not shown because too many files have changed in this diff. Show more