Compare commits

...
Author SHA1 Message Date
Julius Marminge 77544333e0 Improve mobile settings navigation and cached connection state
- Nest settings routes for form-sheet navigation
- Persist server config and VCS refs across web and mobile
- Add mobile header actions for empty connection state
2026-07-08 04:05:22 -07:00
Julius Marminge 10ca14a362 Tighten mobile navigation targets 2026-06-30 17:32:34 -07:00
Julius Marminge ee203ed518 Structure mobile navigation around native stack 2026-06-30 16:12:14 -07:00
Julius Marminge f6df16ab1e Replace Expo Router with native stack navigation 2026-06-30 11:41:13 -07:00
Julius Marminge a423e3c4b1 Move thread detail chrome to direct RNS 2026-06-30 09:46:59 -07:00
Julius Marminge c656e071e4 Wire iPad header search to thread sidebar 2026-06-30 08:44:41 -07:00
Julius Marminge 856fc61e65 Tune native mobile glass toolbar grouping 2026-06-30 08:26:38 -07:00
Julius Marminge 3158e1dc12 Group iPad detail header controls 2026-06-30 07:57:44 -07:00
Julius Marminge a930a44212 Polish native mobile Mail-style chrome 2026-06-30 07:39:55 -07:00
Julius Marminge 5bfd2161be Remove stale thread toolbar search slot 2026-06-30 04:58:51 -07:00
Julius Marminge 258a36a7f0 Flatten mobile not found link style 2026-06-30 04:50:22 -07:00
Julius Marminge a838270400 Use compact native search in iPad thread header 2026-06-30 04:40:23 -07:00
Julius Marminge 92404ecfd8 Use native new task sheet controls 2026-06-30 04:23:06 -07:00
Julius Marminge c77e6af72a Use native scroll edge effects on list headers 2026-06-30 04:11:46 -07:00
Julius Marminge dfbfc25a8f Centralize native header scroll edge effects 2026-06-30 04:05:42 -07:00
Julius Marminge 8fb62e1ba3 Use native glass header for file previews 2026-06-30 03:43:37 -07:00
Julius Marminge c70e6b5c34 Align inspector toolbar placement on iPad 2026-06-30 03:32:09 -07:00
Julius Marminge ffdacaf73d Use native Mail toolbar for file search 2026-06-30 03:14:16 -07:00
Julius Marminge 7cddaba1da Tune selected sidebar status pill contrast 2026-06-30 02:39:21 -07:00
Julius Marminge 035eb3b2e6 Centralize native Mail search toolbar config 2026-06-30 02:30:55 -07:00
Julius Marminge c1f87cc48b Show native search in iPad thread header 2026-06-30 02:15:56 -07:00
Julius Marminge c11d0c68e7 Use native header for git inspector 2026-06-30 02:08:45 -07:00
Julius Marminge 1b7051a5d3 Use native header search for file inspector 2026-06-30 01:59:32 -07:00
Julius Marminge 34379b6f5e Share archive row swipe behavior 2026-06-30 01:39:40 -07:00
Julius Marminge 27606a9c94 Use native iPad archive header search 2026-06-30 01:23:04 -07:00
Julius Marminge 2caf6dd1be Use Mail-style overflow controls on mobile 2026-06-30 01:10:37 -07:00
Julius Marminge af87ceced9 Add split sidebar control to terminal header 2026-06-30 00:59:41 -07:00
Julius Marminge 9083c716ea Hide thread search while inspector owns search 2026-06-30 00:47:06 -07:00
Julius Marminge b00deefb03 Match Mail sidebar selection on iPad 2026-06-30 00:37:24 -07:00
Julius Marminge f5d4d7b63c Stop forcing native glass debug route 2026-06-30 00:18:38 -07:00
Julius Marminge a0e0b6ef71 Add split home compose toolbar button 2026-06-30 00:01:16 -07:00
Julius Marminge 3e4b357a86 Add native sidebar status subtitle 2026-06-29 23:50:55 -07:00
Julius Marminge 0f3201e699 Use native edge chrome on file and review routes 2026-06-29 23:32:06 -07:00
Julius Marminge 2c00d79902 Use shared native scroll edge effect in thread surfaces 2026-06-29 23:16:01 -07:00
Julius Marminge 9e52f110e2 Use native glass header for terminal route 2026-06-29 23:05:17 -07:00
Julius Marminge 051160cfec Simplify iPhone thread native header 2026-06-29 22:51:23 -07:00
Julius Marminge fdac1fbcd4 Use Expo Router native home toolbar 2026-06-29 22:30:20 -07:00
Julius Marminge 036e481ec0 Fix native iOS thread header integration 2026-06-29 22:12:22 -07:00
Julius Marminge 29ffec87c0 Hide split detail native title 2026-06-29 19:57:07 -07:00
Julius Marminge 6c96dc7e92 Nudge iPad detail header controls inward 2026-06-29 19:02:21 -07:00
Julius Marminge 2f4fdfa03e Align iPad thread controls with Mail 2026-06-29 18:39:43 -07:00
Julius Marminge 89139e9394 Stabilize iPad thread header controls 2026-06-29 18:28:10 -07:00
Julius Marminge fcb6b03380 Align iPad detail header with Mail 2026-06-29 17:50:41 -07:00
Julius Marminge b5ef318748 Use native split thread header title 2026-06-29 17:40:20 -07:00
Julius Marminge 59af9dce68 Recover stale mobile thread routes 2026-06-29 17:05:45 -07:00
Julius Marminge a4472d0f49 Wire native iPad thread toolbar 2026-06-29 16:22:58 -07:00
Julius Marminge ce72ed4eb8 Restore native iPad thread search 2026-06-29 15:11:53 -07:00
Julius Marminge 5a1138cf39 Polish native phone chrome 2026-06-29 14:43:02 -07:00
Julius Marminge 618506f135 Group native iOS header controls 2026-06-29 14:16:34 -07:00
Julius Marminge 873a000567 Adopt native iOS glass navigation chrome 2026-06-29 13:10:36 -07:00
Julius Marminge b83af8a48e Reveal files inspector once 2026-06-27 12:54:20 -07:00
Julius Marminge 80208bc2c4 Stabilize inspector pane state 2026-06-27 12:44:54 -07:00
Julius Marminge c2aba434a1 Polish inspector routing behavior 2026-06-27 12:35:47 -07:00
Julius Marminge bf00c7e8a6 Fix sidebar selection and file return 2026-06-27 12:30:36 -07:00
Julius Marminge 43b9724418 Harden split inspector edge cases 2026-06-27 12:24:47 -07:00
Julius Marminge bcf070aa2c Fix file inspector route regressions 2026-06-27 12:21:31 -07:00
Julius Marminge 42a2275bbd Fix split inspector review followups 2026-06-27 12:17:54 -07:00
Julius Marminge 5efa2df4ab Address mobile review lifecycle issues 2026-06-27 12:12:33 -07:00
Julius Marminge e4ec3cfca7 Resolve remaining iPad review issues 2026-06-27 11:51:58 -07:00
Julius Marminge 75f0e90c03 Fix iPad header and input review issues 2026-06-27 11:27:13 -07:00
Julius Marminge ea8339ec90 Address iPad layout review feedback 2026-06-27 11:23:12 -07:00
Julius Marminge 7f81813feb Polish iPad mobile layout and native headers 2026-06-27 11:15:16 -07:00
Julius Marminge c4e63e0648 Fix EAS iOS CocoaPods UUID cache 2026-06-26 22:01:12 -07:00
Julius Marminge 4689c43c98 Refactor session handling and stream event processing 2026-06-26 18:43:31 -07:00
Julius Marminge 32e1983e61 Bump Clerk and Expo dependencies
- Update Clerk packages across web, desktop, relay, and mobile
- Refresh lockfile entries for related Expo and native packages
2026-06-26 17:55:40 -07:00
Julius Marminge babbf90197 Update Expo iOS tooling and native glass header 2026-06-26 17:25:24 -07:00
Julius Marminge 8351e7ca31 Refine mobile layout for iPad and native glass headers
- add thread selection context for split-view routing
- switch thread feeds to automatic content insets on iOS glass headers
- add native scroll-edge effect helper and app domain config
2026-06-26 17:08:26 -07:00
Julius Marmingeandcodex d353476417 Memoize thread navigation callbacks
- Stabilize thread selection routing in the adaptive workspace layout
- Extract and memoize thread sidebar rows to reduce unnecessary rerenders

Co-authored-by: codex <[email protected]>
2026-06-26 17:08:26 -07:00
Julius Marmingeandcodex a896942bc7 Improve mobile thread navigation and diff selection
- Keep sidebar threads swipeable with archive/delete actions
- Hide archived threads from navigation groups
- Stabilize review diff visibility and optimistic file selection

Co-authored-by: codex <[email protected]>
2026-06-26 17:08:26 -07:00
Julius Marmingeandcodex cf0f731bc8 Add split-view mobile navigation and native controls
- Adapt iPad/mobile layout for sidebar, inspector, and sheets
- Move review diff payloads off Fabric props and add native scrolling
- Add iOS header button module for consistent toolbar actions

Co-authored-by: codex <[email protected]>
2026-06-26 17:08:18 -07:00
Julius Marmingeandcodex 80d2b26d94 Add split-view mobile workspace layout
- Enable adaptive sidebar navigation on wide mobile windows
- Keep compact single-pane behavior on phones
- Extract and test shared thread grouping and layout logic

Co-authored-by: codex <[email protected]>
2026-06-26 17:08:18 -07:00
156 changed files with 15557 additions and 2964 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
{
"ios": {
"bundleIdentifier": "com.juliusmarminge.-t3toolsmonorepo"
}
}
+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
+10 -1
View File
@@ -17,6 +17,7 @@ const VARIANT_CONFIG: Record<
readonly iosIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
readonly relyingParty?: string;
}
> = {
development: {
@@ -25,6 +26,7 @@ const VARIANT_CONFIG: Record<
iosIcon: "./assets/icon-composer-dev.icon",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
relyingParty: "clerk.t3.codes",
},
preview: {
appName: "T3 Code Preview",
@@ -32,6 +34,7 @@ const VARIANT_CONFIG: Record<
iosIcon: "./assets/icon-composer-prod.icon",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
},
production: {
appName: "T3 Code",
@@ -39,6 +42,7 @@ const VARIANT_CONFIG: Record<
iosIcon: "./assets/icon-composer-prod.icon",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
relyingParty: "clerk.t3.codes",
},
};
@@ -77,6 +81,10 @@ const config: ExpoConfig = {
icon: variant.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
associatedDomains: [
`applinks:${variant.relyingParty}`,
`webcredentials:${variant.relyingParty}`,
],
infoPlist: {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
@@ -101,7 +109,6 @@ const config: ExpoConfig = {
favicon: "./assets/favicon.png",
},
plugins: [
"expo-router",
"expo-font",
"expo-secure-store",
["@clerk/expo", { theme: "./clerk-theme.json" }],
@@ -139,6 +146,7 @@ const config: ExpoConfig = {
},
},
],
"./plugins/withIosCocoaPodsUuidCache.cjs",
[
"expo-widgets",
{
@@ -155,6 +163,7 @@ const config: ExpoConfig = {
],
},
],
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
],
extra: {
+5 -1
View File
@@ -1,2 +1,6 @@
import "react-native-gesture-handler";
import "expo-router/entry";
import { registerRootComponent } from "expo";
import App from "./src/App";
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
@@ -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,37 @@ public class T3ReviewDiffModule: Module {
view.setInitialRowIndex(initialRowIndex)
}
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
Events(
"onDebug",
"onVisibleFileChange",
"onToggleFile",
"onToggleViewedFile",
"onPressLine",
"onToggleComment"
)
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,10 +327,18 @@ 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()
@@ -379,6 +391,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 +415,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 +549,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 +661,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 +686,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 +790,18 @@ 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)
}
private func applyStyle() {
contentView.style = ReviewDiffNativeStyle
.resolve(stylePayload)
@@ -686,6 +818,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 +1419,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
@@ -17,6 +17,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
}
@@ -24,11 +24,37 @@ private enum GhosttyRuntime {
private final class TerminalInputField: UITextField {
var onDeleteBackward: (() -> Void)?
var onInsert: ((String) -> Void)?
override var keyCommands: [UIKeyCommand]? {
[
command(input: "\t", modifiers: UIKeyModifierFlags(), action: #selector(handleTab)),
command(input: "\t", modifiers: .shift, action: #selector(handleBackTab)),
]
}
override func deleteBackward() {
onDeleteBackward?()
super.deleteBackward()
}
private func command(
input: String,
modifiers: UIKeyModifierFlags,
action: Selector
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
command.wantsPriorityOverSystemBehavior = true
return command
}
@objc private func handleTab() {
onInsert?("\t")
}
@objc private func handleBackTab() {
onInsert?("\u{1B}[Z")
}
}
private enum TerminalAppearanceScheme: String {
@@ -108,6 +134,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 +202,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)
+22 -19
View File
@@ -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.6",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "0.35.9",
"react-native-reanimated": "4.3.1",
@@ -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;
});
};
+46
View File
@@ -0,0 +1,46 @@
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { RegistryContext } from "@effect/atom-react";
import { LoadingScreen } from "./components/LoadingScreen";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { AppNavigationProvider } from "./navigation/app-navigation";
import { RootNavigator } from "./navigation/RootNavigator";
import { appAtomRegistry } from "./state/atom-registry";
import "../global.css";
export default function App() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
<AppNavigationProvider>
{fontsLoaded ? (
<RootNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
</AppNavigationProvider>
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</CloudAuthProvider>
</RegistryContext.Provider>
);
}
-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>
);
}
-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>
);
}
-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;
@@ -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 />;
}
+195 -12
View File
@@ -18,7 +18,9 @@ import {
EnvironmentId,
OrchestrationThread,
OrchestrationShellSnapshot,
ServerConfig,
ThreadId,
VcsListRefsResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -34,6 +36,10 @@ const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const SERVER_CONFIG_CACHE_DIRECTORY = "connection-server-configs";
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_DIRECTORY = "connection-vcs-refs";
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
@@ -48,6 +54,19 @@ const StoredThreadSnapshot = Schema.Struct({
thread: OrchestrationThread,
});
const StoredServerConfig = Schema.Struct({
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
config: ServerConfig,
});
const StoredVcsRefs = Schema.Struct({
schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
cwd: Schema.String,
refs: VcsListRefsResult,
});
const LegacyStoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
environmentId: EnvironmentId,
@@ -55,6 +74,16 @@ const LegacyStoredShellSnapshot = Schema.Struct({
snapshot: OrchestrationShellSnapshot,
});
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
const decodeStoredServerConfig = Schema.decodeUnknownResult(StoredServerConfig);
const encodeStoredServerConfig = Schema.encodeUnknownResult(StoredServerConfig);
const decodeStoredVcsRefs = Schema.decodeUnknownResult(StoredVcsRefs);
const encodeStoredVcsRefs = Schema.encodeUnknownResult(StoredVcsRefs);
const decodeLegacyStoredShellSnapshot = Schema.decodeUnknownResult(LegacyStoredShellSnapshot);
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
@@ -69,6 +98,10 @@ function shellPersistenceError(
| "load-thread"
| "save-thread"
| "remove-thread"
| "load-server-config"
| "save-server-config"
| "load-vcs-refs"
| "save-vcs-refs"
| "clear-environment",
cause: unknown,
) {
@@ -82,6 +115,14 @@ function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
}
function environmentCacheFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
function vcsRefsFileName(cwd: string): string {
return `${encodeURIComponent(cwd)}.json`;
}
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
function* (
environmentId: EnvironmentId,
@@ -146,9 +187,54 @@ const secureCatalogStorage: SecureCatalogStorage = {
};
function shellSnapshotFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
return environmentCacheFileName(environmentId);
}
const serverConfigFile = Effect.fn("mobile.connectionStorage.serverConfigFile")(function* (
environmentId: EnvironmentId,
operation: "load-server-config" | "save-server-config" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, SERVER_CONFIG_CACHE_DIRECTORY);
directory.create({ idempotent: true, intermediates: true });
return new File(directory, environmentCacheFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const vcsRefsDirectory = Effect.fn("mobile.connectionStorage.vcsRefsDirectory")(function* (
environmentId: EnvironmentId,
operation: "load-vcs-refs" | "save-vcs-refs" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(
Paths.document,
VCS_REFS_CACHE_DIRECTORY,
encodeURIComponent(environmentId),
);
if (operation !== "clear-environment") {
directory.create({ idempotent: true, intermediates: true });
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const vcsRefsFile = Effect.fn("mobile.connectionStorage.vcsRefsFile")(function* (
environmentId: EnvironmentId,
cwd: string,
operation: "load-vcs-refs" | "save-vcs-refs",
) {
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(yield* vcsRefsDirectory(environmentId, operation), vcsRefsFileName(cwd));
});
const shellSnapshotFileInDirectory = Effect.fn(
"mobile.connectionStorage.shellSnapshotFileInDirectory",
)(function* (
@@ -289,9 +375,9 @@ export const connectionStorageLayer = Layer.effectContext(
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
);
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -310,7 +396,7 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
decodeLegacyStoredShellSnapshot(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
@@ -324,9 +410,9 @@ export const connectionStorageLayer = Layer.effectContext(
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -337,6 +423,47 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadServerConfig: (environmentId) =>
Effect.gen(function* () {
const file = yield* serverConfigFile(environmentId, "load-server-config");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-server-config", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-server-config", cause),
});
const stored = yield* Effect.fromResult(decodeStoredServerConfig(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-server-config", cause)),
);
return stored.environmentId === environmentId
? Option.some(stored.config)
: Option.none();
}),
saveServerConfig: (environmentId, config) =>
Effect.gen(function* () {
const file = yield* serverConfigFile(environmentId, "save-server-config");
const encoded = yield* Effect.fromResult(
encodeStoredServerConfig({
schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
environmentId,
config,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-server-config", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-server-config", cause),
});
}),
loadThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
@@ -351,9 +478,9 @@ export const connectionStorageLayer = Layer.effectContext(
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
);
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -362,7 +489,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
encodeStoredThreadSnapshot({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
@@ -379,6 +506,48 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
loadVcsRefs: (environmentId, cwd) =>
Effect.gen(function* () {
const file = yield* vcsRefsFile(environmentId, cwd, "load-vcs-refs");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-vcs-refs", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-vcs-refs", cause),
});
const stored = yield* Effect.fromResult(decodeStoredVcsRefs(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-vcs-refs", cause)),
);
return stored.environmentId === environmentId && stored.cwd === cwd
? Option.some(stored.refs)
: Option.none();
}),
saveVcsRefs: (environmentId, cwd, refs) =>
Effect.gen(function* () {
const file = yield* vcsRefsFile(environmentId, cwd, "save-vcs-refs");
const encoded = yield* Effect.fromResult(
encodeStoredVcsRefs({
schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
environmentId,
cwd,
refs,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-vcs-refs", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-vcs-refs", cause),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
@@ -408,6 +577,13 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const configFile = yield* serverConfigFile(environmentId, "clear-environment");
if (configFile.exists) {
yield* Effect.try({
try: () => configFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
environmentId,
"clear-environment",
@@ -418,6 +594,13 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const refsDirectory = yield* vcsRefsDirectory(environmentId, "clear-environment");
if (refsDirectory.exists) {
yield* Effect.try({
try: () => refsDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
});
@@ -1,12 +1,12 @@
import { useEffect, useRef } from "react";
import * as Notifications from "expo-notifications";
import { useRouter } from "expo-router";
import { useAppNavigation } from "../../navigation/native-stack-header";
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
export function useAgentNotificationNavigation(): void {
const router = useRouter();
const navigation = useAppNavigation();
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: (deepLink) => navigation.push(deepLink as never),
});
};
@@ -28,5 +28,5 @@ export function useAgentNotificationNavigation(): void {
return () => {
subscription.remove();
};
}, [router]);
}, [navigation]);
}
@@ -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 "../../navigation/native-stack-header";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -4,35 +4,37 @@ import type {
} from "@t3tools/client-runtime/state/shell";
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 "../../navigation/native-stack-header";
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";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
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";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
export interface ArchivedThreadsHeaderEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
@@ -57,79 +59,168 @@ function ArchivedThreadsHeader(props: {
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
<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("");
},
},
headerTransparent: usesNativeChrome,
headerStyle: usesNativeChrome ? { backgroundColor: "transparent" } : undefined,
headerShadowVisible: usesNativeChrome ? false : undefined,
scrollEdgeEffects: usesNativeChrome ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
unstable_navigationItemStyle: usesNativeChrome ? "editor" : undefined,
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>
)}
</>
);
}
@@ -168,26 +259,20 @@ function ArchivedThreadRow(props: {
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 +285,80 @@ function ArchivedThreadRow(props: {
);
return (
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
childrenContainerStyle={{ backgroundColor: cardColor }}
containerStyle={{ backgroundColor: cardColor }}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
if (swipeableRef.current) {
props.onSwipeableClose(swipeableRef.current);
}
<ThreadSwipeable
backgroundColor={cardColor}
fullSwipeWidth={windowWidth - 32}
onDelete={props.onDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
onSwipeableOpenStartDrag={() => {
if (swipeableRef.current) {
props.onSwipeableWillOpen(swipeableRef.current);
}
}}
onSwipeableWillOpen={() => {
const methods = swipeableRef.current;
if (!methods) return;
props.onSwipeableWillOpen(methods);
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
props.onDelete();
}
}}
overshootFriction={1}
overshootRight
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={cardColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={props.thread.title}
>
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
{() => (
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
}}
>
<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-[20px] text-foreground"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{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>
);
}
@@ -341,6 +392,7 @@ export function ArchivedThreadsScreen(props: {
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
}) {
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const archiveScrollGesture = useMemo(() => Gesture.Native(), []);
const refreshTint = useThemeColor("--color-icon");
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
@@ -361,76 +413,85 @@ export function ArchivedThreadsScreen(props: {
<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}
<GestureDetector gesture={archiveScrollGesture}>
<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;
{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}
/>
))}
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)}
simultaneousSwipeGesture={archiveScrollGesture}
thread={thread}
/>
))}
</View>
</View>
</View>
);
})
)}
</ScrollView>
);
})
)}
</ScrollView>
</GestureDetector>
</View>
);
}
@@ -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,11 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly rowHeight: number;
readonly contentWidth: number;
readonly initialRowIndex?: number;
readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
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 +142,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 +277,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
}
try {
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
NATIVE_REVIEW_DIFF_MODULE_NAME,
);
} catch (cause) {
@@ -166,5 +291,5 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
return null;
}
return cachedNativeReviewDiffView ?? null;
return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;
}
@@ -1,6 +1,6 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
@@ -11,9 +11,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 +41,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 +68,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 }}
>
@@ -65,7 +86,9 @@ const FileTreeRow = memo(function FileTreeRow(props: {
<Text
className={cn(
"min-w-0 flex-1 text-sm leading-[19px]",
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
props.selected
? "font-t3-bold text-foreground"
: "font-t3-medium text-foreground-secondary",
)}
numberOfLines={1}
>
@@ -86,13 +109,26 @@ 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 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 +150,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,6 +186,37 @@ 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],
);
return (
<View className="flex-1 bg-sheet">
@@ -152,20 +232,15 @@ export function FileTreeBrowser(props: {
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT}
maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE}
updateCellsBatchingPeriod={16}
windowSize={5}
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}
/>
)}
renderItem={renderItem}
ListEmptyComponent={
<View className="px-4 py-5">
{props.isPending ? (
@@ -20,13 +20,13 @@ import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
import { cn } from "../../lib/cn";
import { MOBILE_CODE_SURFACE } from "../../lib/typography";
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;
@@ -41,10 +41,6 @@ interface SourceFileSurfaceProps {
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 index: number;
readonly line: string;
@@ -119,11 +115,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 +133,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 }) {
@@ -163,8 +156,7 @@ function NativeSourceFileSurface(
},
) {
const { NativeView } = props;
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
const { rowsJson, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
const selectedRowIdsJson = useMemo(
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
@@ -176,11 +168,11 @@ function NativeSourceFileSurface(
<View className="relative flex-1 bg-card">
<SourceHighlightStatusView status={status} />
<NativeView
key={props.path}
collapsable={false}
testID="source-native-code-view"
style={{ flex: 1 }}
appearanceScheme={theme}
contentResetKey={props.path}
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
initialRowIndex={targetIndex ?? -1}
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
@@ -1,8 +1,19 @@
import Stack from "expo-router/stack";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
} from "../../navigation/native-stack-header";
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 { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
ScrollView,
Text as RNText,
useColorScheme,
View,
} from "react-native";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import {
EnvironmentId,
@@ -16,18 +27,30 @@ 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 { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { buildThreadFilesNavigation, threadNavigation } 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 { AdaptiveInspectorLayout } from "../layout/adaptive-inspector-layout";
import {
useAdaptiveWorkspaceLayout,
useAdaptiveWorkspacePaneRole,
} 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 {
@@ -41,6 +64,7 @@ import {
import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
type FileViewMode = "preview" | "source";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
@@ -334,7 +358,7 @@ function FileContent(props: {
}
function useThreadFilesWorkspace() {
const params = useLocalSearchParams<{
const params = useRouteParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
@@ -364,7 +388,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."
@@ -443,11 +467,17 @@ function FilesToolbarBottomFade() {
}
export function ThreadFilesTreeScreen() {
const router = useRouter();
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useAppNavigation();
const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
useAdaptiveWorkspaceLayout();
const [searchQuery, setSearchQuery] = useState("");
const colorScheme = useColorScheme();
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const revealedInspectorRef = useRef(false);
const entriesQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null
environmentId !== null && cwd !== null && !fileInspector.supported
? projectEnvironment.listEntries({
environmentId,
input: { cwd },
@@ -455,18 +485,81 @@ export function ThreadFilesTreeScreen() {
: null,
);
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
const handleReturnToThread = useCallback(() => {
if (navigation.canGoBack()) {
navigation.back();
return;
}
if (environmentId !== null && threadId !== null) {
navigation.replace(threadNavigation({ environmentId, threadId }));
}
}, [environmentId, navigation, threadId]);
const handleSelectFile = useCallback(
(path: string) => {
if (environmentId === null || threadId === null) {
return;
}
router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
const destination = buildThreadFilesNavigation({ environmentId, threadId }, path);
const navigationAction = resolveFileSelectionNavigationAction({
hasPersistentFileInspector: fileInspector.supported,
});
if (navigationAction === "replace") {
navigation.replace(destination);
return;
}
navigation.push(destination);
},
[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],
);
const renderHeaderTitle = useCallback(
() => <FilesHeaderTitle projectName={projectName} />,
[projectName],
);
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}
/>
);
}
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
}
@@ -474,46 +567,90 @@ export function ThreadFilesTreeScreen() {
return <FilesUnavailable />;
}
if (fileInspector.supported) {
return (
<ThreadRouteScreen
onReturnToThread={handleReturnToThread}
renderInspector={renderInspector}
/>
);
}
const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
return (
<View className="flex-1 bg-sheet">
<Stack.Screen
<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("");
},
},
headerTitle: renderHeaderTitle,
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
unstable_headerToolbarItems: usesCompactMailToolbar
? () => [
createNativeMailSearchToolbarItem({
composeButtonId: "files-refresh",
composeSystemImageName: "arrow.clockwise",
onComposePress: entriesQuery.refresh,
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 ? (
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button
accessibilityLabel="Refresh files"
icon="arrow.clockwise"
onPress={entriesQuery.refresh}
/>
</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}
/>
@@ -523,7 +660,11 @@ export function ThreadFilesTreeScreen() {
}
export function ThreadFileScreen() {
const params = useLocalSearchParams<{
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useAppNavigation();
const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
const iconColor = useThemeColor("--color-icon");
const params = useRouteParams<{
line?: string | string[];
path?: string | string[];
}>();
@@ -568,6 +709,33 @@ export function ThreadFileScreen() {
);
const fileData = fileQuery.data as ProjectReadFileResult | null;
const handleSelectFile = useCallback(
(path: string) => {
// We are already on the catch-all file route. Updating its params keeps
// the current native screen mounted while replacing the selected file in
// place, avoiding an RNSScreen snapshot/unmount for every tree click.
navigation.setParams({
line: undefined,
path: path.split("/").filter(Boolean),
});
},
[navigation],
);
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],
);
if (selectedThread === null || environmentId === null || threadId === null) {
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
}
@@ -579,7 +747,7 @@ 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>
);
@@ -588,9 +756,42 @@ export function ThreadFileScreen() {
return (
<ReviewHighlighterProvider>
<View className="flex-1 bg-sheet">
<Stack.Screen options={{ title: basename(relativePath) }} />
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
<NativeStackScreenOptions
options={{
headerTitle: basename(relativePath),
headerTransparent: true,
headerShadowVisible: false,
headerStyle: { backgroundColor: "transparent" },
headerTintColor: iconColor,
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
title: basename(relativePath),
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
}}
/>
<WorkspaceSidebarToolbar>
{fileInspector.supported ? (
<NativeHeaderToolbar.Button
accessibilityLabel="Return to chat"
icon="chevron.left"
onPress={() => {
navigation.replace(threadNavigation({ environmentId, 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.Button
accessibilityLabel="Refresh file"
icon="arrow.clockwise"
onPress={() => {
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
@@ -600,26 +801,30 @@ export function ThreadFileScreen() {
fileQuery.refresh();
}}
/>
</Stack.Toolbar>
<FilePreviewHeader
activeMode={resolvedActiveMode}
showModeSelector={canPreview && !isImageFile}
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
projectName={projectName}
relativePath={relativePath}
onSetMode={(mode) => {
setModeOverride({ path: relativePath, mode });
}}
/>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
/>
</NativeHeaderToolbar>
<AdaptiveInspectorLayout
renderInspector={fileInspector.supported ? () => renderInspector(0) : undefined}
>
<FilePreviewHeader
activeMode={resolvedActiveMode}
showModeSelector={canPreview && !isImageFile}
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
projectName={projectName}
relativePath={relativePath}
onSetMode={(mode) => {
setModeOverride({ path: relativePath, mode });
}}
/>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
/>
</AdaptiveInspectorLayout>
</View>
</ReviewHighlighterProvider>
);
@@ -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 "../../lib/native-scroll-edge-effect";
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>
);
}
+182 -199
View File
@@ -4,59 +4,31 @@ import type {
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";
NativeHeaderToolbar,
NativeStackScreenOptions,
} from "../../navigation/native-stack-header";
import { useCallback, useRef } from "react";
import { Platform } from "react-native";
import type { SearchBarCommands } from "react-native-screens";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { useThemeColor } from "../../lib/useThemeColor";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
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 +44,185 @@ 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,
headerLargeTitle: false,
headerStyle: { backgroundColor: "transparent" },
headerTintColor: iconColor,
headerTitle: "",
headerSearchBarOptions: {
placeholder: "Search threads",
hideNavigationBar: false,
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
allowToolbarIntegration: true,
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
headerBackVisible: false,
headerBackTitle: "",
headerTitle: "Threads",
headerTitleStyle: {
fontSize: 18,
fontWeight: "800",
},
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
unstable_headerRightItems:
Platform.OS === "ios"
? () => [
{
accessibilityLabel: "Open settings",
glassEffect: false,
icon: { name: "ellipsis", type: "sfSymbol" } as const,
identifier: "home-settings",
label: "",
onPress: props.onOpenSettings,
sharesBackground: false,
type: "button",
variant: "plain",
},
]
: 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>
)}
</>
);
}
+265 -313
View File
@@ -7,13 +7,17 @@ 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 { useCallback, useMemo, useRef, useState, type ComponentProps } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
Easing,
LinearTransition,
@@ -31,12 +35,11 @@ import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "../threads/threadPresentation";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "./thread-swipe-actions";
import { ThreadSwipeable } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -45,13 +48,21 @@ interface HomeScreenProps {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
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;
@@ -62,19 +73,20 @@ interface HomeScreenProps {
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
switch (thread.session?.status) {
case "running":
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
return { bg: "rgba(249,115,22,0.22)", fg: "#ff9f0a" };
case "ready":
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
return { bg: "rgba(48,209,88,0.22)", fg: "#30d158" };
case "starting":
return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
return { bg: "rgba(10,132,255,0.22)", fg: "#0a84ff" };
case "error":
return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
return { bg: "rgba(255,69,58,0.22)", fg: "#ff453a" };
default:
return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
return { bg: "rgba(142,142,147,0.22)", fg: "#8e8e93" };
}
}
const COLLAPSED_THREAD_LIMIT = 6;
const HOME_COMPACT_HEADER_THRESHOLD = 48;
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
function threadRowExit(values: ExitAnimationsValues) {
@@ -178,7 +190,7 @@ function ProjectGroupLabel(props: {
const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
return (
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<View className="flex-row items-center gap-2.5 px-5 pb-2 pt-5">
<ProjectFavicon
environmentId={props.project.environmentId}
size={18}
@@ -186,7 +198,7 @@ function ProjectGroupLabel(props: {
workspaceRoot={props.project.workspaceRoot}
/>
<Text
className="flex-1 text-xs font-t3-medium uppercase text-foreground-muted"
className="flex-1 text-xs font-t3-bold text-foreground-muted"
style={{ letterSpacing: 0.5 }}
numberOfLines={1}
>
@@ -207,6 +219,10 @@ function ProjectGroupLabel(props: {
);
}
function HomeTopContentSpacer(props: { readonly topInset: number }) {
return <View style={{ height: props.topInset + 78 }} />;
}
/* ─── Thread row ─────────────────────────────────────────────────────── */
function ThreadRow(props: {
@@ -217,15 +233,15 @@ function ThreadRow(props: {
readonly onDelete: () => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
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 screenColor = useThemeColor("--color-screen");
const { bg, fg } = statusColors(props.thread);
const tone = threadStatusTone(props.thread);
const timestamp = relativeTime(
@@ -235,213 +251,128 @@ function ThreadRow(props: {
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);
}
<ThreadSwipeable
backgroundColor={screenColor}
fullSwipeWidth={windowWidth - 32}
onDelete={props.onDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={{
accessibilityLabel: `Archive ${props.thread.title}`,
icon: "archivebox",
label: "Archive",
onPress: props.onArchive,
}}
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}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={props.thread.title}
>
<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,
{(close) => (
<Pressable
accessibilityHint="Swipe left for archive and delete actions"
accessibilityLabel={props.thread.title}
accessibilityRole="button"
className="bg-screen"
onPress={() => {
close();
props.onPress();
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
<View
style={{
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 2,
flexDirection: "row",
paddingLeft: 20,
paddingRight: 18,
paddingVertical: 11,
gap: 12,
minHeight: 78,
}}
>
<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
style={{
width: 46,
height: 46,
borderRadius: 23,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 1,
}}
>
<SymbolView name="arrow.triangle.branch" size={20} tintColor={fg} type="monochrome" />
</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"
/>
<View
style={{
flex: 1,
gap: 3,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
paddingBottom: 11,
}}
>
<View className="flex-row items-center justify-between gap-2">
<Text
className="text-2xs text-foreground-tertiary"
className="flex-1 text-lg font-t3-bold leading-[22px] text-foreground"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitleParts.join(" · ")}
{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-base text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
<SymbolView
name="chevron.right"
size={13}
tintColor={iconSubtleColor}
type="monochrome"
/>
</View>
</View>
) : null}
{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-sm text-foreground-muted" numberOfLines={1}>
{subtitleParts.join(" · ")}
</Text>
</View>
) : null}
</View>
</View>
</View>
</Pressable>
</ReanimatedSwipeable>
</Pressable>
)}
</ThreadSwipeable>
);
}
/* ─── 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 openSwipeableRef = useRef<SwipeableMethods | null>(null);
const insets = useSafeAreaInsets();
const { height: windowHeight } = useWindowDimensions();
const accentColor = useThemeColor("--color-icon-muted");
const toggleExpanded = useCallback((key: string) => {
setExpandedProjects((prev) => {
const next = new Set(prev);
@@ -463,7 +394,6 @@ export function HomeScreen(props: HomeScreenProps) {
openSwipeableRef.current = null;
}
}, []);
const projectGroups = useMemo(
() =>
buildHomeThreadGroups({
@@ -495,126 +425,148 @@ export function HomeScreen(props: HomeScreenProps) {
: (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,
});
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,
}}
>
{!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 ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : !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);
const listContent = (
<>
{Platform.OS === "ios" ? null : <HomeTopContentSpacer topInset={insets.top} />}
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}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View style={{ paddingBottom: 16 }}>
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</View>
{!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 ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : !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);
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="bg-screen">
{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>
);
})
)}
</>
);
const scrollView = (
<ScrollView
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
scrollEventThrottle={16}
className="flex-1 bg-screen"
contentContainerStyle={{
minHeight: windowHeight + HOME_COMPACT_HEADER_THRESHOLD + insets.top,
paddingHorizontal: 0,
paddingTop: Platform.OS === "ios" ? 18 : 0,
paddingBottom: Platform.OS === "ios" ? Math.max(insets.bottom, 24) + 132 : 24,
gap: 0,
}}
scrollIndicatorInsets={
Platform.OS === "ios"
? {
bottom: Math.max(insets.bottom, 16) + 92,
top: insets.top + 72,
}
: undefined
}
>
{listContent}
</ScrollView>
);
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 (
<>
{scrollView}
{connectionStatus}
</>
);
}
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vite-plus/test";
import type { WorkspaceState } from "../../state/workspaceModel";
import {
shouldShowWorkspaceConnectionStatus,
workspaceConnectionStatusLabel,
} from "./workspace-connection-status";
function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState {
return {
isLoadingConnections: false,
hasConnections: true,
hasLoadedShellSnapshot: true,
hasPendingShellSnapshot: false,
hasReadyEnvironment: true,
hasConnectingEnvironment: false,
connectingEnvironments: [],
connectionState: "connected",
connectionError: null,
shellSnapshotError: null,
latestCachedSnapshotReceivedAt: null,
networkStatus: "online",
...overrides,
};
}
describe("workspace connection status", () => {
it("stays hidden while a ready environment is connected", () => {
expect(shouldShowWorkspaceConnectionStatus(workspaceState())).toBe(false);
});
it("surfaces offline snapshots", () => {
const state = workspaceState({ networkStatus: "offline", hasReadyEnvironment: false });
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
expect(workspaceConnectionStatusLabel(state)).toBe("You are offline");
});
it("names the environment while reconnecting", () => {
const state = workspaceState({
hasConnectingEnvironment: true,
hasReadyEnvironment: false,
connectingEnvironments: [
{
environmentId: "environment-1" as never,
environmentLabel: "Julius’s Mac mini",
displayUrl: "",
isRelayManaged: false,
connectionState: "reconnecting",
connectionError: null,
connectionErrorTraceId: null,
},
],
});
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
expect(workspaceConnectionStatusLabel(state)).toBe("Reconnecting to Julius’s Mac mini");
});
it("surfaces connection errors before the generic disconnected fallback", () => {
const state = workspaceState({
connectionError: "Could not reach Julius’s Mac mini",
hasLoadedShellSnapshot: false,
hasReadyEnvironment: false,
});
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
expect(workspaceConnectionStatusLabel(state)).toBe("Could not reach Julius’s Mac mini");
});
});
@@ -0,0 +1,53 @@
import { SymbolView } from "expo-symbols";
import { ActivityIndicator, Pressable } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import type { WorkspaceState } from "../../state/workspaceModel";
import { workspaceConnectionStatusLabel } from "./workspace-connection-status";
export function WorkspaceConnectionStatus(props: {
readonly state: WorkspaceState;
readonly onPress: () => void;
readonly variant?: "floating" | "sidebar";
}) {
const iconColor = useThemeColor("--color-icon-muted");
const isReconnecting = props.state.connectingEnvironments.length > 0;
const variant = props.variant ?? "floating";
return (
<Pressable
accessibilityHint="Opens environment settings"
accessibilityLabel={workspaceConnectionStatusLabel(props.state)}
accessibilityRole="button"
onPress={props.onPress}
className={
variant === "sidebar"
? "mx-3 flex-row items-center gap-2 rounded-xl bg-subtle px-3 py-2.5"
: "flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
}
style={
variant === "floating"
? {
shadowColor: "#000",
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.12,
shadowRadius: 24,
}
: undefined
}
>
{isReconnecting ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
)}
<Text className="min-w-0 flex-1 text-sm font-t3-bold text-foreground" numberOfLines={1}>
{workspaceConnectionStatusLabel(props.state)}
</Text>
{variant === "sidebar" ? (
<SymbolView name="chevron.right" size={11} tintColor={iconColor} type="monochrome" />
) : null}
</Pressable>
);
}
@@ -0,0 +1,120 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import type { HomeProjectSortOrder } from "./homeThreadList";
import {
PROJECT_GROUPING_OPTIONS,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
} from "./home-list-options";
export interface HomeListFilterMenuEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
}
type HomeListFilterMenuAction = {
readonly type: "action";
readonly title: string;
readonly subtitle?: string;
readonly state?: "on" | "off";
readonly onPress: () => void;
};
type HomeListFilterMenuSubmenu = {
readonly type: "submenu";
readonly title: string;
readonly items: HomeListFilterMenuAction[];
};
export interface HomeListFilterMenu {
readonly title: string;
readonly items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu>;
}
export function buildHomeListFilterMenu(props: {
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
readonly onOpenSettings?: () => void;
}): HomeListFilterMenu {
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
if (props.onOpenSettings) {
items.push({
type: "action",
title: "Settings",
onPress: props.onOpenSettings,
});
}
items.push(
{
type: "submenu",
title: "Environment",
items: [
{
type: "action",
title: "All environments",
subtitle: "Show threads from every environment",
state: props.selectedEnvironmentId === null ? "on" : "off",
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",
title: "Sort projects",
items: PROJECT_SORT_OPTIONS.map((option) => ({
type: "action",
title: option.label,
state: props.projectSortOrder === option.value ? "on" : "off",
onPress: () => props.onProjectSortOrderChange(option.value),
})),
},
{
type: "submenu",
title: "Sort threads",
items: THREAD_SORT_OPTIONS.map((option) => ({
type: "action",
title: option.label,
state: props.threadSortOrder === option.value ? "on" : "off",
onPress: () => props.onThreadSortOrderChange(option.value),
})),
},
{
type: "submenu",
title: "Group projects",
items: PROJECT_GROUPING_OPTIONS.map((option) => ({
type: "action",
title: option.label,
subtitle: option.subtitle,
state: props.projectGroupingMode === option.value ? "on" : "off",
onPress: () => props.onProjectGroupingModeChange(option.value),
})),
},
);
return {
title: "Thread list options",
items,
};
}
@@ -0,0 +1,31 @@
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { hasCustomHomeListOptions, type HomeListOptions } from "./home-list-options";
const defaults: 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,
};
describe("home list options", () => {
it("recognizes default options", () => {
expect(hasCustomHomeListOptions(defaults)).toBe(false);
});
it("marks environment filters and grouping changes as customized", () => {
expect(
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
).toBe(true);
expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true);
});
});
@@ -0,0 +1,144 @@
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 {
createContext,
createElement,
useCallback,
useContext,
useMemo,
useState,
type PropsWithChildren,
type Dispatch,
type SetStateAction,
} from "react";
import type { HomeProjectSortOrder } from "./homeThreadList";
export interface HomeListOptions {
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
export const THREAD_SORT_OPTIONS: ReadonlyArray<{
readonly value: SidebarThreadSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
export 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",
},
];
function defaultHomeListOptions(): HomeListOptions {
return {
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,
};
}
interface HomeListOptionsContextValue {
readonly options: HomeListOptions;
readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
}
const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>(null);
/** Keeps list preferences stable while the app moves between compact and split shells. */
export function HomeListOptionsProvider({ children }: PropsWithChildren) {
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
const value = useMemo(() => ({ options, setOptions }), [options]);
return createElement(HomeListOptionsContext, { value }, children);
}
export function hasCustomHomeListOptions(options: HomeListOptions): boolean {
const defaultProjectSortOrder =
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER;
return (
options.selectedEnvironmentId !== null ||
options.projectSortOrder !== defaultProjectSortOrder ||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
);
}
export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<EnvironmentId>) {
const shared = useContext(HomeListOptionsContext);
const [localOptions, setLocalOptions] = useState<HomeListOptions>(defaultHomeListOptions);
const options = shared?.options ?? localOptions;
const setOptions = shared?.setOptions ?? setLocalOptions;
const selectedEnvironmentId =
options.selectedEnvironmentId !== null &&
availableEnvironmentIds.has(options.selectedEnvironmentId)
? options.selectedEnvironmentId
: null;
const resolvedOptions =
selectedEnvironmentId === options.selectedEnvironmentId
? options
: { ...options, selectedEnvironmentId };
const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
}, []);
const setProjectSortOrder = useCallback((value: HomeProjectSortOrder) => {
setOptions((current) => ({ ...current, projectSortOrder: value }));
}, []);
const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => {
setOptions((current) => ({ ...current, threadSortOrder: value }));
}, []);
const setProjectGroupingMode = useCallback((value: SidebarProjectGroupingMode) => {
setOptions((current) => ({ ...current, projectGroupingMode: value }));
}, []);
return {
options: resolvedOptions,
setSelectedEnvironmentId,
setProjectSortOrder,
setThreadSortOrder,
setProjectGroupingMode,
} as const;
}
@@ -1,8 +1,11 @@
import { SymbolView } from "expo-symbols";
import type { ComponentProps } from "react";
import type { ColorValue } from "react-native";
import * as Haptics from "expo-haptics";
import { useCallback, useRef, type ComponentProps, type ReactNode } from "react";
import type { ColorValue, StyleProp, ViewStyle } from "react-native";
import { Pressable, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
Extrapolation,
interpolate,
@@ -26,6 +29,100 @@ export const THREAD_SWIPE_SPRING = {
stiffness: 330,
};
interface ThreadSwipePrimaryAction {
readonly accessibilityLabel: string;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly onPress: () => void;
}
export function ThreadSwipeable(props: {
readonly backgroundColor: ColorValue;
readonly children: (close: () => void) => ReactNode;
readonly containerStyle?: StyleProp<ViewStyle>;
readonly enableTrackpadSwipe?: boolean;
readonly fullSwipeWidth: number;
readonly onDelete: () => void;
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
readonly primaryAction: ThreadSwipePrimaryAction;
readonly simultaneousWithExternalGesture?: ComponentProps<
typeof ReanimatedSwipeable
>["simultaneousWithExternalGesture"];
readonly threadTitle: string;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58);
const close = useCallback(() => swipeableRef.current?.close(), []);
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: props.backgroundColor }}
containerStyle={[{ backgroundColor: props.backgroundColor }, props.containerStyle]}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture={props.enableTrackpadSwipe ?? true}
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={props.backgroundColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
...props.primaryAction,
onPress: () => {
methods.close();
props.primaryAction.onPress();
},
}}
swipeableMethods={methods}
threadTitle={props.threadTitle}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
simultaneousWithExternalGesture={props.simultaneousWithExternalGesture}
>
{props.children(close)}
</ReanimatedSwipeable>
);
}
function SwipeActionButton(props: {
readonly accessibilityLabel: string;
readonly backgroundColor: string;
@@ -179,12 +276,7 @@ export function ThreadSwipeActions(props: {
readonly fullSwipeThreshold: number;
readonly onDelete: () => void;
readonly onFullSwipeArmedChange: (armed: boolean) => void;
readonly primaryAction: {
readonly accessibilityLabel: string;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly onPress: () => void;
};
readonly primaryAction: ThreadSwipePrimaryAction;
readonly swipeableMethods: SwipeableMethods;
readonly threadTitle: string;
readonly translation: SharedValue<number>;
@@ -0,0 +1,22 @@
import type { WorkspaceState } from "../../state/workspaceModel";
export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean {
return (
state.networkStatus === "offline" ||
state.connectionError !== null ||
state.hasConnectingEnvironment ||
(state.hasLoadedShellSnapshot && !state.hasReadyEnvironment)
);
}
export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
if (state.networkStatus === "offline") return "You are offline";
if (state.connectingEnvironments.length === 1) {
return `Reconnecting to ${state.connectingEnvironments[0]!.environmentLabel}`;
}
if (state.connectingEnvironments.length > 1) {
return `Reconnecting ${state.connectingEnvironments.length} environments`;
}
if (state.connectionError !== null) return state.connectionError;
return "Not connected";
}
@@ -0,0 +1,74 @@
import { useCurrentPathname, useAppNavigation } from "../../navigation/native-stack-header";
import { useCallback, useMemo, useSyncExternalStore, type PropsWithChildren } from "react";
import {
buildThreadFilesNavigation,
buildThreadReviewNavigation,
buildThreadTerminalNavigation,
dismissRoute,
newTaskNavigation,
} from "../../lib/routes";
import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
import {
dispatchHardwareKeyboardCommand,
getHardwareKeyboardCommandRegistrationVersion,
getRegisteredHardwareKeyboardCommands,
parseActiveThreadPath,
subscribeToHardwareKeyboardCommandRegistrations,
type HardwareKeyboardCommand,
} from "./hardwareKeyboardCommands";
export function HardwareKeyboardCommandProvider({ children }: PropsWithChildren) {
const pathname = useCurrentPathname();
const navigation = useAppNavigation();
const registrationVersion = useSyncExternalStore(
subscribeToHardwareKeyboardCommandRegistrations,
getHardwareKeyboardCommandRegistrationVersion,
getHardwareKeyboardCommandRegistrationVersion,
);
const enabledCommands = useMemo(() => {
const commands = new Set<HardwareKeyboardCommand>(getRegisteredHardwareKeyboardCommands());
commands.add("newTask");
if (pathname !== "/" || navigation.canGoBack()) commands.add("back");
if (parseActiveThreadPath(pathname)) {
commands.add("files");
commands.add("terminal");
commands.add("review");
}
return [...commands];
}, [pathname, registrationVersion, navigation]);
const onCommand = useCallback(
(command: HardwareKeyboardCommand) => {
if (dispatchHardwareKeyboardCommand(command)) return;
if (command === "newTask") {
navigation.push(newTaskNavigation());
return;
}
if (command === "back") {
dismissRoute(navigation);
return;
}
const thread = parseActiveThreadPath(pathname);
if (!thread) return;
if (command === "files" && !/\/files(?:\/|$)/.test(pathname)) {
navigation.push(buildThreadFilesNavigation(thread));
}
if (command === "terminal" && !/\/terminal(?:\/|$)/.test(pathname)) {
navigation.push(buildThreadTerminalNavigation(thread));
}
if (command === "review" && !/\/review(?:\/|$)/.test(pathname)) {
navigation.push(buildThreadReviewNavigation(thread));
}
},
[pathname, navigation],
);
return (
<T3KeyboardCommands enabledCommands={enabledCommands} onCommand={onCommand}>
{children}
</T3KeyboardCommands>
);
}
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vite-plus/test";
import { parseActiveThreadPath } from "./hardwareKeyboardCommands";
describe("parseActiveThreadPath", () => {
it("extracts the active thread from thread subroutes", () => {
expect(parseActiveThreadPath("/threads/environment-1/thread-1/files/src/index.ts")).toEqual({
environmentId: "environment-1",
threadId: "thread-1",
});
});
it("decodes route components", () => {
expect(parseActiveThreadPath("/threads/local%20machine/thread%2Fone/review")).toEqual({
environmentId: "local machine",
threadId: "thread/one",
});
});
it("ignores non-thread routes", () => {
expect(parseActiveThreadPath("/settings")).toBeNull();
expect(parseActiveThreadPath("/threads/environment-only")).toBeNull();
});
it("ignores malformed encoded route components", () => {
expect(parseActiveThreadPath("/threads/%E0%A4%A/thread-1")).toBeNull();
});
});
@@ -0,0 +1,78 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useEffect } from "react";
export type HardwareKeyboardCommand =
| "newTask"
| "focusSearch"
| "back"
| "files"
| "terminal"
| "review"
| "toggleSidebar";
type CommandHandler = () => boolean | void;
const handlers = new Map<HardwareKeyboardCommand, Set<CommandHandler>>();
const registrationListeners = new Set<() => void>();
let registrationVersion = 0;
/**
* Registers a context-specific hardware-keyboard action. The most recently mounted handler gets
* the first chance to consume the command, allowing focused screens to override app defaults.
*/
export function useHardwareKeyboardCommand(
command: HardwareKeyboardCommand,
handler: CommandHandler,
): void {
useEffect(() => {
const commandHandlers = handlers.get(command) ?? new Set<CommandHandler>();
commandHandlers.add(handler);
handlers.set(command, commandHandlers);
registrationVersion += 1;
registrationListeners.forEach((listener) => listener());
return () => {
commandHandlers.delete(handler);
if (commandHandlers.size === 0) handlers.delete(command);
registrationVersion += 1;
registrationListeners.forEach((listener) => listener());
};
}, [command, handler]);
}
export function getRegisteredHardwareKeyboardCommands(): ReadonlySet<HardwareKeyboardCommand> {
return new Set(handlers.keys());
}
export function getHardwareKeyboardCommandRegistrationVersion(): number {
return registrationVersion;
}
export function subscribeToHardwareKeyboardCommandRegistrations(listener: () => void): () => void {
registrationListeners.add(listener);
return () => registrationListeners.delete(listener);
}
export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
const commandHandlers = handlers.get(command);
if (!commandHandlers) return false;
for (const handler of [...commandHandlers].toReversed()) {
if (handler() !== false) return true;
}
return false;
}
export function parseActiveThreadPath(pathname: string): {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
} | null {
const match = /^\/threads\/([^/]+)\/([^/]+)(?:\/|$)/.exec(pathname);
if (!match?.[1] || !match[2]) return null;
try {
return {
environmentId: EnvironmentId.make(decodeURIComponent(match[1])),
threadId: ThreadId.make(decodeURIComponent(match[2])),
};
} catch {
return null;
}
}
@@ -0,0 +1,364 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import {
useFocusEffect,
useCurrentRouteParams,
useCurrentPathname,
useAppNavigation,
} from "../../navigation/native-stack-header";
import {
createContext,
use,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { useWindowDimensions, View } from "react-native";
import Animated, {
Easing,
ReduceMotion,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import {
deriveFileInspectorPaneLayout,
deriveLayout,
deriveWorkspacePaneLayout,
type FileInspectorPaneLayout,
type Layout,
type WorkspaceAuxiliaryPaneRole,
type WorkspacePaneLayout,
} from "../../lib/layout";
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
import {
buildThreadFilesNavigation,
newTaskNavigation,
settingsNavigation,
threadNavigation,
} from "../../lib/routes";
import { scopedThreadKey } from "../../lib/scopedEntities";
import {
parseActiveThreadPath,
useHardwareKeyboardCommand,
} from "../keyboard/hardwareKeyboardCommands";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
interface AdaptiveWorkspaceContextValue {
readonly layout: Layout;
readonly panes: WorkspacePaneLayout;
readonly fileInspector: FileInspectorPaneLayout;
readonly primarySidebarSearchQuery: string;
readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;
readonly setPrimarySidebarSearchQuery: (query: string) => void;
readonly showAuxiliaryPane: (role: WorkspaceAuxiliaryPaneRole) => void;
readonly toggleAuxiliaryPane: () => void;
readonly togglePrimarySidebar: () => void;
readonly setAuxiliaryPaneWidth: (width: number) => void;
}
const compactLayout = deriveLayout({ width: 0, height: 0 });
const compactPanes = deriveWorkspacePaneLayout({
layout: compactLayout,
viewportWidth: 0,
primarySidebarPreferredVisible: true,
auxiliaryPanePreferredVisible: true,
});
const compactFileInspector = deriveFileInspectorPaneLayout({
layout: compactLayout,
viewportWidth: 0,
});
const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextValue>({
layout: compactLayout,
panes: compactPanes,
fileInspector: compactFileInspector,
primarySidebarSearchQuery: "",
activateAuxiliaryPaneRole: () => () => undefined,
setPrimarySidebarSearchQuery: () => undefined,
showAuxiliaryPane: () => undefined,
toggleAuxiliaryPane: () => undefined,
togglePrimarySidebar: () => undefined,
setAuxiliaryPaneWidth: () => undefined,
});
function firstRouteParam(value: string | string[] | undefined): string | null {
return Array.isArray(value) ? (value[0] ?? null) : (value ?? null);
}
export function useAdaptiveWorkspaceLayout(): AdaptiveWorkspaceContextValue {
return use(AdaptiveWorkspaceContext);
}
export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) {
const { activateAuxiliaryPaneRole } = useAdaptiveWorkspaceLayout();
useFocusEffect(
useCallback(() => activateAuxiliaryPaneRole(role), [activateAuxiliaryPaneRole, role]),
);
}
export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode }) {
const { width, height } = useWindowDimensions();
const pathname = useCurrentPathname();
const navigation = useAppNavigation();
const activeRoleOwner = useRef<symbol | null>(null);
const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true);
const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true);
const [supplementaryPanePreferredWidth, setSupplementaryPanePreferredWidth] = useState<
number | null
>(null);
const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true);
const [fileInspectorPreferredWidth, setFileInspectorPreferredWidth] = useState<number | null>(
null,
);
const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");
const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =
useState<WorkspaceAuxiliaryPaneRole | null>(null);
const params = useCurrentRouteParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
const baseLayout = useMemo(() => deriveLayout({ width, height }), [height, width]);
const layout = baseLayout;
const fileInspector = useMemo(
() =>
deriveFileInspectorPaneLayout({
layout,
viewportWidth: width,
preferredWidth: fileInspectorPreferredWidth ?? undefined,
reservedLeadingWidth:
layout.usesSplitView && primarySidebarPreferredVisible ? (layout.listPaneWidth ?? 0) : 0,
}),
[fileInspectorPreferredWidth, layout, primarySidebarPreferredVisible, width],
);
const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =
focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");
const auxiliaryPanePreferredVisible =
auxiliaryPaneRole === "inspector"
? fileInspectorPreferredVisible
: supplementaryPanePreferredVisible;
const auxiliaryPanePreferredWidth =
auxiliaryPaneRole === "inspector"
? fileInspectorPreferredWidth
: supplementaryPanePreferredWidth;
const panes = useMemo(
() =>
deriveWorkspacePaneLayout({
layout,
viewportWidth: width,
primarySidebarPreferredVisible,
auxiliaryPanePreferredVisible,
auxiliaryPaneRole,
auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
}),
[
auxiliaryPanePreferredVisible,
auxiliaryPaneRole,
auxiliaryPanePreferredWidth,
layout,
primarySidebarPreferredVisible,
width,
],
);
const environmentId = firstRouteParam(params.environmentId);
const threadId = firstRouteParam(params.threadId);
const selectedThreadKey = useMemo(() => {
if (environmentId === null || threadId === null) {
return null;
}
try {
return scopedThreadKey(EnvironmentId.make(environmentId), ThreadId.make(threadId));
} catch {
return null;
}
}, [environmentId, threadId]);
const activateAuxiliaryPaneRole = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
const owner = Symbol(role);
activeRoleOwner.current = owner;
setFocusedAuxiliaryPaneRole(role);
return () => {
if (activeRoleOwner.current !== owner) {
return;
}
activeRoleOwner.current = null;
setFocusedAuxiliaryPaneRole(null);
};
}, []);
const togglePrimarySidebar = useCallback(() => {
if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) {
setFileInspectorPreferredVisible(false);
setPrimarySidebarPreferredVisible(true);
return;
}
setPrimarySidebarPreferredVisible((current) => !current);
}, [panes.primarySidebarSuppressedByAuxiliary, panes.primarySidebarVisible]);
const revealPrimarySidebar = useCallback(() => {
if (panes.primarySidebarSuppressedByAuxiliary) {
setFileInspectorPreferredVisible(false);
}
setPrimarySidebarPreferredVisible(true);
}, [panes.primarySidebarSuppressedByAuxiliary]);
const handleToggleSidebarCommand = useCallback(() => {
togglePrimarySidebar();
return true;
}, [togglePrimarySidebar]);
useHardwareKeyboardCommand("toggleSidebar", handleToggleSidebarCommand);
const showAuxiliaryPane = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
if (role === "inspector") {
setFocusedAuxiliaryPaneRole("inspector");
setFileInspectorPreferredVisible(true);
return;
}
setFocusedAuxiliaryPaneRole("supplementary");
setSupplementaryPanePreferredVisible(true);
}, []);
const handleOpenFilesCommand = useCallback(() => {
const activeThread = parseActiveThreadPath(pathname);
if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {
return false;
}
showAuxiliaryPane("inspector");
if (/\/files(?:\/|$)/.test(pathname)) {
return true;
}
navigation.replace(buildThreadFilesNavigation(activeThread));
return true;
}, [fileInspector.supported, layout.usesSplitView, pathname, navigation, showAuxiliaryPane]);
useHardwareKeyboardCommand("files", handleOpenFilesCommand);
const toggleAuxiliaryPane = useCallback(() => {
if (auxiliaryPaneRole === "inspector") {
setFileInspectorPreferredVisible((current) => !current);
return;
}
setSupplementaryPanePreferredVisible((current) => !current);
}, [auxiliaryPaneRole]);
const setAuxiliaryPaneWidth = useCallback(
(nextWidth: number) => {
if (auxiliaryPaneRole === "inspector") {
setFileInspectorPreferredWidth(nextWidth);
return;
}
setSupplementaryPanePreferredWidth(nextWidth);
},
[auxiliaryPaneRole],
);
const contextValue = useMemo(
() => ({
layout,
panes,
fileInspector,
primarySidebarSearchQuery,
activateAuxiliaryPaneRole,
setPrimarySidebarSearchQuery,
showAuxiliaryPane,
toggleAuxiliaryPane,
togglePrimarySidebar,
setAuxiliaryPaneWidth,
}),
[
activateAuxiliaryPaneRole,
fileInspector,
layout,
panes,
primarySidebarSearchQuery,
showAuxiliaryPane,
setPrimarySidebarSearchQuery,
setAuxiliaryPaneWidth,
toggleAuxiliaryPane,
togglePrimarySidebar,
],
);
const handleOpenSettings = useCallback(() => {
navigation.push(settingsNavigation());
}, [navigation]);
const handleStartNewTask = useCallback(() => {
navigation.push(newTaskNavigation());
}, [navigation]);
const renderedSidebarWidth = useSharedValue(
panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0,
);
useEffect(() => {
const targetWidth = panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0;
renderedSidebarWidth.value = withTiming(targetWidth, {
duration: panes.primarySidebarVisible ? 220 : 160,
easing: panes.primarySidebarVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
reduceMotion: ReduceMotion.System,
});
}, [layout.listPaneWidth, panes.primarySidebarVisible, renderedSidebarWidth]);
const sidebarAnimatedStyle = useAnimatedStyle(() => ({
opacity: Math.min(1, renderedSidebarWidth.value / 80),
width: renderedSidebarWidth.value,
}));
const handleSelectThread = useCallback(
(thread: EnvironmentThreadShell) => {
const destination = threadNavigation(thread);
const navigationAction = resolveThreadSelectionNavigationAction({
usesSplitView: layout.usesSplitView,
pathname,
});
if (navigationAction === "set-params") {
const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);
if (nextThreadKey === selectedThreadKey) {
return;
}
setFileInspectorPreferredVisible(false);
navigation.setParams({
environmentId: String(thread.environmentId),
threadId: String(thread.id),
});
return;
}
if (navigationAction === "replace") {
setFileInspectorPreferredVisible(false);
navigation.replace(destination);
return;
}
navigation.push(destination);
},
[layout.usesSplitView, pathname, navigation, selectedThreadKey],
);
return (
<HomeListOptionsProvider>
<AdaptiveWorkspaceContext.Provider value={contextValue}>
<View testID="adaptive-workspace-layout" style={{ flex: 1, flexDirection: "row" }}>
{layout.usesSplitView && layout.listPaneWidth !== null ? (
<Animated.View
accessibilityElementsHidden={!panes.primarySidebarVisible}
collapsable={false}
importantForAccessibility={
panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
}
pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
style={[{ alignSelf: "stretch", overflow: "hidden" }, sidebarAnimatedStyle]}
>
<ThreadNavigationSidebar
width={layout.listPaneWidth}
visible={panes.primarySidebarVisible}
onRequestVisibility={revealPrimarySidebar}
selectedThreadKey={selectedThreadKey}
onOpenSettings={handleOpenSettings}
onSelectThread={handleSelectThread}
onSearchQueryChange={setPrimarySidebarSearchQuery}
onStartNewTask={handleStartNewTask}
searchQuery={primarySidebarSearchQuery}
/>
</Animated.View>
) : null}
<View collapsable={false} style={{ flex: 1 }}>
{props.children}
</View>
</View>
</AdaptiveWorkspaceContext.Provider>
</HomeListOptionsProvider>
);
}
@@ -0,0 +1,21 @@
import { SymbolView } from "expo-symbols";
import { View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
export function WorkspaceEmptyDetail() {
const iconColor = useThemeColor("--color-icon-subtle");
return (
<View className="flex-1 items-center justify-center bg-screen px-10">
<View className="max-w-[360px] items-center gap-3">
<SymbolView name="sidebar.left" size={34} tintColor={iconColor} type="hierarchical" />
<Text className="text-center text-xl font-t3-bold">Select a thread</Text>
<Text className="text-center text-base text-foreground-muted">
Choose a thread from the sidebar or start a new task.
</Text>
</View>
</View>
);
}
@@ -0,0 +1,103 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { View } from "react-native";
import Animated, {
Easing,
ReduceMotion,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { constrainAuxiliaryPaneWidth } from "../../lib/layout";
import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
import { WorkspacePaneDivider } from "./workspace-pane-divider";
export function AdaptiveInspectorLayout(props: {
readonly children: ReactNode;
readonly renderInspector?: () => ReactNode;
}) {
const { panes, setAuxiliaryPaneWidth } = useAdaptiveWorkspaceLayout();
const inspectorWidth = panes.auxiliaryPaneWidth;
const inspectorSupported = props.renderInspector !== undefined && inspectorWidth !== null;
const inspectorVisible = inspectorSupported && panes.auxiliaryPaneVisible;
const resizeStartWidth = useRef(0);
const [resizing, setResizing] = useState(false);
// A file-to-file replace remounts the route. Initialize an already-visible
// inspector at its final position so route replacement never replays an
// entering transition. Only visibility and explicit resizing change it.
const inspectorProgress = useSharedValue(inspectorVisible ? 1 : 0);
const renderedInspectorWidth = useSharedValue(inspectorVisible ? (inspectorWidth ?? 0) : 0);
useEffect(() => {
inspectorProgress.value = withTiming(inspectorVisible ? 1 : 0, {
duration: inspectorVisible ? 220 : 160,
easing: inspectorVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
reduceMotion: ReduceMotion.System,
});
const targetWidth = inspectorVisible ? (inspectorWidth ?? 0) : 0;
renderedInspectorWidth.value = resizing
? targetWidth
: withTiming(targetWidth, {
duration: inspectorVisible ? 220 : 160,
easing: inspectorVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
reduceMotion: ReduceMotion.System,
});
}, [inspectorProgress, inspectorVisible, inspectorWidth, renderedInspectorWidth, resizing]);
const inspectorStyle = useAnimatedStyle(
() => ({
opacity: inspectorProgress.value,
transform: [{ translateX: (1 - inspectorProgress.value) * 24 }],
width: renderedInspectorWidth.value,
}),
[],
);
const beginResize = useCallback(() => {
resizeStartWidth.current = inspectorWidth ?? 0;
setResizing(true);
}, [inspectorWidth]);
const resizeBy = useCallback(
(delta: number) => {
setAuxiliaryPaneWidth(
constrainAuxiliaryPaneWidth({
preferredWidth: resizeStartWidth.current + delta,
availableWidth: panes.contentPaneWidth,
}),
);
},
[panes.contentPaneWidth, setAuxiliaryPaneWidth],
);
const endResize = useCallback(() => {
setResizing(false);
}, []);
return (
<View className="flex-1 flex-row">
<Animated.View collapsable={false} className="min-w-0 flex-1">
{props.children}
</Animated.View>
{inspectorVisible ? (
<WorkspacePaneDivider
accessibilityLabel="Resize detail pane"
currentWidth={inspectorWidth ?? 0}
resizeDirection={-1}
onResizeStart={beginResize}
onResizeBy={resizeBy}
onResizeEnd={endResize}
/>
) : null}
{inspectorSupported ? (
<Animated.View
accessibilityElementsHidden={!inspectorVisible}
collapsable={false}
importantForAccessibility={inspectorVisible ? "auto" : "no-hide-descendants"}
pointerEvents={inspectorVisible ? "auto" : "none"}
style={[{ flexShrink: 0, overflow: "hidden" }, inspectorStyle]}
>
<View style={{ flex: 1, width: inspectorWidth }}>{props.renderInspector?.()}</View>
</Animated.View>
) : null}
</View>
);
}
@@ -0,0 +1,31 @@
type NativeGlassHeaderItem = {
readonly type: "button" | "menu";
readonly glassEffect?: boolean;
readonly sharesBackground?: boolean;
readonly variant?: "plain" | "done" | "prominent";
readonly width?: number;
};
/**
* iOS 26/27 Mail-style header controls need the native glass button
* configuration when they are not part of a larger toolbar. Keep this
* centralized so native-stack screens and plain react-native-screens demos
* don't drift apart.
*/
export function withNativeGlassHeaderItem<T extends NativeGlassHeaderItem>(
item: T,
options: {
readonly sharesBackground?: boolean;
readonly width?: number;
} = {},
): T {
return {
...item,
glassEffect: item.glassEffect ?? true,
sharesBackground: options.sharesBackground ?? item.sharesBackground ?? true,
variant: item.variant ?? "prominent",
...(options.width !== undefined || item.width !== undefined
? { width: options.width ?? item.width }
: {}),
} as T;
}
@@ -0,0 +1,25 @@
import type { HeaderBarButtonMailSearchToolbarItem } from "react-native-screens";
type NativeMailSearchToolbarInput = Omit<
HeaderBarButtonMailSearchToolbarItem,
"type" | "useFallbackSearchField"
>;
/**
* Builds the patched react-native-screens Mail-style bottom search toolbar.
*
* Keeping this behind an app-level helper makes the iOS-only RNS patch an
* explicit layout primitive instead of a per-screen object literal. Android can
* keep using platform-specific header/search primitives without depending on
* this helper.
*/
export function createNativeMailSearchToolbarItem(
input: NativeMailSearchToolbarInput,
): HeaderBarButtonMailSearchToolbarItem {
return {
placeholder: "Search",
...input,
type: "mailSearchToolbar",
useFallbackSearchField: true,
};
}
@@ -0,0 +1,116 @@
import { useCallback, useMemo, useRef, useState } from "react";
import {
Platform,
PlatformColor,
Pressable,
StyleSheet,
View,
type AccessibilityActionEvent,
} from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { runOnJS } from "react-native-reanimated";
const ACCESSIBILITY_RESIZE_STEP = 24;
interface WorkspacePaneDividerProps {
readonly accessibilityLabel: string;
readonly currentWidth: number;
/** 1 when dragging right grows the pane, -1 when dragging left grows it. */
readonly resizeDirection: 1 | -1;
readonly onResizeStart?: () => void;
readonly onResizeBy: (delta: number) => void;
readonly onResizeEnd?: () => void;
}
/** A forgiving divider target for touch, pointer, and VoiceOver users. */
export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
const latestProps = useRef(props);
latestProps.current = props;
const [hovered, setHovered] = useState(false);
const [dragging, setDragging] = useState(false);
const handleResizeStart = useCallback(() => {
setDragging(true);
latestProps.current.onResizeStart?.();
}, []);
const handleResize = useCallback((translationX: number) => {
latestProps.current.onResizeBy(translationX * latestProps.current.resizeDirection);
}, []);
const handleResizeEnd = useCallback(() => {
setDragging(false);
latestProps.current.onResizeEnd?.();
}, []);
const resizeGesture = useMemo(
() =>
Gesture.Pan()
.activeOffsetX([-4, 4])
.failOffsetY([-24, 24])
.onStart(() => {
runOnJS(handleResizeStart)();
})
.onUpdate((event) => {
runOnJS(handleResize)(event.translationX);
})
.onFinalize(() => {
runOnJS(handleResizeEnd)();
}),
[handleResize, handleResizeEnd, handleResizeStart],
);
const handleAccessibilityAction = (event: AccessibilityActionEvent) => {
props.onResizeStart?.();
if (event.nativeEvent.actionName === "increment") {
props.onResizeBy(ACCESSIBILITY_RESIZE_STEP);
} else if (event.nativeEvent.actionName === "decrement") {
props.onResizeBy(-ACCESSIBILITY_RESIZE_STEP);
}
props.onResizeEnd?.();
};
return (
<GestureDetector gesture={resizeGesture}>
<Pressable
accessibilityActions={[
{ name: "increment", label: "Make pane wider" },
{ name: "decrement", label: "Make pane narrower" },
]}
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="adjustable"
accessibilityValue={{
now: Math.round(props.currentWidth),
text: `${Math.round(props.currentWidth)} points wide`,
}}
onAccessibilityAction={handleAccessibilityAction}
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
style={styles.hitTarget}
>
<View style={[styles.line, (hovered || dragging) && styles.activeLine]} />
</Pressable>
</GestureDetector>
);
}
const styles = StyleSheet.create({
hitTarget: {
alignSelf: "stretch",
cursor: "pointer",
justifyContent: "center",
marginHorizontal: -22,
position: "relative",
width: 44,
zIndex: 100,
},
line: {
alignSelf: "center",
backgroundColor:
Platform.OS === "ios" ? PlatformColor("separator") : "rgba(120, 120, 128, 0.28)",
height: "100%",
opacity: 0.7,
width: StyleSheet.hairlineWidth,
},
activeLine: {
backgroundColor: Platform.OS === "ios" ? PlatformColor("systemBlueColor") : "#0a84ff",
opacity: 1,
width: 2,
},
});
@@ -0,0 +1,31 @@
import { NativeHeaderToolbar } from "../../navigation/native-stack-header";
import type { ReactNode } from "react";
import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
export function WorkspaceSidebarToolbar(
props: {
readonly children?: ReactNode;
readonly afterSidebarButton?: ReactNode;
} = {},
) {
const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
if (!layout.usesSplitView) {
return null;
}
return (
<NativeHeaderToolbar placement="left">
{props.children}
<NativeHeaderToolbar.Button
accessibilityLabel={
panes.primarySidebarVisible ? "Maximize content" : "Show thread sidebar"
}
icon={panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"}
onPress={togglePrimarySidebar}
/>
{props.afterSidebarButton}
</NativeHeaderToolbar>
);
}
@@ -22,7 +22,7 @@ import {
isFilesystemBrowseQuery,
} from "@t3tools/client-runtime/state/projects";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
@@ -40,6 +40,13 @@ import { sourceControlEnvironment } from "../../state/sourceControl";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { SourceControlIcon } from "../../components/SourceControlIcon";
import {
addProjectDestinationNavigation,
addProjectLocalNavigation,
addProjectRepositoryNavigation,
connectionsNewNavigation,
newTaskDraftNavigation,
} from "../../lib/routes";
import { useThemeColor } from "../../lib/useThemeColor";
import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -250,8 +257,8 @@ function useSelectedEnvironment(): {
readonly selectedEnvironment: EnvironmentOption | null;
readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
} {
const router = useRouter();
const params = useLocalSearchParams<{ environmentId?: string }>();
const navigation = useAppNavigation();
const params = useRouteParams<{ environmentId?: string }>();
const environmentOptions = useEnvironmentOptions();
const requestedEnvironmentId = stringParam(params.environmentId) as EnvironmentId | null;
const selectedEnvironment =
@@ -264,12 +271,12 @@ function useSelectedEnvironment(): {
return {
environmentOptions,
selectedEnvironment,
setSelectedEnvironmentId: (environmentId) => router.setParams({ environmentId }),
setSelectedEnvironmentId: (environmentId) => navigation.setParams({ environmentId }),
};
}
function EmptyEnvironmentState() {
const router = useRouter();
const navigation = useAppNavigation();
return (
<View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
@@ -278,7 +285,7 @@ function EmptyEnvironmentState() {
Add an environment before adding a project.
</Text>
<Pressable
onPress={() => router.replace("/connections/new")}
onPress={() => navigation.replace(connectionsNewNavigation())}
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
>
<Text className="text-sm font-t3-bold text-primary-foreground">Add environment</Text>
@@ -294,7 +301,7 @@ function SourceControlRow(props: {
readonly hint: string;
readonly isFirst: boolean;
}) {
const router = useRouter();
const navigation = useAppNavigation();
const iconColor = useThemeColor("--color-icon");
const title =
props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
@@ -322,20 +329,19 @@ function SourceControlRow(props: {
icon={icon}
isFirst={props.isFirst}
onPress={() =>
router.push({
pathname: "/new/add-project/repository",
params: {
navigation.push(
addProjectRepositoryNavigation({
environmentId: props.selectedEnvironmentId,
source: props.source,
},
})
}),
)
}
/>
);
}
export function AddProjectSourceScreen() {
const router = useRouter();
const navigation = useAppNavigation();
const accentColor = useThemeColor("--color-icon-muted");
const iconColor = useThemeColor("--color-icon");
const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
@@ -409,10 +415,11 @@ export function AddProjectSourceScreen() {
}
isFirst
onPress={() =>
router.push({
pathname: "/new/add-project/local",
params: { environmentId: selectedEnvironment.environmentId },
})
navigation.push(
addProjectLocalNavigation({
environmentId: selectedEnvironment.environmentId,
}),
)
}
/>
{(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
@@ -440,7 +447,7 @@ export function AddProjectSourceScreen() {
}
function useCreateProject(environment: EnvironmentOption | null) {
const router = useRouter();
const navigation = useAppNavigation();
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
const projects = useProjects();
@@ -455,14 +462,13 @@ function useCreateProject(environment: EnvironmentOption | null) {
});
if (existing) {
Alert.alert("Project already exists", existing.title);
router.replace({
pathname: "/new/draft",
params: {
navigation.replace(
newTaskDraftNavigation({
environmentId: existing.environmentId,
projectId: existing.id,
title: existing.title,
},
});
}),
);
return;
}
@@ -480,22 +486,21 @@ function useCreateProject(environment: EnvironmentOption | null) {
if (AsyncResult.isFailure(result)) {
return result;
}
router.replace({
pathname: "/new/draft",
params: {
navigation.replace(
newTaskDraftNavigation({
environmentId: environment.environmentId,
projectId,
title: inferProjectTitleFromPath(workspaceRoot),
},
});
}),
);
return result;
},
[createProject, environment, projects, router],
[createProject, environment, projects, navigation],
);
}
function useEnvironmentFromParam(): EnvironmentOption | null {
const params = useLocalSearchParams<{ environmentId?: string }>();
const params = useRouteParams<{ environmentId?: string }>();
const environmentOptions = useEnvironmentOptions();
const environmentId = stringParam(params.environmentId) as EnvironmentId | null;
return (
@@ -509,8 +514,8 @@ export function AddProjectRepositoryScreen() {
const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
reportFailure: false,
});
const router = useRouter();
const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
const navigation = useAppNavigation();
const params = useRouteParams<{ environmentId?: string; source?: string }>();
const environment = useEnvironmentFromParam();
const source = sourceFromParam(params.source);
const [repositoryInput, setRepositoryInput] = useState("");
@@ -524,15 +529,14 @@ export function AddProjectRepositoryScreen() {
const provider = addProjectRemoteSourceProvider(source);
if (!provider) {
const remoteUrl = repositoryInput.trim();
router.push({
pathname: "/new/add-project/destination",
params: {
navigation.push(
addProjectDestinationNavigation({
environmentId: environment.environmentId,
source,
remoteUrl,
repositoryTitle: remoteUrl,
},
});
}),
);
setIsSubmitting(false);
return;
}
@@ -548,18 +552,17 @@ export function AddProjectRepositoryScreen() {
setError(errorMessage(Cause.squash(result.cause)));
} else {
const repository = result.value;
router.push({
pathname: "/new/add-project/destination",
params: {
navigation.push(
addProjectDestinationNavigation({
environmentId: environment.environmentId,
source,
remoteUrl: repository.sshUrl,
repositoryTitle: repository.nameWithOwner,
},
});
}),
);
}
setIsSubmitting(false);
}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, router, source]);
}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
return (
<AddProjectShell>
@@ -749,7 +752,7 @@ export function AddProjectDestinationScreen() {
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
reportFailure: false,
});
const params = useLocalSearchParams<{
const params = useRouteParams<{
environmentId?: string;
remoteUrl?: string;
repositoryTitle?: string;
@@ -1,4 +1,4 @@
import { useLocalSearchParams, useRouter } from "expo-router";
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
import { SymbolView } from "expo-symbols";
import { TextInputWrapper } from "expo-paste-input";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
@@ -41,13 +41,13 @@ import {
const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
export function ReviewCommentComposerSheet() {
const router = useRouter();
const navigation = useAppNavigation();
const insets = useSafeAreaInsets();
const { width } = useWindowDimensions();
const colorScheme = useColorScheme();
const iconTint = String(useThemeColor("--color-icon"));
const target = useReviewCommentTarget();
const { environmentId, threadId } = useLocalSearchParams<{
const { environmentId, threadId } = useRouteParams<{
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
@@ -84,8 +84,8 @@ export function ReviewCommentComposerSheet() {
const previewViewportWidth = Math.max(width - 40, 280);
const dismissComposer = useCallback(() => {
clearReviewCommentTarget();
router.dismiss();
}, [router]);
navigation.dismiss();
}, [navigation]);
const handleNativePaste = useNativePaste((uris) => {
void (async () => {
try {
+484 -148
View File
@@ -1,10 +1,26 @@
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useLocalSearchParams } from "expo-router";
import Stack from "expo-router/stack";
import { useRouteParams } from "../../navigation/native-stack-header";
import { useHeaderHeight } from "@react-navigation/elements";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
} from "../../navigation/native-stack-header";
import { SymbolView } from "expo-symbols";
import { memo, type ReactElement, useCallback, useMemo } from "react";
import {
memo,
type Ref,
type ReactElement,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from "react";
import {
ActivityIndicator,
FlatList,
Platform,
Pressable,
ScrollView,
type NativeSyntheticEvent,
@@ -19,24 +35,37 @@ import { AppText as Text } from "../../components/AppText";
import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { useAtomCommand } from "../../state/use-atom-command";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { useThemeColor } from "../../lib/useThemeColor";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import { AdaptiveInspectorLayout } from "../layout/adaptive-inspector-layout";
import {
useAdaptiveWorkspaceLayout,
useAdaptiveWorkspacePaneRole,
} from "../layout/AdaptiveWorkspaceLayout";
import { useReviewCacheForThread } from "./reviewState";
import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
import {
type NativeReviewDiffViewHandle,
resolveNativeReviewDiffView,
} from "../diffs/nativeReviewDiffSurface";
import {
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
NATIVE_REVIEW_DIFF_ROW_HEIGHT,
} from "./nativeReviewDiffAdapter";
import { useReviewDiffData } from "./useReviewDiffData";
import { useReviewDiffPrewarming } from "./useReviewDiffPrewarming";
import { useReviewFileVisibility } from "./reviewFileVisibility";
import { useReviewSections } from "./useReviewSections";
import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge";
import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController";
import { resolveReviewAvailability } from "./reviewAvailability";
import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
import { buildReviewSectionMenu } from "./review-section-menu";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
const IOS_NAV_BAR_HEIGHT = 44;
const REVIEW_HEADER_SPACING = 0;
const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
@@ -110,13 +139,266 @@ function ReviewSelectionActionBar(props: {
);
}
interface ReviewNavigatorFile {
readonly id: string;
readonly path: string;
readonly additions: number;
readonly deletions: number;
}
const ReviewFileNavigatorRow = memo(function ReviewFileNavigatorRow(props: {
readonly file: ReviewNavigatorFile;
readonly selected: boolean;
readonly onSelectFile: (fileId: string | null) => void;
}) {
const { file, selected, onSelectFile } = props;
const handlePress = useCallback(() => {
onSelectFile(file.id);
}, [file.id, onSelectFile]);
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected }}
className={
selected
? "mt-1 min-h-12 justify-center rounded-xl bg-subtle-strong px-3 py-2"
: "mt-1 min-h-12 justify-center rounded-xl px-3 py-2 active:bg-subtle"
}
onPress={handlePress}
>
<Text
className={
selected
? "text-xs font-t3-bold text-foreground"
: "text-xs font-t3-medium text-foreground-secondary"
}
numberOfLines={2}
>
{file.path}
</Text>
<View className="mt-1 flex-row gap-2">
<Text className="text-2xs font-t3-bold text-emerald-600">+{file.additions}</Text>
<Text className="text-2xs font-t3-bold text-rose-600">-{file.deletions}</Text>
</View>
</Pressable>
);
});
interface ReviewFileNavigatorHandle {
readonly setVisibleFile: (fileId: string | null) => void;
}
interface ReviewFileNavigatorProps {
readonly files: ReadonlyArray<ReviewNavigatorFile>;
readonly headerInset: number;
readonly sectionId: string | null;
readonly onSelectFile: (fileId: string | null) => void;
readonly ref?: Ref<ReviewFileNavigatorHandle>;
}
function ReviewFileNavigator({
files,
headerInset,
sectionId,
onSelectFile,
ref,
}: ReviewFileNavigatorProps) {
const [fileSelection, setFileSelection] = useState<{
readonly sectionId: string | null;
readonly fileId: string | null;
}>({ sectionId: null, fileId: null });
const availableFileIds = useMemo(() => files.map((file) => file.id), [files]);
const selectedFileId = resolveSelectedReviewFileId({
selection: fileSelection,
sectionId,
availableFileIds,
});
useImperativeHandle(
ref,
() => ({
setVisibleFile: (fileId) => {
if (fileId !== null && !availableFileIds.includes(fileId)) {
return;
}
setFileSelection((current) => {
if (current.sectionId === sectionId && current.fileId === fileId) {
return current;
}
return { sectionId, fileId };
});
},
}),
[availableFileIds, sectionId],
);
const handleSelectFile = useCallback(
(fileId: string | null) => {
setFileSelection({ sectionId, fileId });
onSelectFile(fileId);
},
[onSelectFile, sectionId],
);
const renderFile = useCallback(
({ item }: { readonly item: ReviewNavigatorFile }) => (
<ReviewFileNavigatorRow
file={item}
selected={selectedFileId === item.id}
onSelectFile={handleSelectFile}
/>
),
[handleSelectFile, selectedFileId],
);
return (
<View className="flex-1 border-l border-border bg-sheet">
<View className="border-b border-border" style={{ paddingTop: headerInset }}>
<View className="px-4 py-3">
<Text className="text-sm font-t3-bold text-foreground">Changed files</Text>
<Text className="text-xs text-foreground-muted">
{files.length} {files.length === 1 ? "file" : "files"}
</Text>
</View>
</View>
<FlatList
data={files}
extraData={selectedFileId}
keyExtractor={(file) => file.id}
contentContainerStyle={{ paddingHorizontal: 8, paddingVertical: 8 }}
ListHeaderComponent={
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: selectedFileId === null }}
className={
selectedFileId === null
? "min-h-11 justify-center rounded-xl bg-subtle-strong px-3"
: "min-h-11 justify-center rounded-xl px-3 active:bg-subtle"
}
onPress={() => handleSelectFile(null)}
>
<Text className="text-sm font-t3-bold text-foreground">All files</Text>
<Text className="text-xs text-foreground-muted">
{files.length} changed {files.length === 1 ? "file" : "files"}
</Text>
</Pressable>
}
renderItem={renderFile}
/>
</View>
);
}
function ReviewHeaderTitle(props: {
readonly additions: string | null;
readonly deletions: string | null;
readonly foregroundColor: string;
readonly mutedColor: string;
readonly pendingCommentCount: number;
readonly sectionTitle: string;
}) {
return (
<View style={{ alignItems: "center" }}>
<NativeText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
fontWeight: "900",
color: props.foregroundColor,
letterSpacing: -0.4,
}}
>
Files Changed
</NativeText>
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 6,
flexWrap: "wrap",
}}
>
{props.additions && props.deletions ? (
<>
<NativeText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: "#16a34a",
}}
>
{props.additions}
</NativeText>
<NativeText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: "#e11d48",
}}
>
{props.deletions}
</NativeText>
{props.pendingCommentCount > 0 ? (
<NativeText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: "#b45309",
}}
>
{props.pendingCommentCount} pending
</NativeText>
) : null}
</>
) : (
<View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
<NativeText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: props.mutedColor,
}}
>
{props.sectionTitle}
</NativeText>
{props.pendingCommentCount > 0 ? (
<NativeText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: "#b45309",
}}
>
{props.pendingCommentCount} pending
</NativeText>
) : null}
</View>
)}
</View>
</View>
);
}
export function ReviewSheet() {
useAdaptiveWorkspacePaneRole("inspector");
const { layout, panes, showAuxiliaryPane, toggleAuxiliaryPane, togglePrimarySidebar } =
useAdaptiveWorkspaceLayout();
const insets = useSafeAreaInsets();
const headerHeight = useHeaderHeight();
const colorScheme = useColorScheme();
const headerForeground = String(useThemeColor("--color-foreground"));
const headerMuted = String(useThemeColor("--color-foreground-muted"));
const headerIcon = String(useThemeColor("--color-icon"));
const { environmentId, threadId } = useLocalSearchParams<{
const { environmentId, threadId } = useRouteParams<{
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
@@ -126,7 +408,11 @@ export function ReviewSheet() {
const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
const selectedTheme = colorScheme === "dark" ? "dark" : "light";
const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
const topContentInset = headerHeight;
useEffect(() => {
showAuxiliaryPane("inspector");
}, [environmentId, showAuxiliaryPane, threadId]);
const {
error,
loadingGitDiffs,
@@ -141,6 +427,11 @@ export function ReviewSheet() {
threadId,
reviewCache,
});
useReviewDiffPrewarming({
threadKey: reviewCache.threadKey,
sections: reviewSections,
selectedSectionId: selectedSection?.id ?? null,
});
const { headerDiffSummary, nativeReviewDiffData, parsedDiff, pendingReviewCommentCount } =
useReviewDiffData({
threadKey: reviewCache.threadKey,
@@ -148,6 +439,8 @@ export function ReviewSheet() {
draftMessage,
});
const NativeReviewDiffView = resolveNativeReviewDiffView()!;
const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
const reviewFileNavigatorRef = useRef<ReviewFileNavigatorHandle>(null);
const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : [];
const fileVisibility = useReviewFileVisibility({
threadKey: reviewCache.threadKey,
@@ -179,6 +472,41 @@ export function ReviewSheet() {
canHighlight: parsedDiff.kind === "files",
});
const handleSelectFile = useCallback(
(fileId: string | null) => {
commentSelection.clearSelection();
if (fileId !== null && collapsedFileIds.includes(fileId)) {
toggleExpandedFile(fileId);
}
const navigation =
fileId === null
? nativeReviewDiffViewRef.current?.scrollToTop(true)
: nativeReviewDiffViewRef.current?.scrollToFile(fileId, true);
void navigation?.catch((error: unknown) => {
console.error("[review] Failed to navigate to diff file", error);
});
},
[collapsedFileIds, commentSelection, toggleExpandedFile],
);
const handleVisibleFileChange = useCallback(
(event: NativeSyntheticEvent<{ readonly fileId?: string | null }>) => {
reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
},
[],
);
const renderInspector = useCallback(
() => (
<ReviewFileNavigator
ref={reviewFileNavigatorRef}
files={nativeReviewDiffData.files}
headerInset={headerHeight}
sectionId={selectedSection?.id ?? null}
onSelectFile={handleSelectFile}
/>
),
[handleSelectFile, headerHeight, nativeReviewDiffData.files, selectedSection?.id],
);
const handleNativeToggleFile = useCallback(
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
const { fileId } = event.nativeEvent;
@@ -203,6 +531,7 @@ export function ReviewSheet() {
parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
const hasCachedSelectedDiff = selectedSection?.diff != null;
const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);
const sectionMenu = useMemo(() => buildReviewSectionMenu(reviewSections), [reviewSections]);
const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({
hasEnvironmentPresentation: environment.isReady,
isEnvironmentConnected: isEnvironmentReady,
@@ -235,10 +564,30 @@ export function ReviewSheet() {
return <>{children}</>;
}, [error, parsedDiffNotice]);
const renderHeaderTitle = useCallback(
() => (
<ReviewHeaderTitle
additions={headerDiffSummary.additions}
deletions={headerDiffSummary.deletions}
foregroundColor={headerForeground}
mutedColor={headerMuted}
pendingCommentCount={pendingReviewCommentCount}
sectionTitle={selectedSection?.title ?? "Review changes"}
/>
),
[
headerDiffSummary.additions,
headerDiffSummary.deletions,
headerForeground,
headerMuted,
pendingReviewCommentCount,
selectedSection?.title,
],
);
return (
<>
<Stack.Screen
<NativeStackScreenOptions
options={{
headerTransparent: true,
headerShadowVisible: false,
@@ -246,123 +595,102 @@ export function ReviewSheet() {
headerStyle: {
backgroundColor: "transparent",
},
headerTitle: () => (
<View style={{ alignItems: "center" }}>
<NativeText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
fontWeight: "900",
color: headerForeground,
letterSpacing: -0.4,
}}
>
Files Changed
</NativeText>
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 6,
flexWrap: "wrap",
}}
>
{headerDiffSummary.additions && headerDiffSummary.deletions ? (
<>
<NativeText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: "#16a34a",
}}
>
{headerDiffSummary.additions}
</NativeText>
<NativeText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: "#e11d48",
}}
>
{headerDiffSummary.deletions}
</NativeText>
{pendingReviewCommentCount > 0 ? (
<NativeText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: "#b45309",
}}
>
{pendingReviewCommentCount} pending
</NativeText>
) : null}
</>
) : (
<View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
<NativeText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: headerMuted,
}}
>
{selectedSection?.title ?? "Review changes"}
</NativeText>
{pendingReviewCommentCount > 0 ? (
<NativeText
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: "#b45309",
}}
>
{pendingReviewCommentCount} pending
</NativeText>
) : null}
</View>
)}
</View>
</View>
),
headerTitle: renderHeaderTitle,
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
}}
/>
{showSectionToolbar ? (
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground>
{reviewSections.map((section) => (
<Stack.Toolbar.MenuAction
key={section.id}
icon={section.id === selectedSection?.id ? "checkmark" : "circle"}
onPress={() => selectSection(section.id)}
subtitle={section.subtitle ?? undefined}
>
<Stack.Toolbar.Label>{section.title}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
<Stack.Toolbar.MenuAction
icon="arrow.clockwise"
disabled={
loadingGitDiffs ||
(selectedSection?.kind === "turn" && loadingTurnIds[selectedSection.id] === true)
{layout.usesSplitView ? (
<NativeHeaderToolbar placement="left">
<NativeHeaderToolbar.Button
accessibilityLabel={panes.primarySidebarVisible ? "Maximize review" : "Show threads"}
icon={
panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
}
onPress={togglePrimarySidebar}
separateBackground
/>
</NativeHeaderToolbar>
) : null}
{showSectionToolbar || panes.supportsAuxiliaryPane ? (
<NativeHeaderToolbar placement="right">
{panes.supportsAuxiliaryPane ? (
<NativeHeaderToolbar.Button
accessibilityLabel={
panes.auxiliaryPaneVisible ? "Hide changed files" : "Show changed files"
}
onPress={() => void refreshSelectedSection()}
subtitle="Reload current diff"
>
<Stack.Toolbar.Label>Refresh</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
icon="sidebar.right"
onPress={toggleAuxiliaryPane}
separateBackground
/>
) : null}
{showSectionToolbar ? (
<NativeHeaderToolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground>
<NativeHeaderToolbar.Menu inline>
<NativeHeaderToolbar.MenuAction
disabled={sectionMenu.workingTree === null}
isOn={selectedSection?.id === sectionMenu.workingTree?.id}
onPress={() => {
if (sectionMenu.workingTree) {
selectSection(sectionMenu.workingTree.id);
}
}}
>
<NativeHeaderToolbar.Label>Working tree</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
disabled={sectionMenu.branchChanges === null}
isOn={selectedSection?.id === sectionMenu.branchChanges?.id}
onPress={() => {
if (sectionMenu.branchChanges) {
selectSection(sectionMenu.branchChanges.id);
}
}}
>
<NativeHeaderToolbar.Label>Branch changes</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
disabled={sectionMenu.latestTurn === null}
isOn={selectedSection?.id === sectionMenu.latestTurn?.id}
onPress={() => {
if (sectionMenu.latestTurn) {
selectSection(sectionMenu.latestTurn.id);
}
}}
>
<NativeHeaderToolbar.Label>Latest turn</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
{sectionMenu.turns.length > 0 ? (
<NativeHeaderToolbar.Menu title="Turn">
{sectionMenu.turns.map((section) => (
<NativeHeaderToolbar.MenuAction
key={section.id}
isOn={section.id === selectedSection?.id}
onPress={() => selectSection(section.id)}
subtitle={section.subtitle ?? undefined}
>
<NativeHeaderToolbar.Label>{section.title}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
) : null}
</NativeHeaderToolbar.Menu>
<NativeHeaderToolbar.MenuAction
icon="arrow.clockwise"
disabled={
loadingGitDiffs ||
(selectedSection?.kind === "turn" && loadingTurnIds[selectedSection.id] === true)
}
onPress={() => void refreshSelectedSection()}
subtitle="Reload current diff"
>
<NativeHeaderToolbar.Label>Refresh</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
) : null}
</NativeHeaderToolbar>
) : null}
<View className="flex-1 bg-sheet">
@@ -386,35 +714,43 @@ export function ReviewSheet() {
className="flex-1"
style={{
backgroundColor: nativeBridge.theme.background,
paddingTop: topContentInset + REVIEW_HEADER_SPACING,
}}
>
{listHeader}
<View className="flex-1" collapsable={false}>
<NativeReviewDiffView
key={`${reviewCache.threadKey}:${selectedSection.id}`}
collapsable={false}
testID="review-native-diff-view"
style={StyleSheet.absoluteFill}
appearanceScheme={selectedTheme}
collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
rowsJson={nativeBridge.rowsJson}
selectedRowIdsJson={nativeBridge.selectedRowIdsJson}
styleJson={nativeBridge.styleJson}
themeJson={nativeBridge.themeJson}
tokensPatchJson={nativeBridge.tokensPatchJson}
tokensResetKey={nativeBridge.tokensResetKey}
viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
onDebug={nativeBridge.onDebug}
onPressLine={commentSelection.onPressLine}
onToggleComment={nativeBridge.onToggleComment}
onToggleFile={handleNativeToggleFile}
onToggleViewedFile={handleNativeToggleViewedFile}
/>
</View>
<AdaptiveInspectorLayout renderInspector={renderInspector}>
<View
className="min-w-0 flex-1"
style={{ paddingTop: topContentInset + REVIEW_HEADER_SPACING }}
>
{listHeader}
<View className="min-w-0 flex-1" collapsable={false}>
<NativeReviewDiffView
collapsable={false}
testID="review-native-diff-view"
style={StyleSheet.absoluteFill}
appearanceScheme={selectedTheme}
collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`}
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
nativeViewRef={nativeReviewDiffViewRef}
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
rowsJson={nativeBridge.rowsJson}
selectedRowIdsJson={nativeBridge.selectedRowIdsJson}
styleJson={nativeBridge.styleJson}
themeJson={nativeBridge.themeJson}
tokensPatchJson={nativeBridge.tokensPatchJson}
tokensResetKey={nativeBridge.tokensResetKey}
viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
onDebug={nativeBridge.onDebug}
onPressLine={commentSelection.onPressLine}
onVisibleFileChange={handleVisibleFileChange}
onToggleComment={nativeBridge.onToggleComment}
onToggleFile={handleNativeToggleFile}
onToggleViewedFile={handleNativeToggleViewedFile}
/>
</View>
</View>
</AdaptiveInspectorLayout>
</View>
) : (
<ScrollView
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vite-plus/test";
import {
getCachedNativeReviewDiffData,
type BuildNativeReviewDiffDataInput,
} from "./nativeReviewDiffAdapter";
import type { ReviewInlineComment } from "./reviewCommentSelection";
import { buildReviewParsedDiff } from "./reviewModel";
const parsedDiff = buildReviewParsedDiff(
[
"diff --git a/example.ts b/example.ts",
"--- a/example.ts",
"+++ b/example.ts",
"@@ -1 +1 @@",
"-const before = 1;",
"+const after = 2;",
].join("\n"),
"native-review-cache-test",
);
function makeComment(text: string): ReviewInlineComment {
return {
id: "comment-1",
sectionId: "git:working-tree",
sectionTitle: "Dirty worktree",
filePath: "example.ts",
startIndex: 0,
endIndex: 0,
rangeLabel: "-1",
text,
diff: "@@ -1,1 +1,0 @@\n-const before = 1;",
};
}
function buildInput(comments: BuildNativeReviewDiffDataInput["comments"]) {
return { parsedDiff, comments } satisfies BuildNativeReviewDiffDataInput;
}
describe("getCachedNativeReviewDiffData", () => {
it("reuses the row model for equivalent empty comment arrays", () => {
const first = getCachedNativeReviewDiffData(buildInput([]));
const second = getCachedNativeReviewDiffData(buildInput([]));
expect(second).toBe(first);
});
it("reuses equivalent comment contents and invalidates changed comments", () => {
const first = getCachedNativeReviewDiffData(buildInput([makeComment("First")]));
const equivalent = getCachedNativeReviewDiffData(buildInput([makeComment("First")]));
const changed = getCachedNativeReviewDiffData(buildInput([makeComment("Changed")]));
expect(equivalent).toBe(first);
expect(changed).not.toBe(first);
});
});
@@ -75,6 +75,33 @@ export interface BuildNativeReviewDiffDataInput {
readonly comments?: ReadonlyArray<ReviewInlineComment>;
}
interface CachedNativeReviewDiffData {
readonly commentsKey: string;
readonly data: NativeReviewDiffData;
}
const nativeReviewDiffDataCache = new WeakMap<ReviewParsedDiff, CachedNativeReviewDiffData>();
function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment>): string {
if (comments.length === 0) {
return "none";
}
return comments
.map((comment) =>
[
comment.id,
comment.sectionId,
comment.filePath,
comment.startIndex,
comment.endIndex,
comment.rangeLabel,
comment.text,
].join("\u001f"),
)
.join("\u001e");
}
export function createNativeReviewDiffTheme(
scheme: TerminalAppearanceScheme,
): NativeReviewDiffTheme {
@@ -430,3 +457,26 @@ export function buildNativeReviewDiffData(
deletions: parsedDiff.deletions,
};
}
/**
* Reuses the expensive flattened native row model across React development
* render probes and unrelated draft updates. Only the latest comment version
* is retained for each parsed diff so editing a comment cannot grow the cache.
*/
export function getCachedNativeReviewDiffData(
input: BuildNativeReviewDiffDataInput,
): NativeReviewDiffData {
const comments = input.comments ?? [];
const commentsKey = buildReviewCommentsCacheKey(comments);
const cached = nativeReviewDiffDataCache.get(input.parsedDiff);
if (cached?.commentsKey === commentsKey) {
return cached.data;
}
const data = buildNativeReviewDiffData({
parsedDiff: input.parsedDiff,
comments,
});
nativeReviewDiffDataCache.set(input.parsedDiff, { commentsKey, data });
return data;
}
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vite-plus/test";
import type { ReviewSectionItem, ReviewSectionKind } from "./reviewModel";
import { buildReviewSectionMenu } from "./review-section-menu";
function section(id: string, kind: ReviewSectionKind): ReviewSectionItem {
return {
id,
kind,
title: id,
subtitle: null,
diff: null,
isLoading: false,
};
}
describe("buildReviewSectionMenu", () => {
it("exposes git scopes and the latest turn at the top level", () => {
const turn28 = section("turn:28", "turn");
const turn27 = section("turn:27", "turn");
const workingTree = section("git:working-tree", "working-tree");
const branchChanges = section("git:branch-range", "branch-range");
expect(buildReviewSectionMenu([turn28, turn27, workingTree, branchChanges])).toEqual({
workingTree,
branchChanges,
latestTurn: turn28,
turns: [turn28, turn27],
});
});
it("keeps unavailable scopes empty while data loads", () => {
expect(buildReviewSectionMenu([])).toEqual({
workingTree: null,
branchChanges: null,
latestTurn: null,
turns: [],
});
});
});
@@ -0,0 +1,21 @@
import type { ReviewSectionItem } from "./reviewModel";
export interface ReviewSectionMenu {
readonly workingTree: ReviewSectionItem | null;
readonly branchChanges: ReviewSectionItem | null;
readonly latestTurn: ReviewSectionItem | null;
readonly turns: ReadonlyArray<ReviewSectionItem>;
}
export function buildReviewSectionMenu(
sections: ReadonlyArray<ReviewSectionItem>,
): ReviewSectionMenu {
const turns = sections.filter((section) => section.kind === "turn");
return {
workingTree: sections.find((section) => section.kind === "working-tree") ?? null,
branchChanges: sections.find((section) => section.kind === "branch-range") ?? null,
latestTurn: turns[0] ?? null,
turns,
};
}
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
describe("resolveSelectedReviewFileId", () => {
it("keeps a visible file selected within the active section", () => {
expect(
resolveSelectedReviewFileId({
selection: { sectionId: "worktree", fileId: "second" },
sectionId: "worktree",
availableFileIds: ["first", "second"],
}),
).toBe("second");
});
it("clears selection when the review section changes", () => {
expect(
resolveSelectedReviewFileId({
selection: { sectionId: "turn-1", fileId: "first" },
sectionId: "turn-2",
availableFileIds: ["first"],
}),
).toBeNull();
});
it("clears a file that no longer exists in the diff", () => {
expect(
resolveSelectedReviewFileId({
selection: { sectionId: "worktree", fileId: "removed" },
sectionId: "worktree",
availableFileIds: ["first", "second"],
}),
).toBeNull();
});
});
@@ -0,0 +1,16 @@
export interface ReviewPaneFileSelection {
readonly sectionId: string | null;
readonly fileId: string | null;
}
export function resolveSelectedReviewFileId(input: {
readonly selection: ReviewPaneFileSelection;
readonly sectionId: string | null;
readonly availableFileIds: ReadonlyArray<string>;
}): string | null {
if (input.selection.sectionId !== input.sectionId || input.selection.fileId === null) {
return null;
}
return input.availableFileIds.includes(input.selection.fileId) ? input.selection.fileId : null;
}
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import type { NativeSyntheticEvent } from "react-native";
import { useRouter } from "expo-router";
import { useAppNavigation } from "../../navigation/native-stack-header";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Result from "effect/Result";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { buildThreadReviewCommentNavigation } from "../../lib/routes";
import {
buildReviewCommentTarget,
@@ -34,7 +35,7 @@ export function useReviewCommentSelectionController(input: {
readonly nativeReviewDiffData: NativeReviewDiffData;
}) {
const { environmentId, nativeReviewDiffData, selectedSection, threadId } = input;
const { push } = useRouter();
const navigation = useAppNavigation();
const activeCommentTarget = useReviewCommentTarget();
const [pendingNativeCommentSelection, setPendingNativeCommentSelection] =
useState<PendingNativeCommentSelection | null>(null);
@@ -44,11 +45,8 @@ export function useReviewCommentSelectionController(input: {
return;
}
push({
pathname: "/threads/[environmentId]/[threadId]/review-comment",
params: { environmentId, threadId },
});
}, [environmentId, push, threadId]);
navigation.push(buildThreadReviewCommentNavigation({ environmentId, threadId }));
}, [environmentId, navigation, threadId]);
const selectedRowIds = useMemo(() => {
if (
@@ -1,11 +1,13 @@
import { useEffect, useMemo } from "react";
import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection";
import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter";
import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter";
import { markReviewEvent, measureReviewWork } from "./reviewPerf";
import { getCachedReviewParsedDiff } from "./reviewState";
import type { ReviewParsedDiff, ReviewSectionItem } from "./reviewModel";
const EMPTY_INLINE_REVIEW_COMMENTS = Object.freeze([]);
function isReviewDiffDebugLoggingEnabled(): boolean {
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
}
@@ -43,6 +45,7 @@ export function useReviewDiffData(input: {
readonly draftMessage: string;
}) {
const { draftMessage, selectedSection, threadKey } = input;
const selectedSectionId = selectedSection?.id ?? null;
const parsedDiff = useMemo(
() =>
measureReviewWork("parse-diff", () =>
@@ -59,17 +62,16 @@ export function useReviewDiffData(input: {
() => parseReviewInlineComments(draftMessage),
[draftMessage],
);
const selectedSectionInlineComments = useMemo(
() =>
selectedSection
? inlineReviewComments.filter((comment) => comment.sectionId === selectedSection.id)
: [],
[inlineReviewComments, selectedSection],
);
const selectedSectionInlineComments = useMemo(() => {
if (!selectedSectionId || inlineReviewComments.length === 0) {
return EMPTY_INLINE_REVIEW_COMMENTS;
}
return inlineReviewComments.filter((comment) => comment.sectionId === selectedSectionId);
}, [inlineReviewComments, selectedSectionId]);
const nativeReviewDiffData = useMemo(
() =>
measureReviewWork("build-native-diff-data", () =>
buildNativeReviewDiffData({
getCachedNativeReviewDiffData({
parsedDiff,
comments: selectedSectionInlineComments,
}),
@@ -0,0 +1,101 @@
import { useEffect } from "react";
import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter";
import type { ReviewSectionItem } from "./reviewModel";
import { getCachedReviewParsedDiff } from "./reviewState";
interface IdleDeadlineLike {
readonly didTimeout: boolean;
timeRemaining(): number;
}
type IdleCallback = (deadline: IdleDeadlineLike) => void;
function scheduleIdle(callback: IdleCallback): number {
if (typeof globalThis.requestIdleCallback === "function") {
return globalThis.requestIdleCallback(callback, { timeout: 2_000 });
}
return setTimeout(
() => callback({ didTimeout: true, timeRemaining: () => 0 }),
100,
) as unknown as number;
}
function cancelIdle(handle: number): void {
if (typeof globalThis.cancelIdleCallback === "function") {
globalThis.cancelIdleCallback(handle);
return;
}
clearTimeout(handle);
}
export function prewarmReviewDiffSection(input: {
readonly threadKey: string;
readonly section: ReviewSectionItem;
}): void {
const { section, threadKey } = input;
if (section.diff === null) {
return;
}
const parsedDiff = getCachedReviewParsedDiff({
threadKey,
sectionId: section.id,
diff: section.diff,
});
getCachedNativeReviewDiffData({ parsedDiff, comments: [] });
}
/** Warms one cached section per idle period, after navigation animations finish. */
export function useReviewDiffPrewarming(input: {
readonly threadKey: string | null;
readonly sections: ReadonlyArray<ReviewSectionItem>;
readonly selectedSectionId: string | null;
}): void {
const { sections, selectedSectionId, threadKey } = input;
useEffect(() => {
if (!threadKey) {
return;
}
const pendingSections = sections.filter(
(section) => section.id !== selectedSectionId && section.diff !== null,
);
if (pendingSections.length === 0) {
return;
}
let cancelled = false;
let idleHandle: number | null = null;
let nextSectionIndex = 0;
const scheduleNext = () => {
idleHandle = scheduleIdle(() => {
if (cancelled) {
return;
}
const section = pendingSections[nextSectionIndex];
if (!section) {
return;
}
nextSectionIndex += 1;
prewarmReviewDiffSection({ threadKey, section });
if (nextSectionIndex < pendingSections.length) {
scheduleNext();
}
});
};
scheduleNext();
return () => {
cancelled = true;
if (idleHandle !== null) {
cancelIdle(idleHandle);
}
};
}, [sections, selectedSectionId, threadKey]);
}
@@ -179,7 +179,6 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
const keyboardInputRef = useRef<TextInput>(null);
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
const { onInput, onResize } = props;
@@ -196,9 +195,12 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
}, [hasNativeSurface, props.buffer.length, props.isRunning, props.terminalKey]);
const handleNativeInput = useCallback(
(event: NativeSyntheticEvent<TerminalInputEvent>) => {
if (!props.isRunning) {
return;
}
onInput(event.nativeEvent.data);
},
[onInput],
[onInput, props.isRunning],
);
const handleNativeResize = useCallback(
(event: NativeSyntheticEvent<TerminalResizeEvent>) => {
@@ -210,33 +212,13 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
[onResize],
);
// Reopen focus through React and forward input normally; this avoids a native focus-command bridge.
useEffect(() => {
if (!NativeTerminalSurfaceView || (props.keyboardFocusRequest ?? 0) <= 0) {
return undefined;
}
keyboardInputRef.current?.blur();
const focusFrame = requestAnimationFrame(() => keyboardInputRef.current?.focus());
return () => cancelAnimationFrame(focusFrame);
}, [NativeTerminalSurfaceView, props.keyboardFocusRequest]);
const handleKeyboardInput = useCallback(
(data: string) => {
if (data.length > 0) {
onInput(data);
keyboardInputRef.current?.clear();
}
},
[onInput],
);
if (NativeTerminalSurfaceView) {
return (
<View style={props.style}>
<NativeTerminalSurfaceView
appearanceScheme={appearanceScheme}
backgroundColor={theme.background}
focusRequest={props.isRunning ? (props.keyboardFocusRequest ?? 0) : 0}
foregroundColor={theme.foreground}
mutedForegroundColor={theme.mutedForeground}
terminalKey={props.terminalKey}
@@ -247,23 +229,6 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
onInput={handleNativeInput}
onResize={handleNativeResize}
/>
<TextInput
ref={keyboardInputRef}
autoCapitalize="none"
autoCorrect={false}
blurOnSubmit={false}
caretHidden
editable={props.isRunning}
keyboardType="ascii-capable"
style={{ bottom: 0, height: 1, left: 0, opacity: 0.01, position: "absolute", width: 1 }}
onChangeText={handleKeyboardInput}
onKeyPress={(event) => {
if (event.nativeEvent.key === "Backspace") {
onInput("\u007f");
}
}}
onSubmitEditing={() => onInput("\n")}
/>
</View>
);
}
@@ -1,9 +1,14 @@
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import { SymbolView } from "expo-symbols";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
useRouteParams,
useAppNavigation,
} from "../../navigation/native-stack-header";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
import { Platform, Pressable, Text as RNText, View, useColorScheme } from "react-native";
import {
KeyboardController,
KeyboardEvents,
@@ -25,6 +30,7 @@ import { terminalEnvironment } from "../../state/terminal";
import { useAtomCommand } from "../../state/use-atom-command";
import { useWorkspaceState } from "../../state/workspace";
import { buildThreadTerminalNavigation } from "../../lib/routes";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import {
useAttachedTerminalSession,
@@ -33,6 +39,7 @@ import {
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { TerminalSurface } from "./NativeTerminalSurface";
import { getPierreTerminalTheme } from "./terminalTheme";
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
@@ -72,6 +79,7 @@ import {
const DEFAULT_TERMINAL_COLS = 80;
const DEFAULT_TERMINAL_ROWS = 24;
const TERMINAL_ACCESSORY_HEIGHT = 52;
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
type PendingModifier = "ctrl" | "meta";
type HostPlatform = "mac" | "linux" | "windows" | "unknown";
@@ -86,6 +94,47 @@ type TerminalToolbarAction =
readonly modifier: PendingModifier;
};
function TerminalHeaderTitle(props: {
readonly topLine: string;
readonly bottomLine: string;
readonly foreground: string;
readonly mutedForeground: string;
}) {
return (
<View
style={{
alignItems: "center",
gap: 1,
maxWidth: 240,
}}
>
<RNText
numberOfLines={1}
style={{
color: props.foreground,
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.footnote.fontSize,
lineHeight: 16,
}}
>
{props.topLine}
</RNText>
<RNText
ellipsizeMode="middle"
numberOfLines={1}
style={{
color: props.mutedForeground,
fontFamily: "Menlo",
fontSize: MOBILE_TYPOGRAPHY.caption.fontSize,
lineHeight: 14,
}}
>
{props.bottomLine}
</RNText>
</View>
);
}
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
return value[0] ?? null;
@@ -154,14 +203,15 @@ function pickRunningTerminalSessionForBootstrap(
}
export function ThreadTerminalRouteScreen() {
const router = useRouter();
const navigation = useAppNavigation();
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const { state: workspaceState } = useWorkspaceState();
const params = useLocalSearchParams<{
const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
const params = useRouteParams<{
environmentId?: string | string[];
threadId?: string | string[];
terminalId?: string | string[];
@@ -404,6 +454,7 @@ export function ThreadTerminalRouteScreen() {
);
const terminalTheme = getPierreTerminalTheme(appearanceScheme);
const usesNativeHeaderGlass = Platform.OS === "ios";
const pendingModifier =
pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
const headerTitle = useMemo(() => {
@@ -422,6 +473,22 @@ export function ThreadTerminalRouteScreen() {
selectedThreadProject?.title,
selectedThreadProject?.workspaceRoot,
]);
const renderTerminalHeaderTitle = useCallback(
() => (
<TerminalHeaderTitle
topLine={headerTitle.topLine}
bottomLine={headerTitle.bottomLine}
foreground={terminalTheme.foreground}
mutedForeground={terminalTheme.mutedForeground}
/>
),
[
headerTitle.bottomLine,
headerTitle.topLine,
terminalTheme.foreground,
terminalTheme.mutedForeground,
],
);
const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
const modifierActions: ReadonlyArray<TerminalToolbarAction> =
hostPlatform === "mac"
@@ -546,8 +613,10 @@ export function ThreadTerminalRouteScreen() {
if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
return;
}
router.replace(buildThreadTerminalNavigation(selectedThread, runningSession.target.terminalId));
}, [router, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
navigation.replace(
buildThreadTerminalNavigation(selectedThread, runningSession.target.terminalId),
);
}, [navigation, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
useEffect(() => {
const initialInput = pendingLaunch?.initialInput;
@@ -772,9 +841,9 @@ export function ThreadTerminalRouteScreen() {
return;
}
router.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
navigation.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
},
[router, selectedThread, terminalId],
[navigation, selectedThread, terminalId],
);
const handleOpenNewTerminal = useCallback(() => {
@@ -782,7 +851,7 @@ export function ThreadTerminalRouteScreen() {
return;
}
router.replace(
navigation.replace(
buildThreadTerminalNavigation(
selectedThread,
nextOpenTerminalId({
@@ -791,7 +860,7 @@ export function ThreadTerminalRouteScreen() {
}),
),
);
}, [router, selectedThread, terminalId, terminalMenuSessions]);
}, [navigation, selectedThread, terminalId, terminalMenuSessions]);
const adjustFontSize = useCallback((delta: number) => {
setTimeout(() => {
@@ -898,80 +967,72 @@ export function ThreadTerminalRouteScreen() {
return (
<>
<Stack.Screen
<NativeStackScreenOptions
options={{
headerShown: true,
headerBackButtonDisplayMode: "minimal",
headerBackTitle: "",
headerTransparent: usesNativeHeaderGlass,
headerShadowVisible: false,
headerStyle: { backgroundColor: terminalTheme.background },
headerStyle: {
backgroundColor: usesNativeHeaderGlass ? "transparent" : terminalTheme.background,
},
headerTintColor: terminalTheme.foreground,
headerTitleAlign: "center",
title: "",
headerTitle: () => (
<View
style={{
alignItems: "center",
gap: 1,
maxWidth: 240,
}}
>
<RNText
numberOfLines={1}
style={{
color: terminalTheme.foreground,
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.footnote.fontSize,
lineHeight: 16,
}}
>
{headerTitle.topLine}
</RNText>
<RNText
ellipsizeMode="middle"
numberOfLines={1}
style={{
color: terminalTheme.mutedForeground,
fontFamily: "Menlo",
fontSize: MOBILE_TYPOGRAPHY.caption.fontSize,
lineHeight: 14,
}}
>
{headerTitle.bottomLine}
</RNText>
</View>
),
headerTitle: usesNativeHeaderGlass ? headerTitle.topLine : renderTerminalHeaderTitle,
headerTitleStyle: usesNativeHeaderGlass
? {
fontSize: 17,
fontWeight: "800",
}
: undefined,
scrollEdgeEffects: usesNativeHeaderGlass ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
title: headerTitle.topLine,
unstable_navigationItemStyle: usesNativeHeaderGlass ? "editor" : undefined,
}}
/>
{layout.usesSplitView ? (
<NativeHeaderToolbar placement="left">
<NativeHeaderToolbar.Button
accessibilityLabel={panes.primarySidebarVisible ? "Maximize terminal" : "Show threads"}
icon={
panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
}
onPress={togglePrimarySidebar}
separateBackground
/>
</NativeHeaderToolbar>
) : null}
{isEnvironmentReady ? (
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="terminal" title="Terminal options" separateBackground>
<Stack.Toolbar.Label>
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Menu icon="terminal" title="Terminal options" separateBackground>
<NativeHeaderToolbar.Label>
{getTerminalStatusLabel({
status: terminal.status,
hasRunningSubprocess: terminal.hasRunningSubprocess,
})}
</Stack.Toolbar.Label>
<Stack.Toolbar.Menu icon="textformat.size" inline title="Text size">
<Stack.Toolbar.Label>Text size</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.Menu icon="textformat.size" inline title="Text size">
<NativeHeaderToolbar.Label>Text size</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
discoverabilityLabel="Decrease terminal text size"
onPress={handleDecreaseFontSize}
>
<Stack.Toolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
<NativeHeaderToolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
discoverabilityLabel="Increase terminal text size"
onPress={handleIncreaseFontSize}
>
<Stack.Toolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
<NativeHeaderToolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
{terminalMenuSessions.map((session) => (
<Stack.Toolbar.MenuAction
<NativeHeaderToolbar.MenuAction
key={session.terminalId}
icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
onPress={() => handleSelectTerminal(session.terminalId)}
@@ -982,18 +1043,18 @@ export function ThreadTerminalRouteScreen() {
.filter(Boolean)
.join(" · ")}
>
<Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<NativeHeaderToolbar.Label>{session.displayLabel}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
<Stack.Toolbar.MenuAction
<NativeHeaderToolbar.MenuAction
icon="plus"
onPress={handleOpenNewTerminal}
subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
>
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
<NativeHeaderToolbar.Label>Open new terminal</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar>
) : null}
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
@@ -23,6 +23,7 @@ interface TerminalResizeEvent {
export interface NativeTerminalSurfaceProps extends ViewProps {
readonly appearanceScheme?: "light" | "dark";
readonly focusRequest?: number;
readonly themeConfig?: string;
readonly backgroundColor?: string;
readonly foregroundColor?: string;
@@ -1,4 +1,4 @@
import { Stack, useRouter } from "expo-router";
import { NativeStackScreenOptions, useAppNavigation } from "../../navigation/native-stack-header";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { Alert, InteractionManager, View, useColorScheme } from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
@@ -29,7 +29,7 @@ import {
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { buildThreadRoutePath } from "../../lib/routes";
import { newTaskNavigation, threadNavigation } from "../../lib/routes";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
@@ -58,7 +58,7 @@ export function NewTaskDraftScreen(props: {
const projects = useProjects();
const createProjectThread = useCreateProjectThread();
const flow = useNewTaskFlow();
const router = useRouter();
const navigation = useAppNavigation();
const insets = useSafeAreaInsets();
const colorScheme = useColorScheme();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
@@ -101,13 +101,13 @@ export function NewTaskDraftScreen(props: {
return;
}
router.replace("/new");
navigation.replace(newTaskNavigation());
}, [
logicalProjects,
projects,
props.initialProjectRef?.environmentId,
props.initialProjectRef?.projectId,
router,
navigation,
selectedProject,
setProject,
]);
@@ -429,20 +429,20 @@ export function NewTaskDraftScreen(props: {
flow.setPrompt("");
flow.clearAttachments();
router.replace(buildThreadRoutePath(result.value));
navigation.replace(threadNavigation(result.value));
}
if (!selectedProject) {
return (
<View className="flex-1 bg-sheet">
<Stack.Screen options={{ title: "Loading task" }} />
<NativeStackScreenOptions options={{ title: "Loading task" }} />
</View>
);
}
return (
<View className="flex-1 bg-sheet">
<Stack.Screen options={{ title: selectedProject.title }} />
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
<KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
<View style={{ flex: 1, minHeight: 0, paddingHorizontal: 20, paddingTop: 8 }}>
@@ -26,6 +26,7 @@ import {
} from "react-native";
import ImageViewing from "react-native-image-viewing";
import { useThemeColor } from "../../lib/useThemeColor";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { AppText as Text } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
@@ -76,6 +77,7 @@ export interface ThreadComposerProps {
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly placeholder: string;
readonly contentMaxWidth?: number;
readonly bottomInset?: number;
readonly connectionState: RemoteClientConnectionState;
readonly connectionError: string | null;
@@ -208,6 +210,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const inputRef = props.editorRef ?? fallbackInputRef;
const [isFocused, setIsFocused] = useState(false);
const wasExpandedBeforePreviewRef = useRef(false);
const inFlightThreadIdsRef = useRef(new Set<string>());
const { onExpandedChange } = props;
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
@@ -447,9 +450,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
// ── Handle command selection ──────────────────────────────
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
const handleSend = useCallback(() => {
void onSendMessage();
}, [onSendMessage]);
const handleSend = useCallback(async () => {
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
if (inFlightThreadIdsRef.current.has(threadKey)) return;
inFlightThreadIdsRef.current.add(threadKey);
try {
await onSendMessage();
} finally {
inFlightThreadIdsRef.current.delete(threadKey);
}
}, [onSendMessage, props.environmentId, props.selectedThread.id]);
const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => {
if (!composerTrigger) return;
@@ -629,7 +639,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
}}
>
<View className="w-full" style={{ position: "relative" }}>
<View
className="w-full"
style={{ alignSelf: "center", maxWidth: props.contentMaxWidth, position: "relative" }}
>
{composerTrigger && composerMenuItems.length > 0 ? (
<View
style={{
@@ -702,6 +715,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
placeholder={props.placeholder}
onFocus={handleFocus}
onBlur={handleBlur}
onSubmit={handleSend}
scrollEnabled={isExpanded}
contentInsetVertical={isExpanded ? 0 : 6}
style={
@@ -15,7 +15,7 @@ import type {
} from "@t3tools/contracts";
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import * as Haptics from "expo-haptics";
import { useHeaderHeight } from "expo-router/build/react-navigation/elements";
import { useHeaderHeight } from "@react-navigation/elements";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
@@ -27,7 +27,7 @@ import { AppText as Text } from "../../components/AppText";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { LayoutVariant } from "../../lib/layout";
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
import { scopedThreadKey } from "../../lib/scopedEntities";
import type {
PendingApproval,
@@ -69,6 +69,9 @@ export interface ThreadDetailScreenProps {
readonly selectedThreadQueueCount: number;
readonly serverConfig: T3ServerConfig | null;
readonly layoutVariant?: LayoutVariant;
readonly nativeHeaderContentTopInset?: number;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onOpenDrawer: () => void;
readonly onOpenConnectionEditor: () => void;
readonly onChangeDraftMessage: (value: string) => void;
@@ -234,6 +237,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
const nativeHeaderContentTopInset =
props.nativeHeaderContentTopInset ??
Math.max(headerHeight, insets.top + (isSplitLayout ? 88 : 92));
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
const selectedProviderSkills = useMemo(
@@ -382,9 +389,12 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={headerHeight}
contentTopInset={props.usesAutomaticContentInsets ? nativeHeaderContentTopInset : 0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
/>
</View>
@@ -398,39 +408,46 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
<View
ref={composerOverlayRef}
onLayout={onComposerLayout}
style={{ width: "100%", paddingTop: 8 }}
>
<View style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
) : null}
</View>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
+109 -48
View File
@@ -4,7 +4,7 @@ import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { SymbolView } from "expo-symbols";
import { useRouter } from "expo-router";
import { useAppNavigation } from "../../navigation/native-stack-header";
import {
memo,
useCallback,
@@ -25,6 +25,10 @@ import {
ActivityIndicator,
Image,
Linking,
Platform,
type LayoutChangeEvent,
type NativeScrollEvent,
type NativeSyntheticEvent,
Pressable,
ScrollView,
StyleSheet,
@@ -35,9 +39,10 @@ import {
View,
} from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import { ScrollViewMarker } from "react-native-screens";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { SharedValue } from "react-native-reanimated";
import { type SharedValue } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import {
@@ -63,7 +68,8 @@ import {
} from "../review/nativeReviewDiffAdapter";
import { buildReviewParsedDiff } from "../review/reviewModel";
import { cn } from "../../lib/cn";
import type { LayoutVariant } from "../../lib/layout";
import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
@@ -82,6 +88,7 @@ const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
});
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
function formatMessageTime(input: string): string {
const timestamp = Date.parse(input);
@@ -105,7 +112,10 @@ export interface ThreadFeedProps {
readonly contentInsetEndAdjustment: SharedValue<number>;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
readonly contentMaxWidth?: number;
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
}
@@ -1115,13 +1125,17 @@ function ThreadFeedPlaceholder(props: {
}
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const router = useRouter();
const navigation = useAppNavigation();
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const foldSettleFrameRef = useRef<number | null>(null);
const foldSettleSecondFrameRef = useRef<number | null>(null);
const disclosureAnchorKeyRef = useRef<string | null>(null);
const headerMaterialVisibleRef = useRef(false);
const previousLatestTurnRef = useRef(props.latestTurn);
const { width: viewportWidth } = useWindowDimensions();
const { width: windowWidth } = useWindowDimensions();
const [viewportWidth, setViewportWidth] = useState(() =>
props.layoutVariant === "split" ? 0 : windowWidth,
);
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
@@ -1140,12 +1154,19 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
headers?: Record<string, string>;
} | null>(null);
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 2);
const contentHorizontalPadding = deriveCenteredContentHorizontalPadding({
viewportWidth,
maxContentWidth: props.contentMaxWidth ?? null,
minimumPadding: horizontalPadding,
});
const contentWidth = Math.max(0, viewportWidth - contentHorizontalPadding * 2);
const userBubbleMaxWidth = contentWidth * 0.85;
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
const insets = useSafeAreaInsets();
const topContentInset = props.contentTopInset ?? insets.top + 44;
const bottomContentInset = props.contentBottomInset ?? 18;
const usesNativeAutomaticInsets =
props.usesAutomaticContentInsets === true && Platform.OS === "ios";
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const userBubbleColor = useThemeColor("--color-user-bubble");
@@ -1159,7 +1180,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
if (relativePath) {
void Haptics.selectionAsync();
router.push(
navigation.push(
buildThreadFilesNavigation(
{ environmentId: props.environmentId, threadId: props.threadId },
relativePath,
@@ -1174,7 +1195,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
void Linking.openURL(presentation.href);
}
},
[props.environmentId, props.threadId, props.workspaceRoot, router],
[props.environmentId, props.threadId, props.workspaceRoot, navigation],
);
const markdownStyles = useMarkdownStyles(onMarkdownLinkPress);
const reviewCommentColors = useReviewCommentColors();
@@ -1188,6 +1209,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
markdownStyles,
reviewCommentColors,
userBubbleColor,
viewportWidth,
}),
[
copiedRowId,
@@ -1196,8 +1218,34 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
markdownStyles,
reviewCommentColors,
userBubbleColor,
viewportWidth,
],
);
const reportHeaderMaterialVisibility = useCallback(
(visible: boolean) => {
if (headerMaterialVisibleRef.current === visible) {
return;
}
headerMaterialVisibleRef.current = visible;
props.onHeaderMaterialVisibilityChange?.(visible);
},
[props.onHeaderMaterialVisibilityChange],
);
const handleScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + topContentInset > 6);
},
[reportHeaderMaterialVisibility, topContentInset],
);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
}, []);
useEffect(() => {
reportHeaderMaterialVisibility(false);
}, [props.threadId, reportHeaderMaterialVisibility]);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
@@ -1217,6 +1265,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
),
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
);
const anchoredEndSpace = useMemo(
() =>
resolveChatListAnchoredEndSpace(
@@ -1451,47 +1500,59 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
return (
<>
<View style={{ flex: 1 }}>
<KeyboardAwareLegendList
ref={props.listRef}
key={props.threadId}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={false}
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
freeze={props.freeze}
maintainScrollAtEnd={
disclosureToggleSettling
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
<View style={{ flex: 1 }} onLayout={handleViewportLayout}>
<ScrollViewMarker style={{ flex: 1 }} scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}>
<KeyboardAwareLegendList
ref={props.listRef}
key={props.threadId}
style={{ flex: 1 }}
contentInsetAdjustmentBehavior={usesNativeAutomaticInsets ? "automatic" : "never"}
automaticallyAdjustsScrollIndicatorInsets={usesNativeAutomaticInsets}
{...(usesNativeAutomaticInsets
? {
contentInset: { top: topContentInset, left: 0, right: 0, bottom: 0 },
scrollIndicatorInsets: { top: 0, left: 0, right: 0, bottom: 0 },
}
}
maintainVisibleContentPosition={maintainVisibleContentPosition}
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
keyExtractor={(entry) => entry.id}
getItemType={(entry) =>
entry.type === "message" ? `message:${entry.message.role}` : entry.type
}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
estimatedItemSize={180}
initialScrollAtEnd
ListHeaderComponent={<View style={{ height: topContentInset }} />}
contentContainerStyle={{
paddingTop: 12,
paddingHorizontal: horizontalPadding,
}}
/>
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
freeze={props.freeze}
maintainScrollAtEnd={
disclosureToggleSettling
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
maintainVisibleContentPosition={maintainVisibleContentPosition}
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
keyExtractor={(entry) => entry.id}
getItemType={(entry) =>
entry.type === "message" ? `message:${entry.message.role}` : entry.type
}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
estimatedItemSize={180}
initialScrollAtEnd
onScroll={handleScroll}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
}
contentContainerStyle={{
paddingTop: 12,
paddingHorizontal: contentHorizontalPadding,
}}
/>
</ScrollViewMarker>
{props.feed.length === 0 ? (
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
<ThreadFeedPlaceholder
@@ -10,11 +10,16 @@ import {
requiresDefaultBranchConfirmation,
resolveQuickAction,
} from "@t3tools/client-runtime/state/vcs";
import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack";
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
import { NativeHeaderToolbar } from "../../navigation/native-stack-header";
import { useCallback, useMemo } from "react";
import { Alert } from "react-native";
import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
import {
buildGitConfirmNavigation,
buildGitOverviewNavigation,
buildThreadFilesNavigation,
buildThreadReviewNavigation,
} from "../../lib/routes";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import {
basename,
@@ -65,7 +70,24 @@ function compactMenuStatus(gitStatus: VcsStatusResult | null): string {
return parts.join(" · ");
}
export function ThreadGitControls(props: {
type HeaderItem = Record<string, unknown>;
type HeaderItems = HeaderItem[];
type ThreadGitHeaderActionItems = {
readonly terminal: HeaderItem;
readonly files: HeaderItem;
readonly git: HeaderItem;
};
type QuickActionIcon =
| "arrow.down.circle"
| "arrow.up.right.circle"
| "checkmark.circle"
| "arrow.up.circle";
type ThreadGitControlsProps = {
readonly auxiliaryPaneControl?: {
readonly accessibilityLabel: string;
readonly onPress: () => void;
};
readonly currentBranch: string | null;
readonly gitStatus: VcsStatusResult | null;
readonly gitOperationLabel: string | null;
@@ -73,14 +95,20 @@ export function ThreadGitControls(props: {
readonly canOpenFiles: boolean;
readonly projectScripts: ReadonlyArray<ProjectScript>;
readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
readonly showActionControls?: boolean;
readonly showDirectFileControl?: boolean;
readonly onOpenFilesInspector?: () => void;
readonly onOpenGitInspector?: () => void;
readonly onOpenTerminal: (terminalId?: string | null) => void;
readonly onOpenNewTerminal: () => void;
readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
readonly onPull: () => Promise<void>;
readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
}) {
const router = useRouter();
const { environmentId, threadId } = useLocalSearchParams<{
};
function useThreadGitControlModel(props: ThreadGitControlsProps) {
const navigation = useAppNavigation();
const { environmentId, threadId } = useRouteParams<{
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
@@ -109,7 +137,7 @@ export function ThreadGitControls(props: {
? (quickAction.hint ?? "This action is unavailable.")
: null;
const quickActionIcon = (() => {
const quickActionIcon: QuickActionIcon = (() => {
if (quickAction.kind === "run_pull") return "arrow.down.circle";
if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
if (quickAction.kind === "run_action") {
@@ -147,24 +175,24 @@ export function ThreadGitControls(props: {
!input.featureBranch &&
requiresDefaultBranchConfirmation(input.action, isDefaultRef)
) {
router.push({
pathname: "/threads/[environmentId]/[threadId]/git-confirm",
params: {
environmentId,
threadId,
confirmAction: confirmableAction,
branchName,
includesCommit: String(
input.action === "commit_push" || input.action === "commit_push_pr",
),
},
});
navigation.push(
buildGitConfirmNavigation(
{ environmentId, threadId },
{
confirmAction: confirmableAction,
branchName,
includesCommit: String(
input.action === "commit_push" || input.action === "commit_push_pr",
),
},
),
);
return;
}
await onRunAction(input);
},
[environmentId, gitStatus, isDefaultRef, onRunAction, router, threadId],
[environmentId, gitStatus, isDefaultRef, onRunAction, navigation, threadId],
);
const runQuickAction = useCallback(async () => {
@@ -181,102 +209,335 @@ export function ThreadGitControls(props: {
}
}, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
return (
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="terminal" disabled={!props.canOpenTerminal} separateBackground>
{props.projectScripts.length > 0 ? (
props.projectScripts.map((script) => (
<Stack.Toolbar.MenuAction
key={script.id}
icon={projectScriptMenuIcon(script.icon)}
onPress={() => void props.onRunProjectScript(script)}
subtitle={script.command}
>
<Stack.Toolbar.Label>{projectScriptMenuLabel(script)}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))
) : (
<Stack.Toolbar.MenuAction
icon="play"
disabled
onPress={() => {}}
subtitle="This project has no saved scripts yet"
>
<Stack.Toolbar.Label>No project scripts</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
)}
{props.terminalSessions.map((session) => (
<Stack.Toolbar.MenuAction
key={session.terminalId}
icon="terminal"
onPress={() => props.onOpenTerminal(session.terminalId)}
subtitle={[
getTerminalStatusLabel({
status: session.status,
hasRunningSubprocess: session.hasRunningSubprocess,
}),
basename(session.cwd),
]
.filter(Boolean)
.join(" · ")}
>
<Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
<Stack.Toolbar.MenuAction
icon="plus"
onPress={props.onOpenNewTerminal}
subtitle="Start another shell for this thread"
>
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
<Stack.Toolbar.MenuAction
icon="point.topleft.down.curvedto.point.bottomright.up"
disabled
onPress={() => {}}
subtitle={compactMenuStatus(gitStatus)}
>
<Stack.Toolbar.Label>{compactMenuBranchLabel(currentBranchLabel)}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon={quickActionIcon}
disabled={quickAction.disabled}
onPress={() => void runQuickAction()}
subtitle={quickActionHint ?? undefined}
>
<Stack.Toolbar.Label>{quickAction.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon="text.bubble"
disabled={!isRepo}
onPress={() => router.push(buildThreadReviewRoutePath({ environmentId, threadId }))}
subtitle="Turn diffs and worktree changes"
>
<Stack.Toolbar.Label>Review changes</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon="folder"
disabled={!props.canOpenFiles}
onPress={() => router.push(buildThreadFilesNavigation({ environmentId, threadId }))}
subtitle="Browse this workspace"
>
<Stack.Toolbar.Label>Files</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon="ellipsis.circle"
onPress={() =>
router.push({
pathname: "/threads/[environmentId]/[threadId]/git",
params: { environmentId, threadId },
})
}
subtitle="Commit, files, branches"
>
<Stack.Toolbar.Label>More</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
const openFiles = useCallback(() => {
if (props.onOpenFilesInspector) {
props.onOpenFilesInspector();
return;
}
navigation.push(buildThreadFilesNavigation({ environmentId, threadId }));
}, [environmentId, props.onOpenFilesInspector, navigation, threadId]);
const openReview = useCallback(() => {
navigation.push(buildThreadReviewNavigation({ environmentId, threadId }));
}, [environmentId, navigation, threadId]);
const openGitInspector = useCallback(() => {
if (props.onOpenGitInspector) {
props.onOpenGitInspector();
return;
}
navigation.push(buildGitOverviewNavigation({ environmentId, threadId }));
}, [environmentId, props.onOpenGitInspector, navigation, threadId]);
return {
currentBranchLabel,
isRepo,
openFiles,
openGitInspector,
openReview,
quickAction,
quickActionHint,
quickActionIcon,
runQuickAction,
};
}
function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGitHeaderActionItems {
const model = useThreadGitControlModel(props);
return useMemo(
() => ({
terminal: {
accessibilityLabel: "Open terminal",
disabled: !props.canOpenTerminal,
icon: { name: "terminal", type: "sfSymbol" },
identifier: "thread-right-terminal",
label: "Terminal",
menu: {
items: [
...props.projectScripts.map((script) => ({
description: script.command,
icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
label: projectScriptMenuLabel(script),
onPress: () => void props.onRunProjectScript(script),
type: "action" as const,
})),
...(props.projectScripts.length === 0
? [
{
description: "This project has no saved scripts yet",
disabled: true,
icon: { name: "play", type: "sfSymbol" as const },
label: "No project scripts",
onPress: () => {},
type: "action" as const,
},
]
: []),
...props.terminalSessions.map((session) => ({
description: [
getTerminalStatusLabel({
status: session.status,
hasRunningSubprocess: session.hasRunningSubprocess,
}),
basename(session.cwd),
]
.filter(Boolean)
.join(" · "),
icon: { name: "terminal", type: "sfSymbol" as const },
label: session.displayLabel,
onPress: () => props.onOpenTerminal(session.terminalId),
type: "action" as const,
})),
{
description: "Start another shell for this thread",
icon: { name: "plus", type: "sfSymbol" },
label: "Open new terminal",
onPress: props.onOpenNewTerminal,
type: "action",
},
],
title: "Terminal",
},
sharesBackground: true,
type: "menu",
variant: "prominent",
},
files: {
accessibilityLabel: "Open files",
disabled: !props.canOpenFiles,
icon: { name: "folder", type: "sfSymbol" },
identifier: "thread-right-files",
label: "Files",
onPress: model.openFiles,
sharesBackground: true,
type: "button",
variant: "prominent",
},
git: {
accessibilityLabel: "Git actions",
icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" },
identifier: "thread-right-git",
label: "Git",
menu: {
items: [
{
description: compactMenuStatus(props.gitStatus),
disabled: true,
icon: {
name: "point.topleft.down.curvedto.point.bottomright.up",
type: "sfSymbol",
},
label: compactMenuBranchLabel(model.currentBranchLabel),
onPress: (): void => {},
type: "action",
},
{
description: model.quickActionHint ?? undefined,
disabled: model.quickAction.disabled,
icon: { name: model.quickActionIcon, type: "sfSymbol" },
label: model.quickAction.label,
onPress: (): void => void model.runQuickAction(),
type: "action",
},
{
description: "Turn diffs and worktree changes",
disabled: !model.isRepo,
icon: { name: "text.bubble", type: "sfSymbol" },
label: "Review changes",
onPress: model.openReview,
type: "action",
},
{
description: "Browse this workspace",
disabled: !props.canOpenFiles,
icon: { name: "folder", type: "sfSymbol" },
label: "Files",
onPress: model.openFiles,
type: "action",
},
{
description: "Commit, files, branches",
icon: { name: "ellipsis.circle", type: "sfSymbol" },
label: "More",
onPress: model.openGitInspector,
type: "action",
},
],
title: "Git",
},
sharesBackground: true,
type: "menu",
variant: "prominent",
},
}),
[
model.currentBranchLabel,
model.isRepo,
model.openFiles,
model.openGitInspector,
model.openReview,
model.quickAction.disabled,
model.quickAction.label,
model.quickActionHint,
model.quickActionIcon,
model.runQuickAction,
props.canOpenFiles,
props.canOpenTerminal,
props.gitStatus,
props.onOpenNewTerminal,
props.onOpenTerminal,
props.onRunProjectScript,
props.projectScripts,
props.terminalSessions,
],
);
}
export function useThreadGitRightHeaderItems(props: ThreadGitControlsProps): HeaderItems {
const actionItems = useThreadGitHeaderActionItems(props);
return useMemo(
() => [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems,
[actionItems],
);
}
export function useThreadGitCenterHeaderItems(props: ThreadGitControlsProps): HeaderItems {
const actionItems = useThreadGitHeaderActionItems(props);
return useMemo(
() => [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems,
[actionItems],
);
}
export function ThreadGitControls(props: ThreadGitControlsProps) {
const model = useThreadGitControlModel(props);
const showActionControls = props.showActionControls ?? true;
if (!showActionControls) {
return null;
}
return (
<NativeHeaderToolbar placement="right">
{showActionControls && props.auxiliaryPaneControl ? (
<NativeHeaderToolbar.Button
accessibilityLabel={props.auxiliaryPaneControl.accessibilityLabel}
icon="sidebar.right"
onPress={props.auxiliaryPaneControl.onPress}
separateBackground
/>
) : null}
{showActionControls ? (
<NativeHeaderToolbar.Menu
icon="terminal"
disabled={!props.canOpenTerminal}
separateBackground
>
{props.projectScripts.length > 0 ? (
props.projectScripts.map((script) => (
<NativeHeaderToolbar.MenuAction
key={script.id}
icon={projectScriptMenuIcon(script.icon)}
onPress={() => void props.onRunProjectScript(script)}
subtitle={script.command}
>
<NativeHeaderToolbar.Label>
{projectScriptMenuLabel(script)}
</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))
) : (
<NativeHeaderToolbar.MenuAction
icon="play"
disabled
onPress={() => {}}
subtitle="This project has no saved scripts yet"
>
<NativeHeaderToolbar.Label>No project scripts</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
)}
{props.terminalSessions.map((session) => (
<NativeHeaderToolbar.MenuAction
key={session.terminalId}
icon="terminal"
onPress={() => props.onOpenTerminal(session.terminalId)}
subtitle={[
getTerminalStatusLabel({
status: session.status,
hasRunningSubprocess: session.hasRunningSubprocess,
}),
basename(session.cwd),
]
.filter(Boolean)
.join(" · ")}
>
<NativeHeaderToolbar.Label>{session.displayLabel}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
<NativeHeaderToolbar.MenuAction
icon="plus"
onPress={props.onOpenNewTerminal}
subtitle="Start another shell for this thread"
>
<NativeHeaderToolbar.Label>Open new terminal</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
) : null}
{showActionControls && props.showDirectFileControl ? (
<NativeHeaderToolbar.Button
accessibilityLabel="Open files"
disabled={!props.canOpenFiles}
icon="folder"
onPress={model.openFiles}
separateBackground
/>
) : null}
{showActionControls ? (
<NativeHeaderToolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
<NativeHeaderToolbar.MenuAction
icon="point.topleft.down.curvedto.point.bottomright.up"
disabled
onPress={() => {}}
subtitle={compactMenuStatus(props.gitStatus)}
>
<NativeHeaderToolbar.Label>
{compactMenuBranchLabel(model.currentBranchLabel)}
</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
icon={model.quickActionIcon}
disabled={model.quickAction.disabled}
onPress={() => void model.runQuickAction()}
subtitle={model.quickActionHint ?? undefined}
>
<NativeHeaderToolbar.Label>{model.quickAction.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
icon="text.bubble"
disabled={!model.isRepo}
onPress={model.openReview}
subtitle="Turn diffs and worktree changes"
>
<NativeHeaderToolbar.Label>Review changes</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
icon="folder"
disabled={!props.canOpenFiles}
onPress={model.openFiles}
subtitle="Browse this workspace"
>
<NativeHeaderToolbar.Label>Files</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
icon="ellipsis.circle"
onPress={model.openGitInspector}
subtitle="Commit, files, branches"
>
<NativeHeaderToolbar.Label>More</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
) : null}
</NativeHeaderToolbar>
);
}
@@ -8,8 +8,6 @@ import {
useWindowDimensions,
View,
} from "react-native";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
@@ -23,22 +21,11 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { StatusPill } from "../../components/StatusPill";
import { useProjects, useThreadShells } from "../../state/entities";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "./threadPresentation";
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
const threadActivityOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
title: Order.String,
}),
(thread: EnvironmentThreadShell) => ({
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
title: thread.title,
}),
);
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { buildThreadNavigationGroups } from "./thread-navigation-groups";
export function ThreadNavigationDrawer(props: {
readonly visible: boolean;
@@ -192,24 +179,9 @@ function ThreadNavigationDrawerContent(props: {
}) {
const projects = useProjects();
const threads = useThreadShells();
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const groupedThreads = useMemo(
() =>
repositoryGroups.map((group) => {
const threads: EnvironmentThreadShell[] = [];
for (const projectGroup of group.projects) {
threads.push(...projectGroup.threads);
}
return {
key: group.key,
title: group.projects[0]?.project.title ?? group.title,
threads: Arr.sort(threads, threadActivityOrder),
};
}),
[repositoryGroups],
() => buildThreadNavigationGroups({ projects, threads }),
[projects, threads],
);
return (
File diff suppressed because it is too large. Load diff
@@ -1,9 +1,37 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import {
NativeStackScreenOptions,
useFocusEffect,
useRouteParams,
useAppNavigation,
} from "../../navigation/native-stack-header";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ComponentProps,
type ReactNode,
} from "react";
import * as Option from "effect/Option";
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import {
Platform,
Pressable,
ScrollView,
Text as RNText,
View,
type NativeSyntheticEvent,
} from "react-native";
import {
Screen,
ScreenStack,
ScreenStackHeaderConfig,
ScreenStackHeaderSearchBarView,
SearchBar,
type SearchBarCommands,
} from "react-native-screens";
import { useWorkspaceState } from "../../state/workspace";
import { useThemeColor } from "../../lib/useThemeColor";
import { useEnvironmentQuery } from "../../state/query";
@@ -12,10 +40,18 @@ import { vcsEnvironment } from "../../state/vcs";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { buildThreadRoutePath, buildThreadTerminalNavigation } from "../../lib/routes";
import {
buildThreadFilesNavigation,
buildThreadTerminalNavigation,
connectionsNavigation,
homeNavigation,
newTaskNavigation,
threadNavigation,
} from "../../lib/routes";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { connectionTone } from "../connection/connectionTone";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import {
useRemoteConnections,
@@ -37,7 +73,12 @@ import {
} from "../terminal/terminalLaunchContext";
import { terminalDebugLog } from "../terminal/terminalDebugLog";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls";
import {
ThreadGitControls,
useThreadGitCenterHeaderItems,
useThreadGitRightHeaderItems,
} from "./ThreadGitControls";
import { GitOverviewSheet } from "./git/GitOverviewSheet";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
@@ -47,6 +88,37 @@ import { useSelectedThreadWorktree } from "../../state/use-selected-thread-workt
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { threadEnvironment } from "../../state/threads";
import { projectThreadContentPresentation } from "./threadContentPresentation";
import { AdaptiveInspectorLayout } from "../layout/adaptive-inspector-layout";
import {
useAdaptiveWorkspaceLayout,
useAdaptiveWorkspacePaneRole,
} from "../layout/AdaptiveWorkspaceLayout";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
import {
ThreadInspectorContentStack,
type ThreadInspectorMode,
} from "./thread-inspector-content-stack";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
interface ThreadInspectorSelection {
readonly routeThreadIdentity: string | null;
readonly mode: ThreadInspectorMode;
}
type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;
type RnsHeaderItems = ComponentProps<typeof ScreenStackHeaderConfig>["headerRightBarButtonItems"];
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
function asRnsHeaderItems(items: NativeHeaderItems | undefined): RnsHeaderItems {
return items as unknown as RnsHeaderItems;
}
function InspectorPaneRoleActivation() {
useAdaptiveWorkspacePaneRole("inspector");
return null;
}
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
@@ -60,13 +132,143 @@ function OpeningThreadLoadingScreen() {
return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
}
export function ThreadRouteScreen() {
interface ThreadRouteScreenProps {
readonly onReturnToThread?: () => void;
readonly renderInspector?: (headerInset: number) => ReactNode;
}
function ThreadUnavailableScreen() {
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
justifyContent: "center",
paddingHorizontal: 24,
paddingVertical: 32,
}}
className="bg-screen flex-1"
>
<EmptyState
title="Thread unavailable"
detail="This thread is not available in the current mobile snapshot."
/>
</ScrollView>
);
}
export function ThreadRouteScreen(props: ThreadRouteScreenProps = {}) {
const { state: workspaceState } = useWorkspaceState();
const { connectionState } = useRemoteConnectionStatus();
const { selectedThread } = useThreadSelection();
const params = useRouteParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
const environmentIdRaw = firstRouteParam(params.environmentId);
const threadIdRaw = firstRouteParam(params.threadId);
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeThreadKey =
environmentId !== null && threadIdRaw !== null
? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
: null;
const selectedThreadKey =
selectedThread === null
? null
: scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const selectedThreadDetailState = useSelectedThreadDetailState();
const hasThreadDetail = Option.isSome(selectedThreadDetailState.data);
const hasTerminalDetailState =
selectedThreadDetailState.status === "deleted" ||
Option.isSome(selectedThreadDetailState.error);
if (environmentId === null || threadIdRaw === null) {
return <OpeningThreadLoadingScreen />;
}
if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
if (!hasThreadDetail && !hasTerminalDetailState) {
return <OpeningThreadLoadingScreen />;
}
return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
}
const stillHydrating =
workspaceState.isLoadingConnections ||
routeConnectionState === "connecting" ||
routeConnectionState === "reconnecting";
if (stillHydrating) {
return <OpeningThreadLoadingScreen />;
}
return <ThreadUnavailableScreen />;
}
function ThreadHeaderTitle(props: {
readonly foregroundColor: string;
readonly secondaryForegroundColor: string;
readonly subtitle: string;
readonly title: string;
}) {
return (
<Pressable
style={{ alignItems: "center", maxWidth: 200 }}
onLongPress={() => {
// TODO: trigger rename modal
}}
>
<RNText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
fontWeight: "900",
color: props.foregroundColor,
letterSpacing: -0.4,
}}
>
{props.title}
</RNText>
<RNText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: props.secondaryForegroundColor,
letterSpacing: 0.3,
}}
>
{props.subtitle}
</RNText>
</Pressable>
);
}
function ThreadRouteContent(
props: ThreadRouteScreenProps & {
readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
},
) {
const {
fileInspector,
layout,
panes,
setPrimarySidebarSearchQuery,
showAuxiliaryPane,
toggleAuxiliaryPane,
togglePrimarySidebar,
} = useAdaptiveWorkspaceLayout();
const { connectionState } = useRemoteConnectionStatus();
const { onReconnectEnvironment } = useRemoteConnections();
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
useThreadSelection();
const selectedThreadDetailState = useSelectedThreadDetailState();
const selectedThreadDetailState = props.selectedThreadDetailState;
const threadSearchBarRef = useRef<SearchBarCommands>(null);
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
const { selectedThreadCwd } = useSelectedThreadWorktree();
const composer = useThreadComposerState();
@@ -74,8 +276,8 @@ export function ThreadRouteScreen() {
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const router = useRouter();
const params = useLocalSearchParams<{
const navigation = useAppNavigation();
const params = useRouteParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
@@ -83,6 +285,66 @@ export function ThreadRouteScreen() {
const environmentIdRaw = firstRouteParam(params.environmentId);
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
const threadId = firstRouteParam(params.threadId);
const routeThreadIdentity =
environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
() => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
);
const inspectorMode = (() => {
if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
return null;
}
return inspectorSelection.mode;
}
return null;
})();
useEffect(() => {
if (
fileInspector.supported &&
selectedThreadCwd === null &&
inspectorMode === null &&
panes.auxiliaryPaneVisible
) {
toggleAuxiliaryPane();
}
}, [
fileInspector.supported,
inspectorMode,
panes.auxiliaryPaneVisible,
selectedThreadCwd,
toggleAuxiliaryPane,
]);
useEffect(() => {
setInspectorSelection((current) => {
if (props.renderInspector === undefined) {
if (current === null || current.mode === "route") {
return null;
}
return { ...current, routeThreadIdentity };
}
if (current === null || current.mode === "route") {
return { routeThreadIdentity, mode: "route" };
}
return { ...current, routeThreadIdentity };
});
}, [props.renderInspector, routeThreadIdentity]);
useFocusEffect(
useCallback(() => {
return () => {
if (props.renderInspector === undefined) {
// Inspectors are contextual to this chat destination. Clear the
// hidden chat copy after a native push so returning from Files,
// Review, or Terminal cannot reserve an empty trailing pane.
setInspectorSelection(null);
}
};
}, [props.renderInspector]),
);
const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
@@ -104,7 +366,24 @@ export function ThreadRouteScreen() {
const iconColor = String(useThemeColor("--color-icon"));
const foregroundColor = String(useThemeColor("--color-foreground"));
const secondaryFg = String(useThemeColor("--color-foreground-secondary"));
const screenBackgroundColor = String(useThemeColor("--color-screen"));
const usesNativeHeaderGlass = Platform.OS === "ios";
const usesThreadSearchToolbar =
Platform.OS === "ios" && layout.usesSplitView && inspectorMode === null;
const focusThreadSearch = useCallback(() => {
if (!usesThreadSearchToolbar) {
return false;
}
threadSearchBarRef.current?.focus();
return true;
}, [usesThreadSearchToolbar]);
useHardwareKeyboardCommand("focusSearch", focusThreadSearch);
const headerSubtitle = [
selectedThreadProject?.title ?? null,
selectedEnvironmentConnection?.environmentLabel ?? null,
]
.filter(Boolean)
.join(" · ");
/* ─── Git status for native header trigger ───────────────────────── */
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
@@ -145,12 +424,106 @@ export function ThreadRouteScreen() {
const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
const handleOpenDrawer = useCallback(() => {
setDrawerVisible(true);
if (!layout.usesSplitView) {
setDrawerVisible(true);
}
}, [layout.usesSplitView]);
useEffect(() => {
if (layout.usesSplitView) {
setDrawerVisible(false);
}
}, [layout.usesSplitView]);
const handleOpenGitInspector = useCallback(() => {
setInspectorSelection({ routeThreadIdentity, mode: "git" });
showAuxiliaryPane("inspector");
}, [routeThreadIdentity, showAuxiliaryPane]);
const handleOpenFilesInspector = useCallback(() => {
if (!fileInspector.supported || selectedThread === null || selectedThreadCwd === null) {
return;
}
setInspectorSelection({
routeThreadIdentity,
mode: props.renderInspector === undefined ? "files" : "route",
});
showAuxiliaryPane("inspector");
}, [
fileInspector.supported,
props.renderInspector,
routeThreadIdentity,
selectedThread,
selectedThreadCwd,
showAuxiliaryPane,
]);
const inspectorToggleActionRef = useRef({
inspectorMode,
openFilesInspector: handleOpenFilesInspector,
toggleAuxiliaryPane,
});
inspectorToggleActionRef.current = {
inspectorMode,
openFilesInspector: handleOpenFilesInspector,
toggleAuxiliaryPane,
};
const handleToggleInspector = useCallback(() => {
const action = inspectorToggleActionRef.current;
if (action.inspectorMode === null) {
action.openFilesInspector();
return;
}
action.toggleAuxiliaryPane();
}, []);
const handleSelectInspectorFile = useCallback(
(path: string) => {
if (selectedThread === null) {
return;
}
const destination = buildThreadFilesNavigation(selectedThread, path);
if (fileInspector.supported) {
navigation.replace(destination);
return;
}
navigation.push(destination);
},
[fileInspector.supported, navigation, selectedThread],
);
const GitInspector = useCallback(
() => <GitOverviewSheet headerInset={0} presentation="inspector" />,
[],
);
const FilesInspector = useCallback(
() =>
selectedThread !== null && selectedThreadCwd !== null ? (
<ThreadFileNavigatorPane
cwd={selectedThreadCwd}
environmentId={selectedThread.environmentId}
headerInset={0}
projectName={selectedThreadProject?.title ?? "Files"}
selectedPath={null}
onSelectFile={handleSelectInspectorFile}
/>
) : null,
[handleSelectInspectorFile, selectedThread, selectedThreadCwd, selectedThreadProject?.title],
);
const RouteInspector = useCallback(() => props.renderInspector?.(0), [props.renderInspector]);
const renderInspectorStack = useCallback(
() =>
inspectorMode === null ? null : (
<ThreadInspectorContentStack
Files={FilesInspector}
Git={GitInspector}
mode={inspectorMode}
Route={props.renderInspector ? RouteInspector : undefined}
/>
),
[FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
);
const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
const handleOpenConnectionEditor = useCallback(() => {
void router.push("/connections");
}, [router]);
void navigation.push(connectionsNavigation());
}, [navigation]);
const handleStopThread = useCallback(() => {
if (
!selectedThread ||
@@ -182,9 +555,9 @@ export function ThreadRouteScreen() {
return;
}
void router.push(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
void navigation.push(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
},
[router, selectedThread, selectedThreadProject?.workspaceRoot],
[navigation, selectedThread, selectedThreadProject?.workspaceRoot],
);
const handleOpenNewTerminal = useCallback(() => {
@@ -201,8 +574,8 @@ export function ThreadRouteScreen() {
const nextId = nextOpenTerminalId({
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
});
void router.push(buildThreadTerminalNavigation(selectedThread, nextId));
}, [router, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
void navigation.push(buildThreadTerminalNavigation(selectedThread, nextId));
}, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
const handleRunProjectScript = useCallback(
async (script: ProjectScript) => {
@@ -259,48 +632,109 @@ export function ThreadRouteScreen() {
worktreePath: preferredWorktreePath,
});
void router.push(buildThreadTerminalNavigation(selectedThread, targetTerminalId));
void navigation.push(buildThreadTerminalNavigation(selectedThread, targetTerminalId));
},
[
router,
navigation,
selectedThread,
selectedThreadDetailWorktreePath,
selectedThreadProject,
terminalMenuSessions,
],
);
const threadGitControlProps = {
auxiliaryPaneControl:
!layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
? {
accessibilityLabel: "Toggle inspector",
onPress: handleToggleInspector,
}
: undefined,
onOpenFilesInspector:
fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
currentBranch: selectedThread?.branch ?? null,
gitStatus: gitStatus.data,
gitOperationLabel: gitState.gitOperationLabel,
canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
projectScripts: selectedThreadProject?.scripts ?? [],
terminalSessions: terminalMenuSessions,
showDirectFileControl: layout.usesSplitView,
onOpenTerminal: handleOpenTerminal,
onOpenNewTerminal: handleOpenNewTerminal,
onRunProjectScript: handleRunProjectScript,
onPull: gitActions.onPullSelectedThreadBranch,
onRunAction: gitActions.onRunSelectedThreadGitAction,
};
const threadCenterHeaderItems = useThreadGitCenterHeaderItems(threadGitControlProps);
const compactRightHeaderItems = useThreadGitRightHeaderItems(threadGitControlProps);
const compactLeftHeaderItems = useMemo<NativeHeaderItems>(
() => [
withNativeGlassHeaderItem({
accessibilityLabel: "Back to threads",
icon: { name: "chevron.left", type: "sfSymbol" as const },
identifier: "thread-compact-back",
onPress: () => {
if (navigation.canGoBack()) {
navigation.back();
return;
}
navigation.replace(homeNavigation());
},
type: "button" as const,
}),
],
[navigation],
);
const splitLeftHeaderItems = useMemo<NativeHeaderItems>(
() => [
{
// Match Mail's split-view detail toolbar: the first detail action sits
// inside the content pane, not flush against the sidebar divider.
spacing: 18,
type: "spacing" as const,
},
...(props.onReturnToThread
? [
withNativeGlassHeaderItem({
accessibilityLabel: "Return to chat",
icon: { name: "chevron.left", type: "sfSymbol" as const },
identifier: "thread-left-return",
onPress: props.onReturnToThread,
type: "button" as const,
}),
]
: []),
withNativeGlassHeaderItem({
accessibilityLabel: panes.primarySidebarVisible
? "Maximize content"
: "Show thread sidebar",
icon: {
name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
type: "sfSymbol" as const,
},
identifier: "thread-left-sidebar",
onPress: togglePrimarySidebar,
type: "button" as const,
}),
withNativeGlassHeaderItem({
accessibilityLabel: "New task",
icon: { name: "square.and.pencil", type: "sfSymbol" as const },
identifier: "thread-left-new-task",
onPress: () => navigation.push(newTaskNavigation()),
type: "button" as const,
}),
],
[panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
);
if (!environmentId || !threadId) {
return <OpeningThreadLoadingScreen />;
}
if (!selectedThread) {
const stillHydrating =
workspaceState.isLoadingConnections ||
routeConnectionState === "connecting" ||
routeConnectionState === "reconnecting";
if (stillHydrating) {
return <OpeningThreadLoadingScreen />;
}
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
justifyContent: "center",
paddingHorizontal: 24,
paddingVertical: 32,
}}
className="bg-screen flex-1"
>
<EmptyState
title="Thread unavailable"
detail="This thread is not available in the current mobile snapshot."
/>
</ScrollView>
);
return <OpeningThreadLoadingScreen />;
}
const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
@@ -311,129 +745,204 @@ export function ThreadRouteScreen() {
connectionState: routeConnectionState,
});
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const headerSubtitle = [
selectedThreadProject?.title ?? null,
selectedEnvironmentConnection?.environmentLabel ?? null,
]
.filter(Boolean)
.join(" · ");
return (
const renderThreadRouteBody = (showActionControls: boolean) => (
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerBackTitle: "",
headerTitle: () => (
<Pressable
style={{ alignItems: "center", maxWidth: 200 }}
onLongPress={() => {
// TODO: trigger rename modal
}}
>
<RNText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
fontWeight: "900",
color: foregroundColor,
letterSpacing: -0.4,
}}
>
{selectedThread.title}
</RNText>
<RNText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
fontWeight: "700",
color: secondaryFg,
letterSpacing: 0.3,
}}
>
{headerSubtitle}
</RNText>
</Pressable>
),
}}
/>
<ThreadGitControls
currentBranch={selectedThread.branch}
gitStatus={gitStatus.data}
gitOperationLabel={gitState.gitOperationLabel}
canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
canOpenFiles={Boolean(selectedThreadProject?.workspaceRoot)}
projectScripts={selectedThreadProject?.scripts ?? []}
terminalSessions={terminalMenuSessions}
onOpenTerminal={handleOpenTerminal}
onOpenNewTerminal={handleOpenNewTerminal}
onRunProjectScript={handleRunProjectScript}
onPull={gitActions.onPullSelectedThreadBranch}
onRunAction={gitActions.onRunSelectedThreadGitAction}
/>
<ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
<GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
activeWorkStartedAt={composer.activeWorkStartedAt}
activePendingApproval={requests.activePendingApproval}
respondingApprovalId={requests.respondingApprovalId}
activePendingUserInput={requests.activePendingUserInput}
activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
respondingUserInputId={requests.respondingUserInputId}
draftMessage={composer.draftMessage}
draftAttachments={composer.draftAttachments}
connectionStateLabel={routeConnectionState}
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
onOpenDrawer={handleOpenDrawer}
onOpenConnectionEditor={handleOpenConnectionEditor}
onChangeDraftMessage={composer.onChangeDraftMessage}
onPickDraftImages={composer.onPickDraftImages}
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
serverConfig={serverConfig}
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
onSubmitUserInput={requests.onSubmitUserInput}
/>
<AdaptiveInspectorLayout renderInspector={activeInspectorRenderer}>
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
activeWorkStartedAt={composer.activeWorkStartedAt}
activePendingApproval={requests.activePendingApproval}
respondingApprovalId={requests.respondingApprovalId}
activePendingUserInput={requests.activePendingUserInput}
activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
respondingUserInputId={requests.respondingUserInputId}
draftMessage={composer.draftMessage}
draftAttachments={composer.draftAttachments}
connectionStateLabel={routeConnectionState}
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
layoutVariant={layout.variant}
usesAutomaticContentInsets={usesNativeHeaderGlass}
onOpenDrawer={handleOpenDrawer}
onOpenConnectionEditor={handleOpenConnectionEditor}
onChangeDraftMessage={composer.onChangeDraftMessage}
onPickDraftImages={composer.onPickDraftImages}
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
serverConfig={serverConfig}
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
onSubmitUserInput={requests.onSubmitUserInput}
/>
<ThreadNavigationDrawer
visible={drawerVisible}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
router.replace(buildThreadRoutePath(thread));
}}
onStartNewTask={() => router.push("/new")}
/>
</View>
{layout.usesSplitView ? null : (
<ThreadNavigationDrawer
visible={drawerVisible}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
navigation.replace(threadNavigation(thread));
}}
onStartNewTask={() => navigation.push(newTaskNavigation())}
/>
)}
</View>
</AdaptiveInspectorLayout>
</>
);
if (usesNativeHeaderGlass) {
return (
<>
{activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
<NativeStackScreenOptions options={{ headerShown: false }} />
<ScreenStack style={{ flex: 1 }}>
<Screen
activityState={2}
enabled
hasLargeHeader={false}
isNativeStack
screenId={`thread-detail-${selectedThreadKey}`}
scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
style={{ flex: 1, backgroundColor: screenBackgroundColor }}
>
{renderThreadRouteBody(false)}
<ScreenStackHeaderConfig
backgroundColor="rgba(0,0,0,0)"
color={iconColor}
headerCenterBarButtonItems={asRnsHeaderItems(
layout.usesSplitView ? threadCenterHeaderItems : undefined,
)}
headerLeftBarButtonItems={asRnsHeaderItems(
layout.usesSplitView ? splitLeftHeaderItems : compactLeftHeaderItems,
)}
headerRightBarButtonItems={asRnsHeaderItems(
layout.usesSplitView ? undefined : compactRightHeaderItems,
)}
hideBackButton
hideShadow={false}
navigationItemStyle="editor"
subtitle={headerSubtitle}
title={selectedThread.title}
titleColor={foregroundColor}
titleFontSize={17}
titleFontWeight="800"
translucent
>
{usesThreadSearchToolbar ? (
<ScreenStackHeaderSearchBarView>
<SearchBar
allowToolbarIntegration
autoCapitalize="none"
hideNavigationBar={false}
obscureBackground={false}
onCancelButtonPress={() => {
setPrimarySidebarSearchQuery("");
}}
onChangeText={(event: NativeSyntheticEvent<{ readonly text?: string }>) => {
setPrimarySidebarSearchQuery(event.nativeEvent.text ?? "");
}}
placement="integratedButton"
placeholder="Search"
textColor={foregroundColor}
tintColor={iconColor}
/>
</ScreenStackHeaderSearchBarView>
) : null}
</ScreenStackHeaderConfig>
</Screen>
</ScreenStack>
</>
);
}
return (
<>
{activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
<NativeStackScreenOptions
options={{
headerShown: true,
headerTransparent: usesNativeHeaderGlass,
headerShadowVisible: false,
...(usesNativeHeaderGlass
? { headerStyle: { backgroundColor: "transparent" } }
: {
headerStyle: { backgroundColor: screenBackgroundColor },
headerShadowVisible: false,
}),
headerTintColor: iconColor,
headerTitle: layout.usesSplitView ? () => null : selectedThread.title,
headerTitleStyle: usesNativeHeaderGlass
? {
fontSize: 17,
fontWeight: "800",
}
: undefined,
title: layout.usesSplitView ? "" : selectedThread.title,
headerBackVisible: !layout.usesSplitView,
headerBackTitle: "",
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
headerSearchBarOptions: usesThreadSearchToolbar
? {
ref: threadSearchBarRef,
allowToolbarIntegration: true,
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
onCancelButtonPress: () => {
setPrimarySidebarSearchQuery("");
},
onChangeText: (event) => {
setPrimarySidebarSearchQuery(event.nativeEvent.text);
},
placeholder: "Search",
placement: "integratedButton",
}
: undefined,
unstable_headerLeftItems:
layout.usesSplitView && Platform.OS === "ios" ? () => splitLeftHeaderItems : undefined,
unstable_headerCenterItems:
layout.usesSplitView && Platform.OS === "ios"
? () => threadCenterHeaderItems
: undefined,
unstable_headerSubtitle: undefined,
unstable_navigationItemStyle: usesNativeHeaderGlass ? "editor" : undefined,
}}
/>
{layout.usesSplitView || usesNativeHeaderGlass ? null : (
<NativeStackScreenOptions.Title asChild>
<ThreadHeaderTitle
foregroundColor={foregroundColor}
secondaryForegroundColor={secondaryFg}
subtitle={headerSubtitle}
title={selectedThread.title}
/>
</NativeStackScreenOptions.Title>
)}
{renderThreadRouteBody(!layout.usesSplitView)}
</>
);
}
@@ -1,5 +1,5 @@
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { useRouter } from "expo-router";
import { useAppNavigation } from "../../../navigation/native-stack-header";
import { useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -15,7 +15,7 @@ import { vcsEnvironment } from "../../../state/vcs";
import { SheetActionButton } from "./gitSheetComponents";
export function GitBranchesSheet() {
const router = useRouter();
const navigation = useAppNavigation();
const insets = useSafeAreaInsets();
const { selectedThread } = useThreadSelection();
const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
@@ -96,7 +96,7 @@ export function GitBranchesSheet() {
if (branch.length === 0) return;
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
setNewBranchName("");
router.dismiss();
navigation.dismiss();
});
}}
/>
@@ -146,7 +146,7 @@ export function GitBranchesSheet() {
if (baseBranch.length === 0 || newBranch.length === 0) return;
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
setWorktreeBranchName("");
router.dismiss();
navigation.dismiss();
});
}}
/>
@@ -188,7 +188,7 @@ export function GitBranchesSheet() {
}}
onPress={() => {
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
router.dismiss();
navigation.dismiss();
});
}}
>
@@ -1,4 +1,4 @@
import { useRouter } from "expo-router";
import { useAppNavigation } from "../../../navigation/native-stack-header";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View, useColorScheme } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -14,7 +14,7 @@ import { vcsEnvironment } from "../../../state/vcs";
import { SheetActionButton } from "./gitSheetComponents";
export function GitCommitSheet() {
const router = useRouter();
const navigation = useAppNavigation();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const { selectedThread } = useThreadSelection();
@@ -55,7 +55,7 @@ export function GitCommitSheet() {
const runCommitAction = useCallback(
async (featureBranch: boolean) => {
const commitMessage = dialogCommitMessage.trim();
router.dismiss();
navigation.dismiss();
await gitActions.onRunSelectedThreadGitAction({
action: "commit",
featureBranch,
@@ -63,7 +63,7 @@ export function GitCommitSheet() {
...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}),
});
},
[allSelected, dialogCommitMessage, gitActions, router, selectedFiles],
[allSelected, dialogCommitMessage, gitActions, navigation, selectedFiles],
);
return (
@@ -2,7 +2,7 @@ import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime/st
import { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
import * as Arr from "effect/Array";
import * as Result from "effect/Result";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useRouteParams, useAppNavigation } from "../../../navigation/native-stack-header";
import { useCallback, useMemo } from "react";
import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -13,12 +13,12 @@ import { useSelectedThreadGitState } from "../../../state/use-selected-thread-gi
import { SheetActionButton } from "./gitSheetComponents";
export function GitConfirmSheet() {
const router = useRouter();
const navigation = useAppNavigation();
const insets = useSafeAreaInsets();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const params = useLocalSearchParams<{
const params = useRouteParams<{
confirmAction?: string;
branchName?: string;
includesCommit?: string;
@@ -49,17 +49,17 @@ export function GitConfirmSheet() {
const continuePendingAction = useCallback(async () => {
if (!confirmAction) return;
router.dismissAll();
navigation.dismissAll();
await gitActions.onRunSelectedThreadGitAction({
action: confirmAction,
...(params.commitMessage ? { commitMessage: params.commitMessage } : {}),
...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}),
});
}, [confirmAction, gitActions, params, router]);
}, [confirmAction, gitActions, params, navigation]);
const movePendingActionToFeatureBranch = useCallback(async () => {
if (!confirmAction) return;
router.dismissAll();
navigation.dismissAll();
if (includesCommit) {
await gitActions.onRunSelectedThreadGitAction({
@@ -82,7 +82,14 @@ export function GitConfirmSheet() {
);
await gitActions.onCreateSelectedThreadBranch(newBranchName);
await gitActions.onRunSelectedThreadGitAction({ action: confirmAction });
}, [confirmAction, gitActions, gitState.selectedThreadBranches, includesCommit, params, router]);
}, [
confirmAction,
gitActions,
gitState.selectedThreadBranches,
includesCommit,
params,
navigation,
]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -5,16 +5,23 @@ import {
requiresDefaultBranchConfirmation,
} from "@t3tools/client-runtime/state/vcs";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useRouteParams, useAppNavigation } from "../../../navigation/native-stack-header";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo } from "react";
import { Alert, Pressable, ScrollView, View } from "react-native";
import { useCallback, useEffect, useMemo, type ComponentProps } from "react";
import { Alert, Platform, Pressable, ScrollView, View } from "react-native";
import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText";
import { nativeHeaderScrollEdgeEffects } from "../../../lib/native-scroll-edge-effect";
import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
import { buildThreadReviewRoutePath } from "../../../lib/routes";
import {
buildGitBranchesNavigation,
buildGitCommitNavigation,
buildGitConfirmNavigation,
buildThreadReviewNavigation,
} from "../../../lib/routes";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
@@ -23,10 +30,19 @@ import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-wo
import { vcsEnvironment } from "../../../state/vcs";
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
export function GitOverviewSheet() {
const router = useRouter();
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
export function GitOverviewSheet(
props: {
readonly headerInset?: number;
readonly presentation?: "sheet" | "inspector";
} = {},
) {
const navigation = useAppNavigation();
const insets = useSafeAreaInsets();
const { environmentId, threadId } = useLocalSearchParams<{
const presentation = props.presentation ?? "sheet";
const isInspector = presentation === "inspector";
const { environmentId, threadId } = useRouteParams<{
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
@@ -37,6 +53,8 @@ export function GitOverviewSheet() {
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
const foregroundColor = String(useThemeColor("--color-foreground"));
const sheetColor = String(useThemeColor("--color-sheet"));
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
@@ -48,6 +66,7 @@ export function GitOverviewSheet() {
);
const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
const currentStatusSummary = statusSummary(gitStatus.data);
const currentWorktreePath = selectedThreadWorktreePath;
const gitOperationLabel = gitState.gitOperationLabel;
const busy = gitOperationLabel !== null;
@@ -105,25 +124,27 @@ export function GitOverviewSheet() {
!input.featureBranch &&
requiresDefaultBranchConfirmation(input.action, isDefaultRef)
) {
router.push({
pathname: "/threads/[environmentId]/[threadId]/git-confirm",
params: {
environmentId,
threadId,
confirmAction: confirmableAction,
branchName,
includesCommit: String(
input.action === "commit_push" || input.action === "commit_push_pr",
),
},
});
navigation.push(
buildGitConfirmNavigation(
{ environmentId, threadId },
{
confirmAction: confirmableAction,
branchName,
includesCommit: String(
input.action === "commit_push" || input.action === "commit_push_pr",
),
},
),
);
return;
}
router.dismiss();
if (!isInspector) {
navigation.dismiss();
}
await gitActions.onRunSelectedThreadGitAction(input);
},
[environmentId, gitActions, gitStatus.data, isDefaultRef, router, threadId],
[environmentId, gitActions, gitStatus.data, isDefaultRef, isInspector, navigation, threadId],
);
const onPressMenuItem = useCallback(
@@ -134,10 +155,7 @@ export function GitOverviewSheet() {
return;
}
if (item.dialogAction === "commit") {
router.push({
pathname: "/threads/[environmentId]/[threadId]/git/commit",
params: { environmentId, threadId },
});
navigation.push(buildGitCommitNavigation({ environmentId, threadId }));
return;
}
if (item.dialogAction === "push") {
@@ -148,14 +166,148 @@ export function GitOverviewSheet() {
await runActionWithPrompt({ action: "create_pr" });
}
},
[environmentId, openExistingPr, router, runActionWithPrompt, threadId],
[environmentId, openExistingPr, navigation, runActionWithPrompt, threadId],
);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
const inspectorHeaderRightBarButtonItems = useMemo(
() =>
[
{
accessibilityLabel: "Refresh repository status",
disabled: busy,
icon: { name: "arrow.clockwise", type: "sfSymbol" as const },
identifier: "git-overview-refresh",
onPress: () => {
void gitActions.refreshSelectedThreadGitStatus();
},
sharesBackground: false,
tintColor: foregroundColor,
type: "button" as const,
width: 44,
},
] as ComponentProps<typeof ScreenStackHeaderConfig>["headerRightBarButtonItems"],
[busy, foregroundColor, gitActions],
);
<View className="items-center gap-1 px-5 pb-3 pt-4">
const content = (
<ScrollView
contentInsetAdjustmentBehavior={isInspector && Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: isInspector ? 12 : 20,
paddingTop: 8,
gap: 14,
}}
>
<View
className={
isInspector
? "overflow-hidden rounded-2xl border border-border bg-card px-3 py-1"
: "overflow-hidden rounded-[22px] border border-border bg-card px-4 py-1"
}
>
{sheetMenuItems.map(({ item, disabledReason }, index) => (
<View key={`${item.id}-${item.label}`}>
{index > 0 ? (
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
) : null}
<SheetListRow
icon={menuItemIconName(item.icon)}
title={item.label}
subtitle={disabledReason}
disabled={item.disabled}
onPress={() => void onPressMenuItem(item)}
/>
</View>
))}
{(gitStatus.data?.behindCount ?? 0) > 0 ? (
<>
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="arrow.down.circle"
title="Pull latest"
subtitle="Sync this branch with upstream"
disabled={busy || !isRepo}
onPress={() => void gitActions.onPullSelectedThreadBranch()}
/>
</>
) : null}
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="text.bubble"
title="Review changes"
subtitle="Inspect turn diffs, worktree changes, and base branch diff"
disabled={busy || !isRepo}
onPress={() => navigation.push(buildThreadReviewNavigation({ environmentId, threadId }))}
/>
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="point.topleft.down.curvedto.point.bottomright.up"
title="Branches & worktrees"
subtitle="Switch branch, create branch, or move to a worktree"
disabled={busy || !isRepo}
onPress={() => navigation.push(buildGitBranchesNavigation({ environmentId, threadId }))}
/>
</View>
{currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
</ScrollView>
);
if (isInspector && Platform.OS === "ios") {
return (
<View collapsable={false} className="flex-1 border-l border-border bg-sheet">
<ScreenStack style={{ flex: 1 }}>
<Screen
activityState={2}
enabled
isNativeStack
screenId="thread-git-inspector-native"
scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
style={{ backgroundColor: sheetColor, flex: 1 }}
>
{content}
<ScreenStackHeaderConfig
backgroundColor="rgba(0,0,0,0)"
color={foregroundColor}
headerRightBarButtonItems={inspectorHeaderRightBarButtonItems}
hideBackButton
hideShadow={false}
navigationItemStyle="editor"
subtitle={currentStatusSummary}
title={currentBranchLabel}
titleColor={foregroundColor}
titleFontSize={17}
titleFontWeight="700"
translucent
/>
</Screen>
</ScreenStack>
</View>
);
}
return (
<View
collapsable={false}
className={isInspector ? "flex-1 border-l border-border bg-sheet" : "flex-1 bg-sheet"}
>
<View
style={{
minHeight: isInspector ? (props.headerInset ?? 0) : 16,
paddingTop: isInspector ? (props.headerInset ?? 0) : 8,
}}
/>
<View
className={
isInspector
? "gap-1 border-b border-border px-4 pb-4 pt-3"
: "items-center gap-1 px-5 pb-3 pt-4"
}
>
<Pressable
className="absolute right-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1, opacity: busy ? 0.45 : 1 }}
@@ -174,76 +326,17 @@ export function GitOverviewSheet() {
className="text-xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
Branch
{isInspector ? "Repository" : "Branch"}
</Text>
<Text className={isInspector ? "pr-10 text-xl font-t3-bold" : "text-3xl font-t3-bold"}>
{currentBranchLabel}
</Text>
<Text className="text-3xl font-t3-bold">{currentBranchLabel}</Text>
<Text className="text-foreground-secondary text-sm font-medium leading-[19px]">
{statusSummary(gitStatus.data)}
{currentStatusSummary}
</Text>
</View>
<ScrollView
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
gap: 14,
}}
>
<View className="overflow-hidden rounded-[22px] border border-border bg-card px-4 py-1">
{sheetMenuItems.map(({ item, disabledReason }, index) => (
<View key={`${item.id}-${item.label}`}>
{index > 0 ? (
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
) : null}
<SheetListRow
icon={menuItemIconName(item.icon)}
title={item.label}
subtitle={disabledReason}
disabled={item.disabled}
onPress={() => void onPressMenuItem(item)}
/>
</View>
))}
{(gitStatus.data?.behindCount ?? 0) > 0 ? (
<>
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="arrow.down.circle"
title="Pull latest"
subtitle="Sync this branch with upstream"
disabled={busy || !isRepo}
onPress={() => void gitActions.onPullSelectedThreadBranch()}
/>
</>
) : null}
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="text.bubble"
title="Review changes"
subtitle="Inspect turn diffs, worktree changes, and base branch diff"
disabled={busy || !isRepo}
onPress={() => router.push(buildThreadReviewRoutePath({ environmentId, threadId }))}
/>
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="point.topleft.down.curvedto.point.bottomright.up"
title="Branches & worktrees"
subtitle="Switch branch, create branch, or move to a worktree"
disabled={busy || !isRepo}
onPress={() =>
router.push({
pathname: "/threads/[environmentId]/[threadId]/git/branches",
params: { environmentId, threadId },
})
}
/>
</View>
{currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
</ScrollView>
{content}
</View>
);
}
@@ -0,0 +1,24 @@
import { Pressable, View } from "react-native";
import { T3HeaderButton } from "../../native/T3HeaderButton.ios";
type SidebarFilterButtonIcon =
| "line.3.horizontal.decrease.circle"
| "line.3.horizontal.decrease.circle.fill";
export function SidebarFilterButton(props: {
readonly accessibilityLabel: string;
readonly icon: SidebarFilterButtonIcon;
}) {
return (
<Pressable accessibilityLabel={props.accessibilityLabel} accessibilityRole="button">
<View pointerEvents="none" style={{ width: 44, height: 44 }}>
<T3HeaderButton
accessibilityLabel={props.accessibilityLabel}
icon={props.icon}
onPress={() => undefined}
/>
</View>
</Pressable>
);
}
@@ -0,0 +1,49 @@
import { SymbolView } from "expo-symbols";
import { Pressable, StyleSheet, useColorScheme } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
export type SidebarFilterButtonIcon =
| "line.3.horizontal.decrease.circle"
| "line.3.horizontal.decrease.circle.fill";
export function SidebarFilterButton(props: {
readonly accessibilityLabel: string;
readonly icon: SidebarFilterButtonIcon;
}) {
const iconColor = useThemeColor("--color-icon-muted");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
const idleBackgroundColor =
colorScheme === "dark" ? "rgba(118,118,128,0.24)" : "rgba(255,255,255,0.72)";
const borderColor = colorScheme === "dark" ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.08)";
return (
<Pressable
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
hitSlop={4}
style={({ pressed }) => [
styles.button,
{
backgroundColor: pressed ? pressedBackgroundColor : idleBackgroundColor,
borderColor,
},
]}
>
<SymbolView name={props.icon} size={18} tintColor={iconColor} type="monochrome" />
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
width: 44,
height: 44,
borderRadius: 22,
borderWidth: StyleSheet.hairlineWidth,
alignItems: "center",
justifyContent: "center",
cursor: "pointer",
},
});
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more