Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Add archived threads and mobile file viewer (#3155)

Julius Marminge30034ecedc46
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts
index d7252d3f8..687cdb756 100644
--- a/apps/desktop/src/preview/Manager.test.ts
+++ b/apps/desktop/src/preview/Manager.test.ts
@@ -128,6 +128,58 @@ describe("PreviewManager", () => {
),
);
+ effectIt.effect("queues navigation until the webview registers", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const loadURL = vi.fn(async () => undefined);
+ const listeners = new Map<string, (...args: never[]) => void>();
+ fromId.mockReturnValue({
+ id: 42,
+ isDestroyed: () => false,
+ getType: () => "webview",
+ getURL: () => "about:blank",
+ getTitle: () => "",
+ isLoading: () => false,
+ getZoomFactor: () => 1,
+ setZoomFactor: vi.fn(),
+ loadURL,
+ on: vi.fn((event: string, listener: (...args: never[]) => void) => {
+ listeners.set(event, listener);
+ }),
+ off: vi.fn(),
+ ipc: { on: vi.fn(), off: vi.fn() },
+ send: webviewSend,
+ navigationHistory: { canGoBack: () => false, canGoForward: () => false },
+ setWindowOpenHandler: vi.fn(),
+ debugger: {
+ isAttached: () => false,
+ attach: vi.fn(),
+ sendCommand: vi.fn(async () => undefined),
+ on: vi.fn(),
+ off: vi.fn(),
+ },
+ } as never);
+
+ yield* manager.navigate("tab_pending", "localhost:3200");
+
+ expect(yield* manager.automationStatus("tab_pending")).toEqual({
+ available: false,
+ visible: true,
+ tabId: "tab_pending",
+ url: "http://localhost:3200/",
+ title: "",
+ loading: true,
+ });
+
+ yield* manager.registerWebview("tab_pending", 42);
+ yield* Effect.yieldNow;
+
+ expect(loadURL).toHaveBeenCalledOnce();
+ expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
+ }),
+ ),
+ );
+
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index 2c4096e8c..d4bed4980 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -1195,26 +1195,103 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
- if (Math.abs(tab.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
- yield* attempt("registerWebview.restoreZoom", () => wc.setZoomFactor(tab.zoomFactor)).pipe(
- Effect.ignore,
- );
- }
- yield* update(tabId, {
- webContentsId,
- navStatus: computeNavStatus(wc),
- canGoBack: wc.navigationHistory.canGoBack(),
- canGoForward: wc.navigationHistory.canGoForward(),
- zoomFactor: tab.zoomFactor,
+ const registeredAt = yield* currentIso;
+ const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
+ const current = tabs.get(tabId);
+ if (!current) {
+ return [
+ Option.none<{ readonly state: PreviewTabState; readonly pendingUrl: string | null }>(),
+ tabs,
+ ] as const;
+ }
+ const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
+ const next: PreviewTabState = {
+ ...current,
+ webContentsId,
+ navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
+ canGoBack: wc.navigationHistory.canGoBack(),
+ canGoForward: wc.navigationHistory.canGoForward(),
+ updatedAt: registeredAt,
+ };
+ return [
+ Option.some({
+ state: next,
+ pendingUrl,
+ }),
+ replaceMap(tabs, (copy) => {
+ copy.set(tabId, next);
+ }),
+ ] as const;
});
+ if (Option.isNone(registration)) {
+ return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
+ }
+ const { state: registered, pendingUrl } = registration.value;
+ yield* emit(tabId, registered);
+ if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
+ yield* attempt("registerWebview.restoreZoom", () =>
+ wc.setZoomFactor(registered.zoomFactor),
+ ).pipe(Effect.ignore);
+ }
yield* attempt("registerWebview.sendTheme", () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
+ const latestNavStatus = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.navStatus;
+ if (
+ pendingUrl &&
+ latestNavStatus?.kind === "Loading" &&
+ latestNavStatus.url === pendingUrl &&
+ wc.getURL() !== pendingUrl
+ ) {
+ runFork(
+ attemptPromise("registerWebview.loadPendingUrl", () => wc.loadURL(pendingUrl)).pipe(
+ Effect.ignore,
+ ),
+ );
+ }
});
const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) {
- const wc = yield* requireWebContents(tabId);
const url = yield* attempt("navigate.normalizeUrl", () => normalizePreviewUrl(rawUrl));
+ const updatedAt = yield* currentIso;
+ const pending = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
+ const current = tabs.get(tabId);
+ const next: PreviewTabState = {
+ tabId,
+ webContentsId: current?.webContentsId ?? null,
+ navStatus: {
+ kind: "Loading",
+ url,
+ title: current?.navStatus.kind === "Idle" || !current ? "" : current.navStatus.title,
+ },
+ canGoBack: current?.canGoBack ?? false,
+ canGoForward: current?.canGoForward ?? false,
+ zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
+ controller: current?.controller ?? "none",
+ updatedAt,
+ };
+ return [
+ next,
+ replaceMap(tabs, (copy) => {
+ copy.set(tabId, next);
+ }),
+ ] as const;
+ });
+ yield* emit(tabId, pending);
+ if (pending.webContentsId == null) return;
+ const wc = webContents.fromId(pending.webContentsId);
+ if (!wc) {
+ const detached = { ...pending, webContentsId: null };
+ yield* SynchronizedRef.update(tabsRef, (tabs) =>
+ tabs.get(tabId)?.webContentsId !== pending.webContentsId
+ ? tabs
+ : replaceMap(tabs, (copy) => {
+ copy.set(tabId, detached);
+ }),
+ );
+ yield* emit(tabId, detached);
+ return;
+ }
if (wc.getURL() === url) {
yield* attempt("navigate.reload", () => wc.reload());
return;
diff --git a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm
index 3ebfdb7a1..6fa61aab1 100644
--- a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm
+++ b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm
@@ -70,7 +70,12 @@ static void T3MarkdownTextApplyAttachments(
renderingMode:UIImageRenderingModeAlwaysOriginal];
}
attachment.image = image ?: [[UIImage alloc] init];
- attachment.bounds = CGRectMake(0, -0.5, 10, 10);
+ const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
+ attachment.bounds = CGRectMake(
+ 0,
+ T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
+ attachmentSize,
+ attachmentSize);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
@@ -80,104 +85,6 @@ static void T3MarkdownTextApplyAttachments(
}
}
-static NSArray<NSDictionary<NSString *, id> *> *T3MarkdownTextExtractChipBackgrounds(
- NSMutableAttributedString *attributedString,
- const std::vector<T3MarkdownTextChipRange> &chipRanges)
-{
- NSMutableArray<NSDictionary<NSString *, id> *> *backgrounds = [NSMutableArray array];
- for (const auto &chipRange : chipRanges) {
- if (chipRange.length == 0 || chipRange.location >= attributedString.length) {
- continue;
- }
-
- const NSRange range = NSMakeRange(
- chipRange.location,
- MIN(chipRange.length, attributedString.length - chipRange.location));
- UIColor *color = [attributedString attribute:NSBackgroundColorAttributeName
- atIndex:range.location
- effectiveRange:nil];
- UIColor *foregroundColor = [attributedString attribute:NSForegroundColorAttributeName
- atIndex:range.location
- effectiveRange:nil];
- if (color == nil) {
- continue;
- }
- [backgrounds addObject:@{
- @"range": [NSValue valueWithRange:range],
- @"color": color,
- @"strokeColor": [foregroundColor
- colorWithAlphaComponent:chipRange.isSkill ? 0.25 : 0.1] ?: UIColor.clearColor,
- }];
- [attributedString removeAttribute:NSBackgroundColorAttributeName range:range];
- }
- return backgrounds;
-}
-
-@interface T3MarkdownTextBackingView : UITextView
-@property(nonatomic, copy) NSArray<NSDictionary<NSString *, id> *> *chipBackgrounds;
-@end
-
-@implementation T3MarkdownTextBackingView
-
-- (void)drawRect:(CGRect)rect
-{
- [self.layoutManager ensureLayoutForTextContainer:self.textContainer];
- CGContextRef context = UIGraphicsGetCurrentContext();
- if (context != nil) {
- CGContextSaveGState(context);
- CGContextResetClip(context);
- CGContextClipToRect(context, self.bounds);
- }
- for (NSDictionary<NSString *, id> *background in self.chipBackgrounds) {
- const NSRange characterRange = [background[@"range"] rangeValue];
- UIColor *color = background[@"color"];
- UIColor *strokeColor = background[@"strokeColor"];
- if (characterRange.length == 0 || NSMaxRange(characterRange) > self.textStorage.length) {
- continue;
- }
-
- const NSRange glyphRange =
- [self.layoutManager glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
- [color setFill];
- [self.layoutManager
- enumerateEnclosingRectsForGlyphRange:glyphRange
- withinSelectedGlyphRange:NSMakeRange(NSNotFound, 0)
- inTextContainer:self.textContainer
- usingBlock:^(CGRect glyphRect, BOOL *stop) {
- const CGFloat chipHeight = 22;
- CGRect chipRect = CGRectMake(
- glyphRect.origin.x - 4,
- CGRectGetMidY(glyphRect) - chipHeight / 2,
- glyphRect.size.width + 8,
- chipHeight);
- chipRect.origin.x += self.textContainerInset.left;
- chipRect.origin.y += self.textContainerInset.top;
- const CGFloat minimumX = self.textContainerInset.left + 0.5;
- const CGFloat maximumX =
- CGRectGetWidth(self.bounds) - self.textContainerInset.right - 0.5;
- if (chipRect.origin.x < minimumX) {
- chipRect.size.width -= minimumX - chipRect.origin.x;
- chipRect.origin.x = minimumX;
- }
- if (CGRectGetMaxX(chipRect) > maximumX) {
- chipRect.size.width = MAX(0, maximumX - chipRect.origin.x);
- }
- UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:chipRect cornerRadius:6];
- [path fill];
- [strokeColor setStroke];
- path.lineWidth = 1;
- [path stroke];
- }];
- }
- if (context != nil) {
- CGContextRestoreGState(context);
- }
-
- [super drawRect:rect];
-}
-
-@end
-
@protocol T3MarkdownOutsideTapTarget <NSObject>
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
@end
@@ -285,7 +192,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
@implementation T3MarkdownText {
UIView * _view;
- T3MarkdownTextBackingView * _textView;
+ UITextView * _textView;
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
__weak UIWindow * _outsideTapWindow;
BOOL _suppressSelectionChange;
@@ -308,7 +215,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
self.contentView = _view;
self.clipsToBounds = true;
- _textView = [[T3MarkdownTextBackingView alloc] init];
+ _textView = [[UITextView alloc] init];
_attachmentImages = [[NSMutableDictionary alloc] init];
_pendingAttachmentUris = [[NSMutableSet alloc] init];
_textView.scrollEnabled = false;
@@ -405,9 +312,6 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
convertedAttrString,
_state->getData().attachmentRanges,
_attachmentImages);
- _textView.chipBackgrounds = T3MarkdownTextExtractChipBackgrounds(
- convertedAttrString,
- _state->getData().chipRanges);
[self loadAttachmentImages:_state->getData().attachmentRanges];
// Setting attributedText clears any active text selection, and re-assigning
diff --git a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.h b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.h
index afc276aed..99417490a 100644
--- a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.h
+++ b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.h
@@ -28,18 +28,20 @@ struct T3MarkdownTextAttachmentRange {
std::string imageUri;
};
-struct T3MarkdownTextChipRange {
- size_t location;
- size_t length;
- bool isSkill;
-};
+inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
+ return 14;
+}
+
+inline Float T3MarkdownTextAttachmentBaselineOffset(
+ const T3MarkdownTextAttachmentRange &) {
+ return -2;
+}
class T3MarkdownTextStateReal final {
public:
AttributedString attributedString;
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
- std::vector<T3MarkdownTextChipRange> chipRanges;
};
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
@@ -72,6 +74,5 @@ private:
mutable AttributedString _attributedString;
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
- mutable std::vector<T3MarkdownTextChipRange> _chipRanges;
};
} // namespace facebook::React
diff --git a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.mm b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.mm
index 00fda7422..b9abe452f 100644
--- a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.mm
+++ b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownTextShadowNode.mm
@@ -9,9 +9,8 @@
namespace facebook::react {
static constexpr Float ParagraphStyleEncodingOffset = 1000;
-static constexpr auto ChipNativeIdPrefix = "t3-chip-";
-static constexpr auto FileChipNativeIdPrefix = "t3-chip-file:";
-static constexpr auto SkillChipNativeIdPrefix = "t3-chip-skill:";
+static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
+static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
static void applyParagraphStyles(
NSMutableAttributedString *attributedString,
@@ -58,7 +57,12 @@ static void applyAttachments(
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [[UIImage alloc] init];
- attachment.bounds = CGRectMake(0, -0.5, 10, 10);
+ const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
+ attachment.bounds = CGRectMake(
+ 0,
+ T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
+ attachmentSize,
+ attachmentSize);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
@@ -91,7 +95,6 @@ Size T3MarkdownTextShadowNode::measureContent(
auto baseAttributedString = AttributedString{};
auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
- auto chipRanges = std::vector<T3MarkdownTextChipRange>{};
size_t utf16Offset = 0;
const auto &children = getChildren();
for (size_t i = 0; i < children.size(); i++) {
@@ -184,25 +187,19 @@ Size T3MarkdownTextShadowNode::measureContent(
props.shadowRadius - ParagraphStyleEncodingOffset,
});
}
- if (props.nativeId.rfind(ChipNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
- chipRanges.push_back(T3MarkdownTextChipRange{
- utf16Offset,
- fragmentLength,
- props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0,
- });
- }
- if (props.nativeId.rfind(FileChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
+ if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
- utf16Offset + 1,
+ utf16Offset,
1,
- props.nativeId.substr(std::char_traits<char>::length(FileChipNativeIdPrefix)),
+ props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
});
} else if (
- props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
+ props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
- utf16Offset + 1,
+ utf16Offset,
1,
- props.nativeId.substr(std::char_traits<char>::length(SkillChipNativeIdPrefix)),
+ props.nativeId.substr(
+ std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
});
}
utf16Offset += fragmentLength;
@@ -213,7 +210,6 @@ Size T3MarkdownTextShadowNode::measureContent(
_attributedString = baseAttributedString;
_paragraphStyleRanges = paragraphStyleRanges;
_attachmentRanges = attachmentRanges;
- _chipRanges = chipRanges;
NSMutableAttributedString *convertedAttributedString =
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
@@ -263,7 +259,6 @@ void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
_attributedString,
_paragraphStyleRanges,
_attachmentRanges,
- _chipRanges,
});
}
}
diff --git a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx
index 757b6c660..212c38512 100644
--- a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx
+++ b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx
@@ -40,11 +40,13 @@ function documentFor(node: MarkdownNode): MarkdownNode {
function SelectableNode(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
+ readonly onLinkPress?: (href: string) => void;
}) {
return (
<NativeMarkdownSelectableText
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
/>
);
}
@@ -312,6 +314,7 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
function NativeTable(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
+ readonly onLinkPress?: (href: string) => void;
}) {
const rows = collectTableRows(props.node);
return (
@@ -351,6 +354,7 @@ function NativeTable(props: {
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
)}
textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
/>
</View>
))}
@@ -364,10 +368,17 @@ function NativeTable(props: {
function NativeMarkdownImage(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
+ readonly onLinkPress?: (href: string) => void;
}) {
const href = props.node.href;
if (!href) {
- return <SelectableNode node={props.node} textStyle={props.textStyle} />;
+ return (
+ <SelectableNode
+ node={props.node}
+ textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
+ />
+ );
}
return (
@@ -426,6 +437,7 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
function NativeMixedParagraph(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
+ readonly onLinkPress?: (href: string) => void;
}) {
return (
<View style={{ gap: 8 }}>
@@ -435,9 +447,15 @@ function NativeMixedParagraph(props: {
key={nodeKey(child, index)}
node={child}
textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
/>
) : (
- <SelectableNode key={nodeKey(child, index)} node={child} textStyle={props.textStyle} />
+ <SelectableNode
+ key={nodeKey(child, index)}
+ node={child}
+ textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
+ />
),
)}
</View>
@@ -448,6 +466,7 @@ function NativeList(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
+ readonly onLinkPress?: (href: string) => void;
readonly depth: number;
}) {
const ordered = props.node.ordered ?? false;
@@ -508,6 +527,7 @@ function NativeList(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
+ onLinkPress={props.onLinkPress}
depth={props.depth + 1}
compact
/>
@@ -524,6 +544,7 @@ export function NativeMarkdownBlock(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
+ readonly onLinkPress?: (href: string) => void;
readonly depth?: number;
readonly compact?: boolean;
}) {
@@ -538,6 +559,7 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
+ onLinkPress={props.onLinkPress}
depth={depth}
/>
))}
@@ -553,9 +575,21 @@ export function NativeMarkdownBlock(props: {
/>
);
case "table":
- return <NativeTable node={props.node} textStyle={props.textStyle} />;
+ return (
+ <NativeTable
+ node={props.node}
+ textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
+ />
+ );
case "image":
- return <NativeMarkdownImage node={props.node} textStyle={props.textStyle} />;
+ return (
+ <NativeMarkdownImage
+ node={props.node}
+ textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
+ />
+ );
case "horizontal_rule":
return (
<View
@@ -583,6 +617,7 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
+ onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
@@ -595,14 +630,23 @@ export function NativeMarkdownBlock(props: {
node={props.node}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
+ onLinkPress={props.onLinkPress}
depth={depth}
/>
);
case "paragraph":
return (props.node.children ?? []).some((child) => child.type === "image") ? (
- <NativeMixedParagraph node={props.node} textStyle={props.textStyle} />
+ <NativeMixedParagraph
+ node={props.node}
+ textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
+ />
) : (
- <SelectableNode node={props.node} textStyle={props.textStyle} />
+ <SelectableNode
+ node={props.node}
+ textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
+ />
);
case "html_block":
case "math_block":
@@ -618,7 +662,11 @@ export function NativeMarkdownBlock(props: {
: "transparent",
}}
>
- <SelectableNode node={props.node} textStyle={props.textStyle} />
+ <SelectableNode
+ node={props.node}
+ textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
+ />
</View>
);
case "table_head":
@@ -635,6 +683,7 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
+ onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
@@ -642,6 +691,12 @@ export function NativeMarkdownBlock(props: {
</View>
);
default:
- return <SelectableNode node={props.node} textStyle={props.textStyle} />;
+ return (
+ <SelectableNode
+ node={props.node}
+ textStyle={props.textStyle}
+ onLinkPress={props.onLinkPress}
+ />
+ );
}
}
diff --git a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx
index c6495eed8..c7a5a16d6 100644
--- a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx
+++ b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx
@@ -1,61 +1,15 @@
-import { useEffect, useMemo, useState } from "react";
-import { Asset } from "expo-asset";
import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import { markdownFileIconSource } from "./markdownFileIcons";
-import type { MarkdownFileIcon } from "./markdownLinks";
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
const EXTERNAL_LINK_PREFIX = "◉ ";
-const FILE_LINK_PREFIX = "\u00A0\uFFFC\u00A0";
-const CHIP_SUFFIX = "\u00A0";
+const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
-function useFileIconUris(runs: ReadonlyArray<NativeMarkdownTextRun>) {
- const iconSignature = JSON.stringify(
- [...new Set(runs.flatMap((run) => (run.fileIcon ? [run.fileIcon] : [])))].sort(),
- );
- const icons = useMemo(
- () => JSON.parse(iconSignature) as ReadonlyArray<MarkdownFileIcon>,
- [iconSignature],
- );
- const [uris, setUris] = useState<ReadonlyMap<string, string>>(() => new Map());
-
- useEffect(() => {
- let cancelled = false;
-
- void Promise.all(
- icons.map(async (icon) => {
- const source = markdownFileIconSource(icon);
- const fallbackUri = Image.resolveAssetSource(source).uri;
- if (typeof source !== "number" && typeof source !== "string") {
- return [icon, fallbackUri] as const;
- }
- try {
- const asset = Asset.fromModule(source);
- await asset.downloadAsync();
- return [icon, asset.localUri ?? fallbackUri] as const;
- } catch {
- return [icon, fallbackUri] as const;
- }
- }),
- ).then((entries) => {
- if (!cancelled) {
- setUris(new Map(entries));
- }
- });
-
- return () => {
- cancelled = true;
- };
- }, [icons]);
-
- return uris;
-}
-
function runKeySignature(run: NativeMarkdownTextRun): string {
return [
run.text,
@@ -81,13 +35,16 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
const isFile = run.fileIcon != null;
const isSkill = run.skillName != null;
- const isChip = isFile || isSkill;
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
const isHeading = run.role === "heading";
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
const hasParagraphStyle = run.headIndent !== undefined;
- const textDecorationLine = run.strikethrough ? "line-through" : run.href ? "underline" : "none";
+ const textDecorationLine = run.strikethrough
+ ? "line-through"
+ : run.href && !isFile
+ ? "underline"
+ : "none";
return {
color: isFile
@@ -106,20 +63,23 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? textStyle.mutedColor
: run.role === "list-marker"
? textStyle.mutedColor
- : run.code || isFile
+ : isCodeBlock
? textStyle.codeColor
- : run.bold
- ? textStyle.strongColor
- : textStyle.color,
- fontFamily: isChip
- ? "DMSans_500Medium"
- : run.code || isCodeBlock
- ? "ui-monospace"
- : isHeading
- ? textStyle.headingFontFamily
- : run.bold
- ? textStyle.boldFontFamily
- : textStyle.fontFamily,
+ : run.code
+ ? textStyle.inlineCodeColor
+ : run.bold
+ ? textStyle.strongColor
+ : textStyle.color,
+ fontFamily:
+ isFile || isSkill
+ ? textStyle.boldFontFamily
+ : run.code || isCodeBlock
+ ? "ui-monospace"
+ : isHeading
+ ? textStyle.headingFontFamily
+ : run.bold
+ ? textStyle.boldFontFamily
+ : textStyle.fontFamily,
fontSize:
run.role === "spacer"
? (run.spacing ?? 10)
@@ -129,7 +89,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? headingFontSize
: run.role === "code-language"
? 11
- : run.code || isChip || isCodeBlock
+ : run.code || isCodeBlock
? Math.max(12, textStyle.fontSize - 2)
: textStyle.fontSize,
lineHeight:
@@ -143,17 +103,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? 18
: textStyle.lineHeight,
fontStyle: run.italic ? "italic" : "normal",
- fontWeight: isHeading || run.bold ? "700" : isChip ? "500" : "400",
+ fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
textDecorationLine,
- backgroundColor: isCodeBlock
- ? textStyle.codeBlockBackgroundColor
- : isSkill
- ? textStyle.skillBackgroundColor
- : run.code
- ? textStyle.codeBackgroundColor
- : isFile
- ? textStyle.fileBackgroundColor
- : undefined,
+ backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
...(hasParagraphStyle
? {
shadowColor: "transparent",
@@ -170,9 +122,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
export function NativeMarkdownSelectableText(props: {
readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
readonly textStyle: NativeMarkdownTextStyle;
+ readonly onLinkPress?: (href: string) => void;
}) {
const colorScheme = useColorScheme();
- const fileIconUris = useFileIconUris(props.runs);
const occurrences = new Map<string, number>();
const prefixedExternalLinks = new Set<string>();
const keyedRuns = props.runs.map((run) => {
@@ -182,9 +134,9 @@ export function NativeMarkdownSelectableText(props: {
let text = run.text;
if (run.fileIcon) {
- text = `${FILE_LINK_PREFIX}${text}${CHIP_SUFFIX}`;
+ text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
} else if (run.skillName && run.skillLabel) {
- text = `\u00A0${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}${CHIP_SUFFIX}`;
+ text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
prefixedExternalLinks.add(run.href);
text = `${EXTERNAL_LINK_PREFIX}${text}`;
@@ -200,12 +152,11 @@ export function NativeMarkdownSelectableText(props: {
props.textStyle.strongColor,
props.textStyle.mutedColor,
props.textStyle.linkColor,
+ props.textStyle.inlineCodeColor,
props.textStyle.codeColor,
props.textStyle.codeBackgroundColor,
props.textStyle.codeBlockBackgroundColor,
- props.textStyle.fileBackgroundColor,
props.textStyle.fileTextColor,
- props.textStyle.skillBackgroundColor,
props.textStyle.skillTextColor,
props.textStyle.quoteMarkerColor,
props.textStyle.dividerColor,
@@ -217,7 +168,8 @@ export function NativeMarkdownSelectableText(props: {
uiTextView
selectable
style={{
- width: "100%",
+ flexShrink: 1,
+ minWidth: 0,
color: props.textStyle.color,
fontFamily: props.textStyle.fontFamily,
fontSize: props.textStyle.fontSize,
@@ -231,19 +183,20 @@ export function NativeMarkdownSelectableText(props: {
key={key}
nativeID={
run.fileIcon
- ? `t3-chip-file:${
- fileIconUris.get(run.fileIcon) ??
- Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
- }`
+ ? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
: run.skillName
- ? "t3-chip-skill:sf:cube"
+ ? "t3-skill:sf:cube"
: undefined
}
style={runStyle(run, props.textStyle)}
onPress={
href
? () => {
- void Linking.openURL(href);
+ if (props.onLinkPress) {
+ props.onLinkPress(href);
+ } else {
+ void Linking.openURL(href);
+ }
}
: undefined
}
diff --git a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.ios.tsx
index 7c8f8d1bd..56321ba01 100644
--- a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.ios.tsx
+++ b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.ios.tsx
@@ -6,6 +6,7 @@ import {
nativeMarkdownChunkSpacing,
nativeMarkdownDocumentChunks,
nativeMarkdownDocumentRuns,
+ nativeMarkdownWithPreservedSoftBreaks,
} from "./nativeMarkdownText";
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
@@ -33,15 +34,20 @@ export function SelectableMarkdownText({
skills = EMPTY_SKILLS,
textStyle,
highlightCode,
+ preserveSoftBreaks = false,
+ onLinkPress,
marginTop = 0,
marginBottom = 0,
}: SelectableMarkdownTextProps) {
const chunks = useMemo(() => {
- const document = parseMarkdownWithOptions(markdown, {
+ const parsedDocument = parseMarkdownWithOptions(markdown, {
gfm: true,
html: true,
math: false,
});
+ const document = preserveSoftBreaks
+ ? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
+ : parsedDocument;
return nativeMarkdownDocumentChunks(document).map((chunk) =>
chunk.kind === "selectable"
? {
@@ -50,10 +56,14 @@ export function SelectableMarkdownText({
}
: chunk,
);
- }, [markdown, skills]);
+ }, [markdown, preserveSoftBreaks, skills]);
return (
- <View style={{ width: "100%", marginTop, marginBottom }}>
+ // A percentage width here creates a cyclic intrinsic measurement inside
+ // shrink-to-fit containers such as user-message bubbles. Yoga then gives
+ // the native text node an unbounded second pass and the parent only clips
+ // the resulting single-line width instead of reflowing it.
+ <View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
{chunks.map((chunk, index) => {
const content =
chunk.kind === "rich" ? (
@@ -61,9 +71,14 @@ export function SelectableMarkdownText({
node={chunk.node}
textStyle={textStyle}
highlightCode={highlightCode}
+ onLinkPress={onLinkPress}
/>
) : (
- <NativeMarkdownSelectableText runs={chunk.runs} textStyle={textStyle} />
+ <NativeMarkdownSelectableText
+ runs={chunk.runs}
+ textStyle={textStyle}
+ onLinkPress={onLinkPress}
+ />
);
return (
diff --git a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts
index bd67d9110..76c1402d3 100644
--- a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts
+++ b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts
@@ -3,12 +3,11 @@ export interface NativeMarkdownTextStyle {
readonly strongColor: string;
readonly mutedColor: string;
readonly linkColor: string;
+ readonly inlineCodeColor: string;
readonly codeColor: string;
readonly codeBackgroundColor: string;
readonly codeBlockBackgroundColor: string;
- readonly fileBackgroundColor: string;
readonly fileTextColor: string;
- readonly skillBackgroundColor: string;
readonly skillTextColor: string;
readonly quoteMarkerColor: string;
readonly dividerColor: string;
@@ -41,6 +40,8 @@ export interface SelectableMarkdownTextProps {
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
+ readonly preserveSoftBreaks?: boolean;
+ readonly onLinkPress?: (href: string) => void;
readonly marginTop?: number;
readonly marginBottom?: number;
}
diff --git a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts
index affd7515b..f13891e3f 100644
--- a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts
+++ b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts
@@ -27,8 +27,12 @@ export type MarkdownLinkPresentation =
}
| {
readonly kind: "file";
+ readonly href: string;
readonly icon: MarkdownFileIcon;
readonly label: string;
+ readonly path: string;
+ readonly line?: number;
+ readonly column?: number;
}
| {
readonly kind: "link";
@@ -247,7 +251,7 @@ function normalizeDestination(value: string): string {
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
}
-function fileUrlPath(href: string): string | null {
+function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
try {
const parsed = new URL(href);
if (parsed.protocol.toLowerCase() !== "file:") {
@@ -256,15 +260,44 @@ function fileUrlPath(href: string): string | null {
const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
? parsed.pathname.slice(1)
: parsed.pathname;
- const lineMatch = parsed.hash.match(/^#L(\d+)(?:C(\d+))?$/i);
- return `${safeDecode(path)}${
- lineMatch?.[1] ? `:${lineMatch[1]}${lineMatch[2] ? `:${lineMatch[2]}` : ""}` : ""
- }`;
+ return { path, hash: parsed.hash };
} catch {
return null;
}
}
+function stripSearchAndHash(value: string): { readonly path: string; readonly hash: string } {
+ const hashIndex = value.indexOf("#");
+ const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
+ const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
+ const queryIndex = pathWithSearch.indexOf("?");
+ return {
+ path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
+ hash,
+ };
+}
+
+function splitFilePosition(
+ path: string,
+ hash: string,
+): { readonly path: string; readonly line?: number; readonly column?: number } {
+ const suffixMatch = path.match(/:(\d+)(?::(\d+))?$/);
+ const hashMatch = suffixMatch ? null : hash.match(/^#L(\d+)(?:C(\d+))?$/i);
+ const match = suffixMatch ?? hashMatch;
+ if (!match?.[1]) {
+ return { path };
+ }
+
+ const line = Number.parseInt(match[1], 10);
+ const column = match[2] ? Number.parseInt(match[2], 10) : undefined;
+ const pathWithoutPosition = suffixMatch ? path.slice(0, -suffixMatch[0].length) : path;
+ return {
+ path: pathWithoutPosition,
+ ...(line > 0 ? { line } : {}),
+ ...(column !== undefined && column > 0 ? { column } : {}),
+ };
+}
+
function looksLikePosixFilesystemPath(path: string): boolean {
if (!path.startsWith("/")) {
return false;
@@ -331,14 +364,31 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
// Relative paths and non-URL link destinations are handled below.
}
- const fileTarget = normalized.toLowerCase().startsWith("file:")
- ? fileUrlPath(normalized)
- : safeDecode(normalized.split(/[?#]/, 1)[0] ?? normalized);
- if (fileTarget && looksLikeFilePath(fileTarget)) {
+ const source = normalized.toLowerCase().startsWith("file:")
+ ? fileUrlTarget(normalized)
+ : stripSearchAndHash(normalized);
+ const decodedSource = source
+ ? { path: safeDecode(source.path.trim()), hash: safeDecode(source.hash.trim()) }
+ : null;
+ const fileTarget = decodedSource
+ ? splitFilePosition(decodedSource.path, decodedSource.hash)
+ : null;
+ const targetWithPosition = fileTarget
+ ? `${fileTarget.path}${
+ fileTarget.line
+ ? `:${fileTarget.line}${fileTarget.column ? `:${fileTarget.column}` : ""}`
+ : ""
+ }`
+ : null;
+ if (fileTarget && targetWithPosition && looksLikeFilePath(targetWithPosition)) {
return {
kind: "file",
- icon: resolveMarkdownFileIcon(fileTarget),
- label: fileLabel(fileTarget),
+ href: normalized,
+ icon: resolveMarkdownFileIcon(fileTarget.path),
+ label: fileLabel(targetWithPosition),
+ path: fileTarget.path,
+ ...(fileTarget.line ? { line: fileTarget.line } : {}),
+ ...(fileTarget.column ? { column: fileTarget.column } : {}),
};
}
diff --git a/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts b/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts
index 6751e165f..dc84755cb 100644
--- a/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts
+++ b/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts
@@ -293,6 +293,7 @@ function appendNode(
if (presentation.kind === "file") {
return appendRun(runs, presentation.label, {
...context,
+ href: presentation.href,
fileIcon: presentation.icon,
});
}
@@ -319,6 +320,15 @@ export function nativeMarkdownTextRuns(node: MarkdownNode): ReadonlyArray<Native
return appendChildren([], node, EMPTY_CONTEXT);
}
+export function nativeMarkdownWithPreservedSoftBreaks(node: MarkdownNode): MarkdownNode {
+ const children = node.children?.map(nativeMarkdownWithPreservedSoftBreaks);
+ return {
+ ...node,
+ ...(node.type === "soft_break" ? { type: "line_break" as const } : {}),
+ ...(children ? { children } : {}),
+ };
+}
+
function appendBlockTerminator(
runs: NativeMarkdownTextRun[],
context: RunContext,
diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
index f19671659..81cdd8417 100644
--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
@@ -57,6 +57,10 @@ public class T3ReviewDiffModule: Module {
view.setContentWidth(CGFloat(contentWidth))
}
+ Prop("initialRowIndex") { (view: T3ReviewDiffView, initialRowIndex: Double) in
+ view.setInitialRowIndex(initialRowIndex)
+ }
+
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
}
}
diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
index a4b5e57d6..f8e080e76 100644
--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
@@ -205,7 +205,7 @@ private struct ReviewDiffNativeStyle {
ReviewDiffNativeStyle(
rowHeight: metric(payload?.rowHeight, fallback: 24),
contentWidth: metric(payload?.contentWidth, fallback: 2800),
- changeBarWidth: metric(payload?.changeBarWidth, fallback: 4),
+ changeBarWidth: nonNegativeMetric(payload?.changeBarWidth, fallback: 4),
gutterWidth: metric(payload?.gutterWidth, fallback: 50),
codePadding: metric(payload?.codePadding, fallback: 8),
textVerticalInset: metric(payload?.textVerticalInset, fallback: 3),
@@ -243,6 +243,13 @@ private struct ReviewDiffNativeStyle {
return CGFloat(value)
}
+ private static func nonNegativeMetric(_ value: Double?, fallback: CGFloat) -> CGFloat {
+ guard let value, value.isFinite, value >= 0 else {
+ return fallback
+ }
+ return CGFloat(value)
+ }
+
private static func fontWeight(_ value: String?, fallback: UIFont.Weight) -> UIFont.Weight {
switch value?.lowercased() {
case "ultralight", "ultra-light":
@@ -316,6 +323,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private var lastMetricsDebugKey = ""
private var lastVisibleRangeDebugKey = ""
private var tokensResetKey = ""
+ private var initialRowIndex: Int?
+ private var hasAppliedInitialRowIndex = false
let onDebug = EventDispatcher()
let onToggleFile = EventDispatcher()
@@ -394,6 +403,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
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",
@@ -402,6 +412,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
} catch {
rows = []
contentView.rows = []
+ hasAppliedInitialRowIndex = false
updateContentMetrics()
emitDebug("rows-decode-failed", [
"error": error.localizedDescription,
@@ -561,6 +572,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
contentView.setNeedsDisplay()
+ applyInitialRowIndexIfNeeded()
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
if debugKey != lastMetricsDebugKey {
@@ -645,6 +657,19 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
applyStyle()
}
+ func setInitialRowIndex(_ initialRowIndex: Double) {
+ let nextIndex: Int? = initialRowIndex.isFinite && initialRowIndex >= 0
+ ? Int(initialRowIndex.rounded(.down))
+ : nil
+ guard nextIndex != self.initialRowIndex else {
+ return
+ }
+
+ self.initialRowIndex = nextIndex
+ hasAppliedInitialRowIndex = false
+ applyInitialRowIndexIfNeeded()
+ }
+
private func applyStyle() {
contentView.style = ReviewDiffNativeStyle
.resolve(stylePayload)
@@ -662,6 +687,22 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
}
+
+ private func applyInitialRowIndexIfNeeded() {
+ guard !hasAppliedInitialRowIndex,
+ let initialRowIndex,
+ bounds.height > 0,
+ let rowFrame = contentView.frameForRow(at: initialRowIndex) else {
+ return
+ }
+
+ let targetScreenY = max(0, (bounds.height - rowFrame.height) * 0.3)
+ let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
+ let targetOffset = min(max(rowFrame.minY - targetScreenY, 0), maxOffset)
+ hasAppliedInitialRowIndex = true
+ scrollView.setContentOffset(CGPoint(x: 0, y: targetOffset), animated: false)
+ updateViewportFrame()
+ }
}
private enum ReviewDiffHorizontalPanKind {
@@ -820,6 +861,19 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
return style.rowHeight
}
+ func frameForRow(at index: Int) -> CGRect? {
+ guard rows.indices.contains(index), rowOffsets.indices.contains(index) else {
+ return nil
+ }
+
+ return CGRect(
+ x: 0,
+ y: rowOffsets[index],
+ width: max(viewportWidth, 1),
+ height: height(for: rows[index])
+ )
+ }
+
private func rebuildRowLayout() {
var nextOffsets: [CGFloat] = []
var nextFileHeaderRowIndices: [Int] = []
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 0c853aaec..f47fb9d24 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -101,6 +101,7 @@
"react-native-screens": "4.25.2",
"react-native-shiki-engine": "^0.3.12",
"react-native-svg": "15.15.4",
+ "react-native-webview": "^13.16.1",
"react-native-worklets": "0.8.3",
"shiki": "4.2.0",
"tailwind-merge": "^3.5.0",
diff --git a/apps/mobile/src/app/_layout.tsx b/apps/mobile/src/app/_layout.tsx
index db44e9904..968be6c14 100644
--- a/apps/mobile/src/app/_layout.tsx
+++ b/apps/mobile/src/app/_layout.tsx
@@ -30,10 +30,11 @@ import { useThemeColor } from "../lib/useThemeColor";
function AppNavigator() {
const pathname = usePathname();
- const clerkRouteIsActive = pathname === "/settings/auth";
+ const expandedSettingsRouteIsActive =
+ pathname === "/settings/archive" || pathname === "/settings/auth";
return (
- <ClerkSettingsSheetDetentProvider initiallyExpanded={clerkRouteIsActive}>
+ <ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
<AppNavigatorContent />
</ClerkSettingsSheetDetentProvider>
);
diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx
index 3a846a130..7f9962efc 100644
--- a/apps/mobile/src/app/index.tsx
+++ b/apps/mobile/src/app/index.tsx
@@ -1,13 +1,33 @@
-import { Stack, useRouter } from "expo-router";
-import { useState } from "react";
-import { Text as RNText, View } from "react-native";
+import type {
+ EnvironmentId,
+ SidebarProjectGroupingMode,
+ SidebarThreadSortOrder,
+} from "@t3tools/contracts";
+import {
+ DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
+ DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
+ DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
+} from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+import { useRouter } from "expo-router";
+import { useCallback, useMemo, useState } from "react";
import { useProjects, useThreadShells } from "../state/entities";
import { useWorkspaceState } from "../state/workspace";
import { buildThreadRoutePath } from "../lib/routes";
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
-import { useThemeColor } from "../lib/useThemeColor";
+import { HomeHeader } from "../features/home/HomeHeader";
+import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
+import { useThreadListActions } from "../features/home/useThreadListActions";
+
+interface HomeListOptions {
+ readonly selectedEnvironmentId: EnvironmentId | null;
+ readonly projectSortOrder: HomeProjectSortOrder;
+ readonly threadSortOrder: SidebarThreadSortOrder;
+ readonly projectGroupingMode: SidebarProjectGroupingMode;
+}
/* ─── Route screen ───────────────────────────────────────────────────── */
@@ -18,103 +38,82 @@ export default function HomeRouteScreen() {
const { savedConnectionsById } = useSavedRemoteConnections();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
-
- const iconColor = useThemeColor("--color-icon");
- const mutedColor = useThemeColor("--color-foreground-muted");
- const subtleColor = useThemeColor("--color-subtle");
+ const [listOptions, setListOptions] = useState<HomeListOptions>({
+ selectedEnvironmentId: null,
+ projectSortOrder:
+ DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
+ ? "updated_at"
+ : DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
+ threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
+ projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
+ });
+ const { archiveThread, confirmDeleteThread } = useThreadListActions();
+ const environments = useMemo(
+ () =>
+ Arr.sort(
+ Object.values(savedConnectionsById).map((connection) => ({
+ environmentId: connection.environmentId,
+ label: connection.environmentLabel,
+ })),
+ Order.mapInput(
+ Order.String,
+ (environment: { readonly label: string }) => environment.label,
+ ),
+ ),
+ [savedConnectionsById],
+ );
+ const selectedEnvironmentId = environments.some(
+ (environment) => environment.environmentId === listOptions.selectedEnvironmentId,
+ )
+ ? listOptions.selectedEnvironmentId
+ : null;
+ const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
+ setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
+ }, []);
+ const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
+ setListOptions((current) => ({ ...current, projectSortOrder }));
+ }, []);
+ const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
+ setListOptions((current) => ({ ...current, threadSortOrder }));
+ }, []);
+ const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
+ setListOptions((current) => ({ ...current, projectGroupingMode }));
+ }, []);
return (
<>
- <Stack.Screen
- options={{
- headerShown: true,
- headerTransparent: true,
- headerStyle: { backgroundColor: "transparent" },
- headerShadowVisible: false,
- headerTintColor: iconColor,
- headerTitle: "",
- headerSearchBarOptions: {
- placeholder: "Search threads",
- hideNavigationBar: false,
- onChangeText: (event) => {
- setSearchQuery(event.nativeEvent.text);
- },
- onCancelButtonPress: () => {
- setSearchQuery("");
- },
- allowToolbarIntegration: true,
- },
- }}
+ <HomeHeader
+ environments={environments}
+ selectedEnvironmentId={selectedEnvironmentId}
+ projectSortOrder={listOptions.projectSortOrder}
+ threadSortOrder={listOptions.threadSortOrder}
+ projectGroupingMode={listOptions.projectGroupingMode}
+ onEnvironmentChange={setSelectedEnvironmentId}
+ onOpenSettings={() => router.push("/settings")}
+ onProjectGroupingModeChange={setProjectGroupingMode}
+ onProjectSortOrderChange={setProjectSortOrder}
+ onSearchQueryChange={setSearchQuery}
+ onStartNewTask={() => router.push("/new")}
+ onThreadSortOrderChange={setThreadSortOrder}
/>
- {/* Header left: plain text, no Liquid Glass button chrome */}
- <Stack.Toolbar placement="left">
- <Stack.Toolbar.View hidesSharedBackground>
- <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
- <RNText
- style={{
- fontFamily: "DMSans_700Bold",
- fontSize: 17,
- color: iconColor,
- letterSpacing: -0.4,
- }}
- >
- T3 Code
- </RNText>
- <View
- style={{
- backgroundColor: subtleColor,
- borderRadius: 99,
- paddingHorizontal: 8,
- paddingVertical: 3,
- }}
- >
- <RNText
- style={{
- fontFamily: "DMSans_700Bold",
- fontSize: 10,
- color: mutedColor,
- letterSpacing: 1.1,
- textTransform: "uppercase",
- }}
- >
- Alpha
- </RNText>
- </View>
- </View>
- </Stack.Toolbar.View>
- </Stack.Toolbar>
-
- <Stack.Toolbar placement="right">
- <Stack.Toolbar.Button
- icon="gearshape"
- onPress={() => router.push("/settings")}
- separateBackground
- />
- </Stack.Toolbar>
-
- {/* Bottom toolbar: search + compose, visually split like iMessage */}
- <Stack.Toolbar placement="bottom">
- <Stack.Toolbar.SearchBarSlot />
- <Stack.Toolbar.Spacer width={8} sharesBackground={false} />
- <Stack.Toolbar.Button
- icon="square.and.pencil"
- onPress={() => router.push("/new")}
- separateBackground
- />
- </Stack.Toolbar>
-
<HomeScreen
- projects={projects}
- threads={threads}
catalogState={catalogState}
- savedConnectionsById={savedConnectionsById}
- searchQuery={searchQuery}
onAddConnection={() => router.push("/connections/new")}
+ onArchiveThread={archiveThread}
+ onDeleteThread={confirmDeleteThread}
onOpenEnvironments={() => router.push("/settings/environments")}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
+ projectGroupingMode={listOptions.projectGroupingMode}
+ projects={projects}
+ projectSortOrder={listOptions.projectSortOrder}
+ savedConnectionsById={savedConnectionsById}
+ searchQuery={searchQuery}
+ selectedEnvironmentId={selectedEnvironmentId}
+ threads={threads}
+ threadSortOrder={listOptions.threadSortOrder}
/>
</>
);
diff --git a/apps/mobile/src/app/settings/_layout.tsx b/apps/mobile/src/app/settings/_layout.tsx
index 86831d885..2607c2cd1 100644
--- a/apps/mobile/src/app/settings/_layout.tsx
+++ b/apps/mobile/src/app/settings/_layout.tsx
@@ -14,7 +14,7 @@ export default function SettingsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
- const handleClerkRouteTransitionEnd = useCallback(
+ const handleExpandedRouteTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
@@ -47,9 +47,14 @@ export default function SettingsLayout() {
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: handleClerkRouteTransitionEnd }}
+ listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Sign in" }}
/>
</Stack>
diff --git a/apps/mobile/src/app/settings/archive.tsx b/apps/mobile/src/app/settings/archive.tsx
new file mode 100644
index 000000000..2b900afbb
--- /dev/null
+++ b/apps/mobile/src/app/settings/archive.tsx
@@ -0,0 +1,3 @@
+import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
+
+export default ArchivedThreadsRouteScreen;
diff --git a/apps/mobile/src/app/settings/index.tsx b/apps/mobile/src/app/settings/index.tsx
index 856264d60..eae7c5fa3 100644
--- a/apps/mobile/src/app/settings/index.tsx
+++ b/apps/mobile/src/app/settings/index.tsx
@@ -65,6 +65,8 @@ function LocalSettingsRouteScreen() {
/>
</SettingsSection>
+ <ArchivedThreadsSettingsSection />
+
<AppSettingsSection />
</ScrollView>
</View>
@@ -374,6 +376,8 @@ function ConfiguredSettingsRouteScreen() {
/>
</SettingsSection>
+ <ArchivedThreadsSettingsSection />
+
<AppSettingsSection />
</ScrollView>
</View>
@@ -416,12 +420,20 @@ function AppSettingsSection() {
);
}
+function ArchivedThreadsSettingsSection() {
+ return (
+ <SettingsSection title="Threads">
+ <SettingsRow icon="archivebox" label="Archived Threads" href="/settings/archive" />
+ </SettingsSection>
+ );
+}
+
function SettingsRow(props: {
readonly disabled?: boolean;
readonly icon: SymbolName;
readonly label: string;
readonly value?: string;
- readonly href?: "/settings/environments";
+ readonly href?: "/settings/archive" | "/settings/environments";
readonly onPress?: () => void;
}) {
const icon = useThemeColor("--color-icon");
@@ -459,7 +471,9 @@ function SettingsRow(props: {
if (props.href) {
return (
<Link href={props.href} asChild>
- <Pressable>{content}</Pressable>
+ <Pressable accessibilityLabel={props.label} accessibilityRole="button">
+ {content}
+ </Pressable>
</Link>
);
}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx
index eb0ae8e07..92e90920e 100644
--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx
@@ -55,6 +55,32 @@ export default function ThreadLayout() {
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={{
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/[...path].tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/[...path].tsx
new file mode 100644
index 000000000..225c39f2e
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/[...path].tsx
@@ -0,0 +1,5 @@
+import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
+
+export default function ThreadFileRoute() {
+ return <ThreadFileScreen />;
+}
diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/index.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/index.tsx
new file mode 100644
index 000000000..b67630dbf
--- /dev/null
+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/index.tsx
@@ -0,0 +1,5 @@
+import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
+
+export default function ThreadFilesIndexRoute() {
+ return <ThreadFilesTreeScreen />;
+}
diff --git a/apps/mobile/src/components/LoadingStrip.tsx b/apps/mobile/src/components/LoadingStrip.tsx
new file mode 100644
index 000000000..9c16e1c68
--- /dev/null
+++ b/apps/mobile/src/components/LoadingStrip.tsx
@@ -0,0 +1,93 @@
+import { useEffect, useState } from "react";
+import { View } from "react-native";
+import Animated, {
+ cancelAnimation,
+ Easing,
+ useAnimatedStyle,
+ useSharedValue,
+ withRepeat,
+ withTiming,
+} from "react-native-reanimated";
+
+const INDICATOR_WIDTH_FRACTION = 0.3;
+const MIN_INDICATOR_WIDTH = 48;
+
+function LoadingStripFrame(props: {
+ readonly children: React.ReactNode;
+ readonly onLayout?: (width: number) => void;
+}) {
+ return (
+ <View
+ pointerEvents="none"
+ accessibilityElementsHidden
+ importantForAccessibility="no-hide-descendants"
+ className="absolute inset-x-0 top-0 z-10 h-0.5 overflow-hidden"
+ onLayout={
+ props.onLayout
+ ? (event) => {
+ props.onLayout?.(event.nativeEvent.layout.width);
+ }
+ : undefined
+ }
+ >
+ {props.children}
+ </View>
+ );
+}
+
+function IndeterminateLoadingStrip() {
+ const [containerWidth, setContainerWidth] = useState(0);
+ const travelProgress = useSharedValue(0);
+ const indicatorWidth = Math.max(MIN_INDICATOR_WIDTH, containerWidth * INDICATOR_WIDTH_FRACTION);
+
+ useEffect(() => {
+ travelProgress.value = 0;
+ travelProgress.value = withRepeat(
+ withTiming(1, {
+ duration: 1100,
+ easing: Easing.inOut(Easing.quad),
+ }),
+ -1,
+ false,
+ );
+
+ return () => {
+ cancelAnimation(travelProgress);
+ };
+ }, [travelProgress]);
+
+ const indicatorStyle = useAnimatedStyle(
+ () => ({
+ transform: [
+ {
+ translateX: (containerWidth + indicatorWidth) * travelProgress.value - indicatorWidth,
+ },
+ ],
+ width: indicatorWidth,
+ }),
+ [containerWidth, indicatorWidth],
+ );
+
+ return (
+ <LoadingStripFrame onLayout={setContainerWidth}>
+ <Animated.View className="h-full rounded-full bg-primary" style={indicatorStyle} />
+ </LoadingStripFrame>
+ );
+}
+
+export function LoadingStrip(props: { readonly progress?: number }) {
+ if (props.progress === undefined) {
+ return <IndeterminateLoadingStrip />;
+ }
+
+ const clampedProgress = Math.min(1, Math.max(0, props.progress));
+
+ return (
+ <LoadingStripFrame>
+ <View
+ className="h-full rounded-r-full bg-primary"
+ style={{ width: `${clampedProgress * 100}%` }}
+ />
+ </LoadingStripFrame>
+ );
+}
diff --git a/apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx b/apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx
new file mode 100644
index 000000000..d560f8db9
--- /dev/null
+++ b/apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx
@@ -0,0 +1,95 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+import { useFocusEffect } from "expo-router";
+import { useCallback, useMemo, useState } from "react";
+
+import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
+import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
+import { useArchivedThreadListActions } from "../home/useThreadListActions";
+import {
+ ArchivedThreadsScreen,
+ type ArchivedThreadsHeaderEnvironment,
+} from "./ArchivedThreadsScreen";
+import { buildArchivedThreadGroups, type ArchivedThreadSortOrder } from "./archivedThreadList";
+import {
+ refreshArchivedThreadsForEnvironment,
+ useArchivedThreadSnapshots,
+} from "./useArchivedThreadSnapshots";
+
+export function ArchivedThreadsRouteScreen() {
+ const { expand } = useClerkSettingsSheetDetent();
+ const { savedConnectionsById } = useSavedRemoteConnections();
+ const [searchQuery, setSearchQuery] = useState("");
+ const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
+ const [sortOrder, setSortOrder] = useState<ArchivedThreadSortOrder>("newest");
+ const environments = useMemo<ReadonlyArray<ArchivedThreadsHeaderEnvironment>>(
+ () =>
+ Arr.sort(
+ Object.values(savedConnectionsById).map((connection) => ({
+ environmentId: connection.environmentId,
+ label: connection.environmentLabel,
+ })),
+ Order.mapInput(Order.String, (environment: ArchivedThreadsHeaderEnvironment) =>
+ environment.label.toLocaleLowerCase(),
+ ),
+ ),
+ [savedConnectionsById],
+ );
+ const environmentIds = useMemo(
+ () => environments.map((environment) => environment.environmentId),
+ [environments],
+ );
+ const environmentLabels = useMemo(
+ () =>
+ Object.fromEntries(
+ environments.map((environment) => [environment.environmentId, environment.label]),
+ ),
+ [environments],
+ );
+ const { error, isLoading, refresh, snapshots } = useArchivedThreadSnapshots(environmentIds);
+ const groups = useMemo(
+ () =>
+ buildArchivedThreadGroups({
+ snapshots,
+ environmentLabels,
+ environmentId: selectedEnvironmentId,
+ searchQuery,
+ sortOrder,
+ }),
+ [environmentLabels, searchQuery, selectedEnvironmentId, snapshots, sortOrder],
+ );
+ const refreshChangedEnvironment = useCallback(
+ (thread: { readonly environmentId: EnvironmentId }) => {
+ refreshArchivedThreadsForEnvironment(thread.environmentId);
+ },
+ [],
+ );
+ const { unarchiveThread, confirmDeleteThread } =
+ useArchivedThreadListActions(refreshChangedEnvironment);
+
+ useFocusEffect(
+ useCallback(() => {
+ expand();
+ refresh();
+ }, [expand, refresh]),
+ );
+
+ return (
+ <ArchivedThreadsScreen
+ environments={environments}
+ error={error}
+ groups={groups}
+ isLoading={isLoading}
+ onDeleteThread={confirmDeleteThread}
+ onEnvironmentChange={setSelectedEnvironmentId}
+ onRefresh={refresh}
+ onSearchQueryChange={setSearchQuery}
+ onSortOrderChange={setSortOrder}
+ onUnarchiveThread={unarchiveThread}
+ searchQuery={searchQuery}
+ selectedEnvironmentId={selectedEnvironmentId}
+ sortOrder={sortOrder}
+ />
+ );
+}
diff --git a/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx b/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx
new file mode 100644
index 000000000..ecdd99901
--- /dev/null
+++ b/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx
@@ -0,0 +1,434 @@
+import type {
+ EnvironmentProject,
+ EnvironmentThreadShell,
+} 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 { SymbolView } from "expo-symbols";
+import { useCallback, useRef } from "react";
+import {
+ ActivityIndicator,
+ Pressable,
+ RefreshControl,
+ ScrollView,
+ useWindowDimensions,
+ View,
+} from "react-native";
+import ReanimatedSwipeable, {
+ 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 { relativeTime } from "../../lib/time";
+import { useThemeColor } from "../../lib/useThemeColor";
+import {
+ THREAD_SWIPE_ACTIONS_WIDTH,
+ THREAD_SWIPE_SPRING,
+ ThreadSwipeActions,
+} from "../home/thread-swipe-actions";
+import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
+
+export interface ArchivedThreadsHeaderEnvironment {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+}
+
+const THREAD_ACTIONS: MenuAction[] = [
+ {
+ id: "unarchive",
+ title: "Unarchive",
+ image: "arrow.uturn.backward",
+ },
+ {
+ id: "delete",
+ title: "Delete",
+ image: "trash",
+ attributes: { destructive: true },
+ },
+];
+
+function ArchivedThreadsHeader(props: {
+ readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
+ readonly selectedEnvironmentId: EnvironmentId | null;
+ readonly sortOrder: ArchivedThreadSortOrder;
+ readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
+ readonly onSearchQueryChange: (query: string) => void;
+ readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
+}) {
+ const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
+
+ return (
+ <>
+ <Stack.Screen
+ 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("");
+ },
+ },
+ }}
+ />
+
+ <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)}
+ >
+ <Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
+ </Stack.Toolbar.MenuAction>
+ ))}
+ </Stack.Toolbar.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>
+ </>
+ );
+}
+
+function ProjectGroupLabel(props: {
+ readonly environmentLabel: string | null;
+ readonly project: EnvironmentProject;
+}) {
+ return (
+ <View className="flex-row items-center gap-2.5 px-1 pb-2">
+ <ProjectFavicon
+ environmentId={props.project.environmentId}
+ projectTitle={props.project.title}
+ size={18}
+ workspaceRoot={props.project.workspaceRoot}
+ />
+ <Text
+ className="flex-1 text-[12px] font-t3-medium uppercase text-foreground-muted"
+ numberOfLines={1}
+ style={{ letterSpacing: 0.5 }}
+ >
+ {props.project.title}
+ </Text>
+ {props.environmentLabel ? (
+ <Text className="max-w-[42%] text-[11px] text-foreground-tertiary" numberOfLines={1}>
+ {props.environmentLabel}
+ </Text>
+ ) : null}
+ </View>
+ );
+}
+
+function ArchivedThreadRow(props: {
+ readonly environmentLabel: string | null;
+ readonly isLast: boolean;
+ readonly onDelete: () => void;
+ readonly onSwipeableClose: (methods: SwipeableMethods) => void;
+ readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
+ 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") {
+ props.onUnarchive();
+ } else if (event.nativeEvent.event === "delete") {
+ props.onDelete();
+ }
+ },
+ [props.onDelete, props.onUnarchive],
+ );
+
+ return (
+ <ReanimatedSwipeable
+ ref={swipeableRef}
+ animationOptions={THREAD_SWIPE_SPRING}
+ childrenContainerStyle={{ backgroundColor: cardColor }}
+ containerStyle={{ backgroundColor: cardColor }}
+ dragOffsetFromRightEdge={8}
+ enableTrackpadTwoFingerGesture
+ friction={1}
+ onSwipeableClose={() => {
+ fullSwipeArmedRef.current = false;
+ if (swipeableRef.current) {
+ props.onSwipeableClose(swipeableRef.current);
+ }
+ }}
+ onSwipeableOpenStartDrag={() => {
+ if (swipeableRef.current) {
+ props.onSwipeableWillOpen(swipeableRef.current);
+ }
+ }}
+ onSwipeableWillOpen={() => {
+ const methods = swipeableRef.current;
+ if (!methods) return;
+
+ props.onSwipeableWillOpen(methods);
+ if (fullSwipeArmedRef.current) {
+ fullSwipeArmedRef.current = false;
+ methods.close();
+ props.onDelete();
+ }
+ }}
+ overshootFriction={1}
+ overshootRight
+ renderRightActions={(_progress, translation, methods) => (
+ <ThreadSwipeActions
+ backgroundColor={cardColor}
+ fullSwipeThreshold={fullSwipeThreshold}
+ onDelete={props.onDelete}
+ onFullSwipeArmedChange={handleFullSwipeArmedChange}
+ primaryAction={{
+ accessibilityLabel: `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}
+ >
+ <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-[15px] font-t3-bold leading-[20px] text-foreground"
+ numberOfLines={1}
+ >
+ {props.thread.title}
+ </Text>
+ <Text
+ className="text-[12px] text-foreground-tertiary"
+ style={{ fontVariant: ["tabular-nums"] }}
+ >
+ {timestamp}
+ </Text>
+ </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-[11px] 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>
+ );
+}
+
+function ArchiveError(props: { readonly message: string; readonly onRetry: () => void }) {
+ return (
+ <View className="rounded-[20px] border border-danger-border bg-danger p-4">
+ <Text className="font-t3-bold text-danger-foreground">Could not load every archive</Text>
+ <Text className="mt-1 text-[13px] leading-[18px] text-foreground-muted">{props.message}</Text>
+ <Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
+ <Text className="text-[13px] font-t3-bold text-danger-foreground">Try again</Text>
+ </Pressable>
+ </View>
+ );
+}
+
+export function ArchivedThreadsScreen(props: {
+ readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
+ readonly error: string | null;
+ readonly groups: ReadonlyArray<ArchivedThreadGroup>;
+ readonly isLoading: boolean;
+ readonly searchQuery: string;
+ readonly selectedEnvironmentId: EnvironmentId | null;
+ readonly sortOrder: ArchivedThreadSortOrder;
+ readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
+ readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
+ readonly onRefresh: () => void;
+ readonly onSearchQueryChange: (query: string) => void;
+ readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
+ readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
+}) {
+ const openSwipeableRef = useRef<SwipeableMethods | null>(null);
+ const refreshTint = useThemeColor("--color-icon");
+ const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
+ if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
+ openSwipeableRef.current.close();
+ }
+ openSwipeableRef.current = methods;
+ }, []);
+ const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
+ if (openSwipeableRef.current === methods) {
+ openSwipeableRef.current = null;
+ }
+ }, []);
+ const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
+ const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
+
+ return (
+ <View className="flex-1 bg-sheet">
+ <ArchivedThreadsHeader
+ environments={props.environments}
+ onEnvironmentChange={props.onEnvironmentChange}
+ onSearchQueryChange={props.onSearchQueryChange}
+ onSortOrderChange={props.onSortOrderChange}
+ selectedEnvironmentId={props.selectedEnvironmentId}
+ sortOrder={props.sortOrder}
+ />
+
+ <ScrollView
+ className="flex-1"
+ contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
+ contentInsetAdjustmentBehavior="automatic"
+ keyboardDismissMode="on-drag"
+ keyboardShouldPersistTaps="handled"
+ onScrollBeginDrag={() => openSwipeableRef.current?.close()}
+ refreshControl={
+ <RefreshControl
+ onRefresh={props.onRefresh}
+ refreshing={props.isLoading && !isInitialLoad}
+ tintColor={String(refreshTint)}
+ />
+ }
+ showsVerticalScrollIndicator={false}
+ >
+ {props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
+
+ {isInitialLoad ? (
+ <View className="items-center py-16">
+ <ActivityIndicator color={refreshTint} />
+ <Text className="mt-3 text-[13px] text-foreground-muted">Loading archive…</Text>
+ </View>
+ ) : props.groups.length === 0 ? (
+ <EmptyState
+ detail={
+ isFiltered
+ ? "Try another search or environment."
+ : "Threads you archive will appear here."
+ }
+ title={isFiltered ? "No matching threads" : "No archived threads"}
+ />
+ ) : (
+ props.groups.map((group) => {
+ const environmentLabel =
+ props.environments.find(
+ (environment) => environment.environmentId === group.project.environmentId,
+ )?.label ?? null;
+
+ return (
+ <View key={group.key} collapsable={false}>
+ <ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
+ <View
+ className="overflow-hidden rounded-[20px] bg-card"
+ style={{ borderCurve: "continuous" }}
+ >
+ {group.threads.map((thread, index) => (
+ <ArchivedThreadRow
+ key={`${thread.environmentId}:${thread.id}`}
+ environmentLabel={environmentLabel}
+ isLast={index === group.threads.length - 1}
+ onDelete={() => props.onDeleteThread(thread)}
+ onSwipeableClose={handleSwipeableClose}
+ onSwipeableWillOpen={handleSwipeableWillOpen}
+ onUnarchive={() => props.onUnarchiveThread(thread)}
+ thread={thread}
+ />
+ ))}
+ </View>
+ </View>
+ );
+ })
+ )}
+ </ScrollView>
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/archive/archivedThreadList.test.ts b/apps/mobile/src/features/archive/archivedThreadList.test.ts
new file mode 100644
index 000000000..6cd530ab3
--- /dev/null
+++ b/apps/mobile/src/features/archive/archivedThreadList.test.ts
@@ -0,0 +1,144 @@
+import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
+import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
+import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { buildArchivedThreadGroups } from "./archivedThreadList";
+
+const environmentId = EnvironmentId.make("environment-1");
+
+function makeProject(
+ input: Partial<OrchestrationProjectShell> & Pick<OrchestrationProjectShell, "id" | "title">,
+): OrchestrationProjectShell {
+ return {
+ workspaceRoot: `/workspaces/${input.id}`,
+ repositoryIdentity: null,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-01T00:00:00.000Z",
+ ...input,
+ };
+}
+
+function makeThread(
+ input: Partial<OrchestrationThreadShell> &
+ Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
+): OrchestrationThreadShell {
+ return {
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-01T00:00:00.000Z",
+ archivedAt: "2026-06-02T00:00:00.000Z",
+ session: null,
+ latestUserMessageAt: null,
+ hasPendingApprovals: false,
+ hasPendingUserInput: false,
+ hasActionableProposedPlan: false,
+ ...input,
+ };
+}
+
+function makeSnapshot(
+ projects: ReadonlyArray<OrchestrationProjectShell>,
+ threads: ReadonlyArray<OrchestrationThreadShell>,
+ targetEnvironmentId = environmentId,
+): ArchivedSnapshotEntry {
+ return {
+ environmentId: targetEnvironmentId,
+ snapshot: {
+ snapshotSequence: 1,
+ projects,
+ threads,
+ updatedAt: "2026-06-04T00:00:00.000Z",
+ },
+ };
+}
+
+describe("buildArchivedThreadGroups", () => {
+ it("groups archived threads by project and sorts newest first", () => {
+ const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
+ const older = makeThread({
+ id: ThreadId.make("thread-older"),
+ projectId: project.id,
+ title: "Older",
+ });
+ const newer = makeThread({
+ archivedAt: "2026-06-03T00:00:00.000Z",
+ id: ThreadId.make("thread-newer"),
+ projectId: project.id,
+ title: "Newer",
+ });
+
+ const result = buildArchivedThreadGroups({
+ snapshots: [makeSnapshot([project], [older, newer])],
+ environmentLabels: { [environmentId]: "Julius's MacBook Pro" },
+ environmentId: null,
+ searchQuery: "",
+ sortOrder: "newest",
+ });
+
+ expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-newer", "thread-older"]);
+ });
+
+ it("filters by environment and matches project, thread, and branch text", () => {
+ const secondEnvironmentId = EnvironmentId.make("environment-2");
+ const firstProject = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
+ const secondProject = makeProject({ id: ProjectId.make("project-2"), title: "Website" });
+ const firstThread = makeThread({
+ branch: "fix/archive-screen",
+ id: ThreadId.make("thread-1"),
+ projectId: firstProject.id,
+ title: "Build settings route",
+ });
+ const secondThread = makeThread({
+ id: ThreadId.make("thread-2"),
+ projectId: secondProject.id,
+ title: "Unrelated",
+ });
+ const snapshots = [
+ makeSnapshot([firstProject], [firstThread]),
+ makeSnapshot([secondProject], [secondThread], secondEnvironmentId),
+ ];
+
+ const result = buildArchivedThreadGroups({
+ snapshots,
+ environmentLabels: {
+ [environmentId]: "Local",
+ [secondEnvironmentId]: "Remote",
+ },
+ environmentId,
+ searchQuery: "archive-screen",
+ sortOrder: "oldest",
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.project.environmentId).toBe(environmentId);
+ expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-1"]);
+ });
+
+ it("ignores non-archived entries returned in a snapshot", () => {
+ const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
+ const active = makeThread({
+ archivedAt: null,
+ id: ThreadId.make("thread-active"),
+ projectId: project.id,
+ title: "Active",
+ });
+
+ const result = buildArchivedThreadGroups({
+ snapshots: [makeSnapshot([project], [active])],
+ environmentLabels: {},
+ environmentId: null,
+ searchQuery: "",
+ sortOrder: "newest",
+ });
+
+ expect(result).toEqual([]);
+ });
+});
diff --git a/apps/mobile/src/features/archive/archivedThreadList.ts b/apps/mobile/src/features/archive/archivedThreadList.ts
new file mode 100644
index 000000000..6146bba20
--- /dev/null
+++ b/apps/mobile/src/features/archive/archivedThreadList.ts
@@ -0,0 +1,106 @@
+import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
+import {
+ scopeProject,
+ scopeThreadShell,
+ type EnvironmentProject,
+ type EnvironmentThreadShell,
+} from "@t3tools/client-runtime/state/shell";
+import type { EnvironmentId } from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+
+import { scopedProjectKey } from "../../lib/scopedEntities";
+
+export type ArchivedThreadSortOrder = "newest" | "oldest";
+
+export interface ArchivedThreadGroup {
+ readonly key: string;
+ readonly project: EnvironmentProject;
+ readonly threads: ReadonlyArray<EnvironmentThreadShell>;
+}
+
+function archiveTimestamp(thread: EnvironmentThreadShell): number {
+ const timestamp = Date.parse(thread.archivedAt ?? thread.updatedAt);
+ return Number.isNaN(timestamp) ? 0 : timestamp;
+}
+
+function matchesQuery(value: string | null, query: string): boolean {
+ return value?.toLocaleLowerCase().includes(query) ?? false;
+}
+
+export function buildArchivedThreadGroups(input: {
+ readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
+ readonly environmentLabels: Readonly<Record<string, string>>;
+ readonly environmentId: EnvironmentId | null;
+ readonly searchQuery: string;
+ readonly sortOrder: ArchivedThreadSortOrder;
+}): ReadonlyArray<ArchivedThreadGroup> {
+ const query = input.searchQuery.trim().toLocaleLowerCase();
+ const groups: ArchivedThreadGroup[] = [];
+
+ for (const entry of input.snapshots) {
+ if (input.environmentId !== null && input.environmentId !== entry.environmentId) {
+ continue;
+ }
+
+ const environmentLabel = input.environmentLabels[entry.environmentId] ?? null;
+ const threadsByProjectId = new Map<string, EnvironmentThreadShell[]>();
+ for (const thread of entry.snapshot.threads) {
+ if (thread.archivedAt === null) {
+ continue;
+ }
+ const threads = threadsByProjectId.get(thread.projectId) ?? [];
+ threads.push(scopeThreadShell(entry.environmentId, thread));
+ threadsByProjectId.set(thread.projectId, threads);
+ }
+
+ for (const rawProject of entry.snapshot.projects) {
+ const project = scopeProject(entry.environmentId, rawProject);
+ const projectThreads = threadsByProjectId.get(project.id) ?? [];
+ const groupMatches =
+ query.length === 0 ||
+ matchesQuery(project.title, query) ||
+ matchesQuery(project.workspaceRoot, query) ||
+ matchesQuery(environmentLabel, query);
+ const matchingThreads = groupMatches
+ ? projectThreads
+ : projectThreads.filter(
+ (thread) => matchesQuery(thread.title, query) || matchesQuery(thread.branch, query),
+ );
+
+ if (matchingThreads.length === 0) {
+ continue;
+ }
+
+ const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
+ groups.push({
+ key: scopedProjectKey(project.environmentId, project.id),
+ project,
+ threads: Arr.sort(
+ matchingThreads,
+ Order.mapInput(
+ Order.Struct({ timestamp: timestampOrder, title: Order.String, id: Order.String }),
+ (thread: EnvironmentThreadShell) => ({
+ timestamp: archiveTimestamp(thread),
+ title: thread.title,
+ id: thread.id,
+ }),
+ ),
+ ),
+ });
+ }
+ }
+
+ const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
+ return Arr.sort(
+ groups,
+ Order.mapInput(
+ Order.Struct({ timestamp: timestampOrder, title: Order.String, key: Order.String }),
+ (group: ArchivedThreadGroup) => ({
+ timestamp: group.threads[0] ? archiveTimestamp(group.threads[0]) : 0,
+ title: group.project.title,
+ key: group.key,
+ }),
+ ),
+ );
+}
diff --git a/apps/mobile/src/features/archive/useArchivedThreadSnapshots.ts b/apps/mobile/src/features/archive/useArchivedThreadSnapshots.ts
new file mode 100644
index 000000000..d18cc230c
--- /dev/null
+++ b/apps/mobile/src/features/archive/useArchivedThreadSnapshots.ts
@@ -0,0 +1,47 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ type ArchivedSnapshotEntry,
+ createArchivedThreadSnapshotsAtomFamily,
+ makeArchivedThreadsEnvironmentKey,
+} from "@t3tools/client-runtime/state/threads";
+import type { EnvironmentId } from "@t3tools/contracts";
+import { useCallback, useMemo } from "react";
+
+import { appAtomRegistry } from "../../state/atom-registry";
+import { orchestrationEnvironment } from "../../state/orchestration";
+
+function archivedSnapshotAtom(environmentId: EnvironmentId) {
+ return orchestrationEnvironment.archivedShellSnapshot({
+ environmentId,
+ input: {},
+ });
+}
+
+const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
+ getSnapshotAtom: archivedSnapshotAtom,
+ labelPrefix: "mobile:archived-thread-snapshots",
+});
+
+export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
+ appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
+}
+
+export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
+ readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
+ readonly error: string | null;
+ readonly isLoading: boolean;
+ readonly refresh: () => void;
+} {
+ const environmentKey = useMemo(
+ () => makeArchivedThreadsEnvironmentKey(environmentIds),
+ [environmentIds],
+ );
+ const result = useAtomValue(archivedSnapshotsAtom(environmentKey));
+ const refresh = useCallback(() => {
+ for (const environmentId of environmentIds) {
+ appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
+ }
+ }, [environmentIds]);
+
+ return { ...result, refresh };
+}
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
index 7bd53f677..4a6816634 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
@@ -110,6 +110,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly styleJson?: string;
readonly rowHeight: number;
readonly contentWidth: number;
+ readonly initialRowIndex?: number;
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx
new file mode 100644
index 000000000..1f6720cb7
--- /dev/null
+++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx
@@ -0,0 +1,166 @@
+import { useMemo } from "react";
+import {
+ Markdown,
+ type CustomRenderers,
+ type NodeStyleOverrides,
+ type PartialMarkdownTheme,
+} from "react-native-nitro-markdown";
+import { Linking, ScrollView, Text as NativeText, View } from "react-native";
+
+import { useThemeColor } from "../../lib/useThemeColor";
+import {
+ hasNativeSelectableMarkdownText,
+ SelectableMarkdownText,
+ type NativeMarkdownTextStyle,
+} from "../../native/SelectableMarkdownText";
+
+interface MarkdownPreviewStyles {
+ readonly theme: PartialMarkdownTheme;
+ readonly styles: NodeStyleOverrides;
+ readonly renderers: CustomRenderers;
+ readonly nativeTextStyle: NativeMarkdownTextStyle;
+}
+
+function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
+ const body = String(useThemeColor("--color-md-body"));
+ const strong = String(useThemeColor("--color-md-strong"));
+ const link = String(useThemeColor("--color-md-link"));
+ const blockquoteBorder = String(useThemeColor("--color-md-blockquote-border"));
+ const blockquoteBackground = String(useThemeColor("--color-md-blockquote-bg"));
+ const codeBackground = String(useThemeColor("--color-md-code-bg"));
+ const codeText = String(useThemeColor("--color-md-code-text"));
+ const horizontalRule = String(useThemeColor("--color-md-hr"));
+
+ return useMemo(() => {
+ const renderers: CustomRenderers = {
+ link: ({ href, children }) => (
+ <NativeText
+ onPress={() => {
+ if (href) {
+ void Linking.openURL(href);
+ }
+ }}
+ style={{
+ color: link,
+ fontFamily: "DMSans_500Medium",
+ textDecorationLine: "none",
+ }}
+ >
+ {children}
+ </NativeText>
+ ),
+ };
+
+ return {
+ theme: {
+ colors: {
+ text: body,
+ heading: strong,
+ link,
+ blockquote: blockquoteBorder,
+ border: horizontalRule,
+ surfaceLight: blockquoteBackground,
+ accent: link,
+ tableBorder: horizontalRule,
+ tableHeader: blockquoteBackground,
+ tableHeaderText: strong,
+ code: codeText,
+ codeBackground,
+ },
+ },
+ styles: {
+ text: {
+ color: body,
+ fontFamily: "DMSans_400Regular",
+ fontSize: 15,
+ lineHeight: 22,
+ },
+ heading: {
+ color: strong,
+ fontFamily: "DMSans_700Bold",
+ },
+ strong: {
+ color: strong,
+ fontFamily: "DMSans_700Bold",
+ },
+ link: {
+ color: link,
+ fontFamily: "DMSans_500Medium",
+ },
+ blockquote: {
+ backgroundColor: blockquoteBackground,
+ borderLeftColor: blockquoteBorder,
+ borderLeftWidth: 3,
+ paddingLeft: 12,
+ },
+ code: {
+ backgroundColor: codeBackground,
+ color: codeText,
+ fontFamily: "ui-monospace",
+ },
+ codeBlock: {
+ backgroundColor: codeBackground,
+ borderRadius: 12,
+ color: codeText,
+ fontFamily: "ui-monospace",
+ padding: 12,
+ },
+ hr: {
+ backgroundColor: horizontalRule,
+ },
+ },
+ renderers,
+ nativeTextStyle: {
+ color: body,
+ strongColor: strong,
+ mutedColor: body,
+ linkColor: link,
+ inlineCodeColor: codeText,
+ codeColor: codeText,
+ codeBackgroundColor: codeBackground,
+ codeBlockBackgroundColor: codeBackground,
+ fileTextColor: codeText,
+ skillTextColor: codeText,
+ quoteMarkerColor: blockquoteBorder,
+ dividerColor: horizontalRule,
+ fontSize: 15,
+ lineHeight: 22,
+ fontFamily: "DMSans_400Regular",
+ headingFontFamily: "DMSans_700Bold",
+ boldFontFamily: "DMSans_700Bold",
+ },
+ };
+ }, [
+ blockquoteBackground,
+ blockquoteBorder,
+ body,
+ codeBackground,
+ codeText,
+ horizontalRule,
+ link,
+ strong,
+ ]);
+}
+
+export function FileMarkdownPreview(props: { readonly markdown: string }) {
+ const styles = useMarkdownPreviewStyles();
+
+ return (
+ <ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
+ <View className="mx-auto w-full max-w-[760px]">
+ {hasNativeSelectableMarkdownText() ? (
+ <SelectableMarkdownText markdown={props.markdown} textStyle={styles.nativeTextStyle} />
+ ) : (
+ <Markdown
+ options={{ gfm: true }}
+ renderers={styles.renderers}
+ styles={styles.styles}
+ theme={styles.theme}
+ >
+ {props.markdown}
+ </Markdown>
+ )}
+ </View>
+ </ScrollView>
+ );
+}
diff --git a/apps/mobile/src/features/files/FileTreeBrowser.tsx b/apps/mobile/src/features/files/FileTreeBrowser.tsx
new file mode 100644
index 000000000..ff9577a4a
--- /dev/null
+++ b/apps/mobile/src/features/files/FileTreeBrowser.tsx
@@ -0,0 +1,191 @@
+import type { ProjectEntry } from "@t3tools/contracts";
+import { SymbolView } from "expo-symbols";
+import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
+
+import { AppText as Text } from "../../components/AppText";
+import { PierreEntryIcon } from "../../components/PierreEntryIcon";
+import { cn } from "../../lib/cn";
+import { useThemeColor } from "../../lib/useThemeColor";
+import {
+ buildFileTree,
+ defaultExpandedTreePaths,
+ flattenFileTree,
+ type VisibleFileTreeNode,
+} from "./fileTree";
+
+function ancestorPaths(path: string): ReadonlyArray<string> {
+ const parts = path.split("/").filter(Boolean);
+ const ancestors: string[] = [];
+ for (let index = 1; index < parts.length; index += 1) {
+ ancestors.push(parts.slice(0, index).join("/"));
+ }
+ return ancestors;
+}
+
+const FileTreeRow = memo(function FileTreeRow(props: {
+ readonly item: VisibleFileTreeNode;
+ readonly selectedPath: string | null;
+ readonly expanded: boolean;
+ readonly iconColor: string;
+ readonly onPressDirectory: (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}
+ onPress={() => {
+ if (node.kind === "directory") {
+ props.onPressDirectory(node.path);
+ return;
+ }
+ props.onPressFile(node.path);
+ }}
+ className={cn(
+ "mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
+ selected && "bg-subtle-strong",
+ )}
+ style={{ paddingLeft: 8 + depth * 18 }}
+ >
+ {node.kind === "directory" ? (
+ <SymbolView
+ name={props.expanded ? "chevron.down" : "chevron.right"}
+ size={12}
+ tintColor={props.iconColor}
+ type="monochrome"
+ />
+ ) : (
+ <View className="w-3" />
+ )}
+ <PierreEntryIcon path={node.path} kind={node.kind} size={17} />
+ <Text
+ className={cn(
+ "min-w-0 flex-1 text-[14px] leading-[19px]",
+ selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
+ )}
+ numberOfLines={1}
+ >
+ {node.name}
+ </Text>
+ {node.kind === "directory" ? (
+ <Text className="text-[11px] font-t3-medium text-foreground-tertiary">
+ {node.children.length}
+ </Text>
+ ) : null}
+ </Pressable>
+ );
+});
+
+export function FileTreeBrowser(props: {
+ readonly entries: ReadonlyArray<ProjectEntry>;
+ readonly error: string | null;
+ readonly isPending: boolean;
+ readonly searchQuery: string;
+ readonly selectedPath: string | null;
+ readonly onRefresh: () => void;
+ readonly onSelectFile: (path: string) => void;
+}) {
+ const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
+ const iconColor = String(useThemeColor("--color-icon-muted"));
+
+ const tree = useMemo(() => buildFileTree(props.entries), [props.entries]);
+ const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
+ const visibleNodes = useMemo(
+ () =>
+ flattenFileTree({
+ nodes: tree,
+ expanded: expandedPaths,
+ searchQuery: props.searchQuery,
+ }),
+ [expandedPaths, props.searchQuery, tree],
+ );
+
+ useEffect(() => {
+ setExpandedPaths((current) => {
+ if (current.size > 0 || defaultExpanded.size === 0) {
+ return current;
+ }
+ return new Set(defaultExpanded);
+ });
+ }, [defaultExpanded]);
+
+ useEffect(() => {
+ if (!props.selectedPath) {
+ return;
+ }
+ setExpandedPaths((current) => {
+ const next = new Set(current);
+ for (const ancestor of ancestorPaths(props.selectedPath ?? "")) {
+ next.add(ancestor);
+ }
+ return next;
+ });
+ }, [props.selectedPath]);
+
+ const toggleDirectory = useCallback((path: string) => {
+ setExpandedPaths((current) => {
+ const next = new Set(current);
+ if (next.has(path)) {
+ next.delete(path);
+ } else {
+ next.add(path);
+ }
+ return next;
+ });
+ }, []);
+
+ return (
+ <View className="flex-1 bg-sheet">
+ {props.error && props.entries.length === 0 ? (
+ <View className="px-4 py-5">
+ <Text className="text-[13px] font-t3-bold text-foreground">Files unavailable</Text>
+ <Text className="mt-1 text-[12px] leading-[18px] text-foreground-muted">
+ {props.error}
+ </Text>
+ </View>
+ ) : (
+ <FlatList
+ data={visibleNodes}
+ keyExtractor={(item) => item.node.path}
+ contentInsetAdjustmentBehavior="automatic"
+ keyboardDismissMode="on-drag"
+ keyboardShouldPersistTaps="handled"
+ contentContainerStyle={{ paddingVertical: 8 }}
+ refreshControl={
+ <RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
+ }
+ renderItem={({ item }) => (
+ <FileTreeRow
+ item={item}
+ selectedPath={props.selectedPath}
+ expanded={expandedPaths.has(item.node.path)}
+ iconColor={iconColor}
+ onPressDirectory={toggleDirectory}
+ onPressFile={props.onSelectFile}
+ />
+ )}
+ ListEmptyComponent={
+ <View className="px-4 py-5">
+ {props.isPending ? (
+ <ActivityIndicator size="small" />
+ ) : (
+ <>
+ <Text className="text-[13px] font-t3-bold text-foreground">No files found</Text>
+ <Text className="mt-1 text-[12px] leading-[18px] text-foreground-muted">
+ {props.searchQuery.trim().length > 0
+ ? "Try a different search."
+ : "The workspace file index is empty."}
+ </Text>
+ </>
+ )}
+ </View>
+ }
+ />
+ )}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/files/SourceFileSurface.tsx b/apps/mobile/src/features/files/SourceFileSurface.tsx
new file mode 100644
index 000000000..5f3647d73
--- /dev/null
+++ b/apps/mobile/src/features/files/SourceFileSurface.tsx
@@ -0,0 +1,252 @@
+import { useAtomValue } from "@effect/atom-react";
+import { AsyncResult } from "effect/unstable/reactivity";
+import type { ComponentType } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef } from "react";
+import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
+
+import { AppText as Text } from "../../components/AppText";
+import { LoadingStrip } from "../../components/LoadingStrip";
+import {
+ type NativeReviewDiffViewProps,
+ resolveNativeReviewDiffView,
+} from "../diffs/nativeReviewDiffSurface";
+import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
+import {
+ REVIEW_DIFF_LINE_HEIGHT,
+ REVIEW_MONO_FONT_FAMILY,
+ renderVisibleWhitespace,
+} from "../review/reviewDiffRendering";
+import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
+import { cn } from "../../lib/cn";
+import {
+ buildNativeSourceRows,
+ buildNativeSourceTokens,
+ NATIVE_SOURCE_CONTENT_WIDTH,
+ NATIVE_SOURCE_ROW_HEIGHT,
+ NATIVE_SOURCE_STYLE,
+ nativeSourceRowId,
+} from "./nativeSourceFileAdapter";
+import { sourceHighlightAtom } from "./sourceHighlightingState";
+
+const SOURCE_LINE_HEIGHT = 24;
+const SOURCE_LINE_NUMBER_WIDTH = 58;
+const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
+
+interface SourceFileSurfaceProps {
+ readonly contents: string;
+ readonly path: string;
+ readonly initialLine?: number | null;
+}
+
+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;
+ readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
+ readonly highlighted: boolean;
+}) {
+ return (
+ <View
+ className={cn("flex-row", props.highlighted && "bg-primary/10")}
+ style={{ minHeight: SOURCE_LINE_HEIGHT }}
+ >
+ <NativeText
+ className="select-none pr-3 text-right text-[11px] leading-[24px] text-foreground-tertiary"
+ style={{
+ width: SOURCE_LINE_NUMBER_WIDTH,
+ fontFamily: REVIEW_MONO_FONT_FAMILY,
+ }}
+ >
+ {props.index + 1}
+ </NativeText>
+ <NativeText
+ selectable
+ numberOfLines={1}
+ className="text-[13px] font-medium leading-[24px] text-foreground"
+ style={{ fontFamily: REVIEW_MONO_FONT_FAMILY, minWidth: 320 }}
+ >
+ {props.tokens && props.tokens.length > 0
+ ? (() => {
+ let offset = 0;
+ return props.tokens.map((token) => {
+ const start = offset;
+ offset += token.content.length;
+
+ const fontWeight =
+ token.fontStyle !== null && (token.fontStyle & 2) === 2
+ ? ("700" as const)
+ : ("500" as const);
+ const fontStyle =
+ token.fontStyle !== null && (token.fontStyle & 1) === 1
+ ? ("italic" as const)
+ : ("normal" as const);
+
+ return (
+ <NativeText
+ key={`${start}:${token.content.length}:${token.color ?? ""}`}
+ selectable
+ style={{
+ color: token.color ?? undefined,
+ fontFamily: REVIEW_MONO_FONT_FAMILY,
+ fontWeight,
+ fontStyle,
+ }}
+ >
+ {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
+ </NativeText>
+ );
+ });
+ })()
+ : renderVisibleWhitespace(props.line || " ")}
+ </NativeText>
+ </View>
+ );
+});
+
+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 targetIndex =
+ props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
+ ? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
+ : null;
+ const highlightAtom = useMemo(
+ () => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),
+ [normalizedContents, props.path, theme],
+ );
+ const highlightResult = useAtomValue(highlightAtom);
+ const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
+ const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
+ ? "error"
+ : AsyncResult.isSuccess(highlightResult)
+ ? "ready"
+ : "highlighting";
+
+ return { lines, status, targetIndex, theme, tokens };
+}
+
+function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
+ if (props.status === "highlighting") {
+ return <LoadingStrip />;
+ }
+ if (props.status === "error") {
+ return (
+ <View className="border-b border-border bg-card px-4 py-2">
+ <Text className="text-[11px] font-t3-medium uppercase text-foreground-muted">
+ Plain text
+ </Text>
+ </View>
+ );
+ }
+ return null;
+}
+
+function NativeSourceFileSurface(
+ props: SourceFileSurfaceProps & {
+ readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
+ },
+) {
+ const { NativeView } = props;
+ const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
+ const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
+ const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
+ const selectedRowIdsJson = useMemo(
+ () => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
+ [targetIndex],
+ );
+ const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
+
+ return (
+ <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}
+ contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
+ initialRowIndex={targetIndex ?? -1}
+ rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
+ rowsJson={rowsJson}
+ selectedRowIdsJson={selectedRowIdsJson}
+ styleJson={NATIVE_SOURCE_STYLE_JSON}
+ themeJson={themeJson}
+ tokensJson={tokensJson}
+ />
+ </View>
+ );
+}
+
+function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
+ const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
+ const listRef = useRef<FlatList<string>>(null);
+
+ useEffect(() => {
+ if (targetIndex === null) {
+ return;
+ }
+ const frame = requestAnimationFrame(() => {
+ listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [props.path, targetIndex]);
+
+ const renderLine = useCallback(
+ ({ item, index }: { item: string; index: number }) => (
+ <HighlightedSourceLine
+ index={index}
+ line={item}
+ tokens={tokens?.[index] ?? null}
+ highlighted={index === targetIndex}
+ />
+ ),
+ [targetIndex, tokens],
+ );
+
+ return (
+ <View className="relative flex-1 bg-card">
+ <SourceHighlightStatusView status={status} />
+ <ScrollView horizontal bounces={false} className="flex-1">
+ <FlatList
+ ref={listRef}
+ data={lines}
+ keyExtractor={(_line, index) => String(index)}
+ initialNumToRender={80}
+ maxToRenderPerBatch={80}
+ windowSize={12}
+ getItemLayout={(_data, index) => ({
+ length: SOURCE_LINE_HEIGHT,
+ offset: SOURCE_LINE_HEIGHT * index,
+ index,
+ })}
+ contentContainerStyle={{
+ minWidth: "100%",
+ paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
+ paddingTop: 8,
+ }}
+ renderItem={renderLine}
+ />
+ </ScrollView>
+ </View>
+ );
+}
+
+export function SourceFileSurface(props: SourceFileSurfaceProps) {
+ const NativeView = resolveNativeReviewDiffView();
+ return NativeView ? (
+ <NativeSourceFileSurface {...props} NativeView={NativeView} />
+ ) : (
+ <JavaScriptSourceFileSurface {...props} />
+ );
+}
diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
new file mode 100644
index 000000000..f730e4616
--- /dev/null
+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
@@ -0,0 +1,631 @@
+import Stack from "expo-router/stack";
+import { SymbolView } from "expo-symbols";
+import { useLocalSearchParams, useRouter } from "expo-router";
+import { useCallback, useMemo, useRef, useState } from "react";
+import {
+ ActivityIndicator,
+ Linking,
+ Pressable,
+ ScrollView,
+ Text as RNText,
+ View,
+} from "react-native";
+import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
+import {
+ EnvironmentId,
+ type ProjectListEntriesResult,
+ type ProjectReadFileResult,
+ ThreadId,
+} from "@t3tools/contracts";
+
+import { AppText as Text } from "../../components/AppText";
+import { CopyTextButton } from "../../components/CopyTextButton";
+import { EmptyState } from "../../components/EmptyState";
+import { LoadingScreen } from "../../components/LoadingScreen";
+import { cn } from "../../lib/cn";
+import { buildThreadFilesNavigation } from "../../lib/routes";
+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 { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
+import { FileMarkdownPreview } from "./FileMarkdownPreview";
+import { FileTreeBrowser } from "./FileTreeBrowser";
+import { SourceFileSurface } from "./SourceFileSurface";
+import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
+import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
+import {
+ basename,
+ fileBreadcrumbs,
+ isBrowserPreviewFile,
+ isImagePreviewFile,
+ isMarkdownPreviewFile,
+ isSvgImagePreviewFile,
+} from "./filePath";
+import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
+
+type FileViewMode = "preview" | "source";
+
+function firstRouteParam(value: string | string[] | undefined): string | null {
+ if (Array.isArray(value)) {
+ return value[0] ?? null;
+ }
+
+ return value ?? null;
+}
+
+function normalizeRoutePath(value: string | string[] | undefined): string | null {
+ const path = Array.isArray(value) ? value.join("/") : value;
+ if (path === undefined || path.trim().length === 0) {
+ return null;
+ }
+ return path;
+}
+
+function normalizeRouteLine(value: string | null): number | null {
+ if (value === null) {
+ return null;
+ }
+ const parsed = Number(value);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
+}
+
+function defaultViewMode(path: string | null): FileViewMode {
+ return path !== null && (isBrowserPreviewFile(path) || isImagePreviewFile(path))
+ ? "preview"
+ : "source";
+}
+
+function ModeButton(props: {
+ readonly active: boolean;
+ readonly icon: "doc.text" | "eye";
+ readonly label: string;
+ readonly onPress: () => void;
+}) {
+ const iconColor = String(
+ useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"),
+ );
+
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ selected: props.active }}
+ className={cn(
+ "h-8 flex-row items-center justify-center gap-1.5 rounded-full px-3 active:opacity-70",
+ props.active ? "bg-primary" : "bg-subtle",
+ )}
+ onPress={props.onPress}
+ >
+ <SymbolView name={props.icon} size={13} tintColor={iconColor} type="monochrome" />
+ <Text
+ className={cn(
+ "text-[12px] font-t3-bold",
+ props.active ? "text-primary-foreground" : "text-foreground-muted",
+ )}
+ >
+ {props.label}
+ </Text>
+ </Pressable>
+ );
+}
+
+function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) {
+ const gradientId = `file-breadcrumb-${props.side}-fade`;
+ const isLeft = props.side === "left";
+
+ return (
+ <View
+ pointerEvents="none"
+ className={cn("absolute inset-y-0 w-7", isLeft ? "left-0" : "right-0")}
+ >
+ <Svg width="100%" height="100%">
+ <Defs>
+ <LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
+ <Stop offset="0%" stopColor={props.color} stopOpacity={isLeft ? 1 : 0} />
+ <Stop offset="100%" stopColor={props.color} stopOpacity={isLeft ? 0 : 1} />
+ </LinearGradient>
+ </Defs>
+ <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
+ </Svg>
+ </View>
+ );
+}
+
+function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) {
+ const iconColor = String(useThemeColor("--color-icon-muted"));
+ const cardColor = String(useThemeColor("--color-card"));
+ const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 });
+ const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false });
+ const breadcrumbs = useMemo(
+ () => fileBreadcrumbs(props.projectName, props.relativePath),
+ [props.projectName, props.relativePath],
+ );
+ const updateFadeVisibility = useCallback(
+ (metrics: Partial<(typeof scrollMetrics)["current"]>) => {
+ Object.assign(scrollMetrics.current, metrics);
+ const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current;
+ const maxOffset = Math.max(0, contentWidth - viewportWidth);
+ const next = {
+ left: maxOffset > 1 && offsetX > 1,
+ right: maxOffset > 1 && offsetX < maxOffset - 1,
+ };
+
+ setFadeVisibility((current) =>
+ current.left === next.left && current.right === next.right ? current : next,
+ );
+ },
+ [],
+ );
+
+ return (
+ <View className="min-w-0 flex-1">
+ <ScrollView
+ horizontal
+ showsHorizontalScrollIndicator={false}
+ onContentSizeChange={(contentWidth) => {
+ updateFadeVisibility({ contentWidth });
+ }}
+ onLayout={(event) => {
+ updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width });
+ }}
+ onScroll={(event) => {
+ updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x });
+ }}
+ scrollEventThrottle={16}
+ >
+ <View className="h-8 flex-row items-center">
+ {breadcrumbs.map((crumb, index) => (
+ <View key={crumb.path || "project"} className="flex-row items-center">
+ {index > 0 ? (
+ <SymbolView
+ name="chevron.right"
+ size={10}
+ tintColor={iconColor}
+ type="monochrome"
+ />
+ ) : null}
+ <Text
+ className={cn(
+ "max-w-[180px] px-1 text-[12px]",
+ crumb.kind === "file"
+ ? "font-t3-bold text-foreground"
+ : "font-t3-medium text-foreground-muted",
+ )}
+ numberOfLines={1}
+ >
+ {crumb.label}
+ </Text>
+ </View>
+ ))}
+ </View>
+ </ScrollView>
+ {fadeVisibility.left ? <BreadcrumbFade color={cardColor} side="left" /> : null}
+ {fadeVisibility.right ? <BreadcrumbFade color={cardColor} side="right" /> : null}
+ </View>
+ );
+}
+
+function FilePreviewHeader(props: {
+ readonly activeMode: FileViewMode;
+ readonly showModeSelector: boolean;
+ readonly externalPreviewUri?: string | null;
+ readonly projectName: string;
+ readonly relativePath: string;
+ readonly onSetMode: (mode: FileViewMode) => void;
+}) {
+ const iconColor = String(useThemeColor("--color-icon-muted"));
+
+ return (
+ <View className="border-b border-border bg-card px-3 py-2">
+ <View className="flex-row items-center gap-2">
+ <FileBreadcrumbs projectName={props.projectName} relativePath={props.relativePath} />
+ <CopyTextButton
+ accessibilityLabel="Copy file path"
+ text={props.relativePath}
+ tintColor={iconColor}
+ buttonSize={32}
+ iconSize={13}
+ />
+ </View>
+ {props.showModeSelector ? (
+ <View className="mt-2 flex-row items-center gap-2">
+ <ModeButton
+ active={props.activeMode === "preview"}
+ icon="eye"
+ label="Preview"
+ onPress={() => props.onSetMode("preview")}
+ />
+ <ModeButton
+ active={props.activeMode === "source"}
+ icon="doc.text"
+ label="Source"
+ onPress={() => props.onSetMode("source")}
+ />
+ {props.externalPreviewUri !== undefined ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel="Open preview in Safari"
+ disabled={props.externalPreviewUri === null}
+ hitSlop={8}
+ className={cn(
+ "ml-auto h-8 w-8 items-center justify-center rounded-full bg-subtle active:opacity-70",
+ props.externalPreviewUri === null && "opacity-40",
+ )}
+ onPress={() => {
+ if (typeof props.externalPreviewUri === "string") {
+ void Linking.openURL(props.externalPreviewUri);
+ }
+ }}
+ >
+ <SymbolView name="safari" size={15} tintColor={iconColor} type="monochrome" />
+ </Pressable>
+ ) : null}
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+function FileContent(props: {
+ readonly activeMode: FileViewMode;
+ readonly previewUri: string | null;
+ readonly fileContents: string | null;
+ readonly fileError: string | null;
+ readonly relativePath: string;
+ readonly initialLine: number | null;
+ readonly truncated: boolean;
+}) {
+ const isMarkdown = isMarkdownPreviewFile(props.relativePath);
+ const isBrowserFile = isBrowserPreviewFile(props.relativePath);
+ const isImageFile = isImagePreviewFile(props.relativePath);
+
+ if (props.activeMode === "preview" && isImageFile) {
+ if (isSvgImagePreviewFile(props.relativePath)) {
+ return <WorkspaceFileWebPreview uri={props.previewUri} />;
+ }
+ return (
+ <WorkspaceFileImagePreview
+ accessibilityLabel={basename(props.relativePath)}
+ uri={props.previewUri}
+ />
+ );
+ }
+
+ if (props.activeMode === "preview" && isBrowserFile) {
+ return <WorkspaceFileWebPreview uri={props.previewUri} />;
+ }
+
+ if (props.fileError && props.fileContents === null) {
+ return (
+ <View className="flex-1 items-center justify-center bg-card px-6">
+ <EmptyState title="File unavailable" detail={props.fileError} />
+ </View>
+ );
+ }
+
+ if (props.fileContents === null) {
+ return (
+ <View className="flex-1 items-center justify-center gap-3 bg-card px-6">
+ <ActivityIndicator />
+ <Text className="text-center text-[13px] text-foreground-muted">Loading file...</Text>
+ </View>
+ );
+ }
+
+ return (
+ <View className="flex-1 bg-card">
+ {props.truncated ? (
+ <View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
+ <Text className="text-[11px] font-t3-bold uppercase text-amber-700 dark:text-amber-300">
+ Partial file
+ </Text>
+ <Text className="text-[12px] leading-[17px] text-amber-800 dark:text-amber-200">
+ Preview limited to the first 1 MB of a truncated file.
+ </Text>
+ </View>
+ ) : null}
+ {props.activeMode === "preview" && isMarkdown ? (
+ <FileMarkdownPreview markdown={props.fileContents} />
+ ) : (
+ <SourceFileSurface
+ contents={props.fileContents}
+ path={props.relativePath}
+ initialLine={props.initialLine}
+ />
+ )}
+ </View>
+ );
+}
+
+function useThreadFilesWorkspace() {
+ const params = useLocalSearchParams<{
+ environmentId?: string | string[];
+ threadId?: string | string[];
+ }>();
+ const routeEnvironmentId = firstRouteParam(params.environmentId);
+ const routeThreadId = firstRouteParam(params.threadId);
+ const { selectedThread, selectedThreadProject } = useThreadSelection();
+ const { selectedThreadCwd } = useSelectedThreadWorktree();
+ const environmentId =
+ routeEnvironmentId !== null
+ ? EnvironmentId.make(routeEnvironmentId)
+ : (selectedThread?.environmentId ?? null);
+ const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
+ const project = selectedThreadProject as {
+ readonly title?: string;
+ readonly workspaceRoot?: string;
+ } | null;
+
+ return {
+ cwd: selectedThreadCwd ?? project?.workspaceRoot ?? null,
+ environmentId,
+ projectName: project?.title ?? "Files",
+ selectedThread,
+ threadId,
+ };
+}
+
+function FilesUnavailable() {
+ return (
+ <View className="flex-1 items-center justify-center bg-sheet px-6">
+ <Stack.Screen options={{ title: "Files" }} />
+ <EmptyState
+ title="Files unavailable"
+ detail="This thread does not have an active workspace path."
+ />
+ </View>
+ );
+}
+
+function FilesHeaderTitle(props: { readonly projectName: string }) {
+ const foregroundColor = String(useThemeColor("--color-foreground"));
+ const secondaryForegroundColor = String(useThemeColor("--color-foreground-secondary"));
+
+ return (
+ <View style={{ alignItems: "center", maxWidth: 220 }}>
+ <RNText
+ numberOfLines={1}
+ style={{
+ color: foregroundColor,
+ fontFamily: "DMSans_700Bold",
+ fontSize: 18,
+ fontWeight: "900",
+ letterSpacing: -0.4,
+ }}
+ >
+ Files
+ </RNText>
+ <RNText
+ numberOfLines={1}
+ style={{
+ color: secondaryForegroundColor,
+ fontFamily: "DMSans_500Medium",
+ fontSize: 12,
+ fontWeight: "500",
+ letterSpacing: 0.2,
+ }}
+ >
+ {props.projectName}
+ </RNText>
+ </View>
+ );
+}
+
+function FilesToolbarBottomFade() {
+ const sheetColor = String(useThemeColor("--color-sheet"));
+
+ if (process.env.EXPO_OS !== "ios") {
+ return null;
+ }
+
+ return (
+ <View
+ pointerEvents="none"
+ accessibilityElementsHidden
+ importantForAccessibility="no-hide-descendants"
+ style={{
+ bottom: 0,
+ height: 112,
+ left: 0,
+ position: "absolute",
+ right: 0,
+ zIndex: 1,
+ }}
+ >
+ <Svg width="100%" height="100%">
+ <Defs>
+ <LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
+ <Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
+ <Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
+ <Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
+ </LinearGradient>
+ </Defs>
+ <Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
+ </Svg>
+ </View>
+ );
+}
+
+export function ThreadFilesTreeScreen() {
+ const router = useRouter();
+ const [searchQuery, setSearchQuery] = useState("");
+ const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
+ const entriesQuery = useEnvironmentQuery(
+ environmentId !== null && cwd !== null
+ ? projectEnvironment.listEntries({
+ environmentId,
+ input: { cwd },
+ })
+ : null,
+ );
+ const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
+
+ const handleSelectFile = useCallback(
+ (path: string) => {
+ if (environmentId === null || threadId === null) {
+ return;
+ }
+ router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
+ },
+ [environmentId, router, threadId],
+ );
+
+ if (selectedThread === null || environmentId === null || threadId === null) {
+ return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
+ }
+
+ if (cwd === null) {
+ return <FilesUnavailable />;
+ }
+
+ return (
+ <View className="flex-1 bg-sheet">
+ <Stack.Screen
+ 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("");
+ },
+ },
+ }}
+ />
+ <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>
+ <FileTreeBrowser
+ entries={entriesData?.entries ?? []}
+ error={entriesQuery.error}
+ isPending={entriesQuery.isPending}
+ searchQuery={searchQuery}
+ selectedPath={null}
+ onRefresh={entriesQuery.refresh}
+ onSelectFile={handleSelectFile}
+ />
+ <FilesToolbarBottomFade />
+ </View>
+ );
+}
+
+export function ThreadFileScreen() {
+ const params = useLocalSearchParams<{
+ line?: string | string[];
+ path?: string | string[];
+ }>();
+ const relativePath = normalizeRoutePath(params.path);
+ const targetLine = normalizeRouteLine(firstRouteParam(params.line));
+ const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
+ const [modeOverride, setModeOverride] = useState<{
+ readonly path: string;
+ readonly mode: FileViewMode;
+ } | null>(null);
+ const [previewRevision, setPreviewRevision] = useState(0);
+ const isBrowserFile = relativePath !== null && isBrowserPreviewFile(relativePath);
+ const isImageFile = relativePath !== null && isImagePreviewFile(relativePath);
+ const canPreview =
+ relativePath !== null && (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile);
+ const activeMode =
+ relativePath !== null && modeOverride?.path === relativePath
+ ? modeOverride.mode
+ : defaultViewMode(relativePath);
+ const resolvedActiveMode = canPreview ? activeMode : "source";
+ const assetPreviewPath = isBrowserFile || isImageFile ? relativePath : null;
+ const assetPreviewUri = useWorkspaceFileAssetUrl({
+ cwd,
+ environmentId,
+ relativePath: assetPreviewPath,
+ threadId,
+ });
+ const previewUri =
+ assetPreviewUri === null || previewRevision === 0
+ ? assetPreviewUri
+ : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
+ const needsFileContents =
+ relativePath !== null &&
+ (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
+ const fileQuery = useEnvironmentQuery(
+ environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
+ ? projectEnvironment.readFile({
+ environmentId,
+ input: { cwd, relativePath },
+ })
+ : null,
+ );
+ const fileData = fileQuery.data as ProjectReadFileResult | null;
+
+ if (selectedThread === null || environmentId === null || threadId === null) {
+ return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
+ }
+
+ if (cwd === null) {
+ return <FilesUnavailable />;
+ }
+
+ if (relativePath === null) {
+ return (
+ <View className="flex-1 items-center justify-center bg-sheet px-6">
+ <Stack.Screen options={{ title: "Files" }} />
+ <EmptyState title="File unavailable" detail="This file path is invalid." />
+ </View>
+ );
+ }
+
+ return (
+ <ReviewHighlighterProvider>
+ <View className="flex-1 bg-sheet">
+ <Stack.Screen options={{ title: basename(relativePath) }} />
+ <Stack.Toolbar placement="right">
+ <Stack.Toolbar.Button
+ icon="arrow.clockwise"
+ onPress={() => {
+ if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
+ setPreviewRevision((current) => current + 1);
+ return;
+ }
+ fileQuery.refresh();
+ }}
+ />
+ </Stack.Toolbar>
+ <FilePreviewHeader
+ activeMode={resolvedActiveMode}
+ showModeSelector={canPreview && !isImageFile}
+ externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
+ projectName={projectName}
+ relativePath={relativePath}
+ onSetMode={(mode) => {
+ setModeOverride({ path: relativePath, mode });
+ }}
+ />
+ <FileContent
+ activeMode={resolvedActiveMode}
+ previewUri={previewUri}
+ fileContents={fileData?.contents ?? null}
+ fileError={fileQuery.error}
+ initialLine={targetLine}
+ relativePath={relativePath}
+ truncated={fileData?.truncated ?? false}
+ />
+ </View>
+ </ReviewHighlighterProvider>
+ );
+}
diff --git a/apps/mobile/src/features/files/WorkspaceFileImagePreview.tsx b/apps/mobile/src/features/files/WorkspaceFileImagePreview.tsx
new file mode 100644
index 000000000..15d5b7671
--- /dev/null
+++ b/apps/mobile/src/features/files/WorkspaceFileImagePreview.tsx
@@ -0,0 +1,118 @@
+import { useAtomValue } from "@effect/atom-react";
+import { useMemo, useState } from "react";
+import { ActivityIndicator, Image, Pressable, View } from "react-native";
+import ImageViewing from "react-native-image-viewing";
+import { AsyncResult } from "effect/unstable/reactivity";
+
+import { AppText as Text } from "../../components/AppText";
+import { EmptyState } from "../../components/EmptyState";
+import { workspaceFileImageAtom } from "./workspace-file-image-cache";
+
+function ResolvedWorkspaceFileImagePreview(props: {
+ readonly accessibilityLabel: string;
+ readonly uri: string;
+}) {
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [fullScreenVisible, setFullScreenVisible] = useState(false);
+ const imageSource = useMemo(
+ () => ({ uri: props.uri, cache: "force-cache" as const }),
+ [props.uri],
+ );
+ const fullScreenImages = useMemo(() => [imageSource], [imageSource]);
+
+ return (
+ <View className="relative flex-1 bg-subtle">
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Open full-screen preview of ${props.accessibilityLabel}`}
+ disabled={loadError !== null}
+ className="flex-1 p-4 active:bg-subtle-strong"
+ onPress={() => setFullScreenVisible(true)}
+ >
+ <Image
+ accessible={false}
+ source={imageSource}
+ className="h-full w-full"
+ resizeMode="contain"
+ onLoadStart={() => setLoadError(null)}
+ onError={(event) => {
+ setLoadError(event.nativeEvent.error || "The image could not be rendered.");
+ }}
+ />
+ </Pressable>
+
+ {loadError !== null ? (
+ <View className="absolute inset-0 items-center justify-center bg-card px-6">
+ <EmptyState title="Image unavailable" detail={loadError} />
+ </View>
+ ) : null}
+
+ <ImageViewing
+ images={fullScreenImages}
+ imageIndex={0}
+ visible={fullScreenVisible}
+ onRequestClose={() => setFullScreenVisible(false)}
+ swipeToCloseEnabled
+ doubleTapToZoomEnabled
+ />
+ </View>
+ );
+}
+
+function CachedWorkspaceFileImagePreview(props: {
+ readonly accessibilityLabel: string;
+ readonly uri: string;
+}) {
+ const imageAtom = useMemo(() => workspaceFileImageAtom(props.uri), [props.uri]);
+ const imageResult = useAtomValue(imageAtom);
+
+ if (AsyncResult.isFailure(imageResult)) {
+ return (
+ <View className="flex-1 items-center justify-center bg-card px-6">
+ <EmptyState
+ title="Image unavailable"
+ detail="The image could not be loaded into the local cache."
+ />
+ </View>
+ );
+ }
+
+ if (!AsyncResult.isSuccess(imageResult)) {
+ return (
+ <View className="flex-1 items-center justify-center gap-3 bg-card px-6">
+ <ActivityIndicator />
+ <Text className="text-center text-[13px] text-foreground-muted">Loading image...</Text>
+ </View>
+ );
+ }
+
+ return (
+ <ResolvedWorkspaceFileImagePreview
+ accessibilityLabel={props.accessibilityLabel}
+ uri={imageResult.value}
+ />
+ );
+}
+
+export function WorkspaceFileImagePreview(props: {
+ readonly accessibilityLabel: string;
+ readonly uri: string | null;
+}) {
+ if (props.uri === null) {
+ return (
+ <View className="flex-1 items-center justify-center gap-3 bg-card px-6">
+ <ActivityIndicator />
+ <Text className="text-center text-[13px] text-foreground-muted">
+ Preparing image preview...
+ </Text>
+ </View>
+ );
+ }
+
+ return (
+ <CachedWorkspaceFileImagePreview
+ accessibilityLabel={props.accessibilityLabel}
+ uri={props.uri}
+ />
+ );
+}
diff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx
new file mode 100644
index 000000000..1628c4601
--- /dev/null
+++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx
@@ -0,0 +1,62 @@
+import { useState } from "react";
+import { ActivityIndicator, View } from "react-native";
+import { WebView } from "react-native-webview";
+
+import { AppText as Text } from "../../components/AppText";
+import { LoadingStrip } from "../../components/LoadingStrip";
+
+export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) {
+ const [loadProgress, setLoadProgress] = useState(0);
+ const [loadError, setLoadError] = useState<string | null>(null);
+
+ if (props.uri === null) {
+ return (
+ <View className="flex-1 items-center justify-center gap-3 bg-card px-6">
+ <ActivityIndicator />
+ <Text className="text-center text-[13px] text-foreground-muted">Preparing preview...</Text>
+ </View>
+ );
+ }
+
+ return (
+ <View className="relative flex-1 bg-card">
+ {loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
+ {loadError ? (
+ <View className="border-b border-border bg-card px-4 py-2">
+ <Text className="text-[12px] font-t3-bold text-foreground">Preview failed</Text>
+ <Text className="mt-0.5 text-[12px] leading-[17px] text-foreground-muted">
+ {loadError}
+ </Text>
+ </View>
+ ) : null}
+ <WebView
+ source={{ uri: props.uri }}
+ originWhitelist={["*"]}
+ allowsBackForwardNavigationGestures
+ allowsFullscreenVideo
+ setSupportMultipleWindows={false}
+ startInLoadingState
+ onLoadProgress={(event) => {
+ setLoadProgress(event.nativeEvent.progress);
+ }}
+ onLoadStart={() => {
+ setLoadProgress(0.05);
+ setLoadError(null);
+ }}
+ onLoadEnd={() => {
+ setLoadProgress(0);
+ }}
+ onError={(event) => {
+ setLoadProgress(0);
+ setLoadError(event.nativeEvent.description || "The file could not be rendered.");
+ }}
+ renderLoading={() => (
+ <View className="absolute inset-0 items-center justify-center bg-card">
+ <ActivityIndicator />
+ </View>
+ )}
+ style={{ flex: 1, backgroundColor: "transparent" }}
+ />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/files/filePath.test.ts b/apps/mobile/src/features/files/filePath.test.ts
new file mode 100644
index 000000000..af0ace61f
--- /dev/null
+++ b/apps/mobile/src/features/files/filePath.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ isBrowserPreviewFile,
+ isImagePreviewFile,
+ isSvgImagePreviewFile,
+ resolveWorkspaceRelativeFilePath,
+} from "./filePath";
+
+describe("resolveWorkspaceRelativeFilePath", () => {
+ it("keeps normalized workspace-relative paths", () => {
+ expect(resolveWorkspaceRelativeFilePath("/repo", "./src/../src/main.ts")).toBe("src/main.ts");
+ });
+
+ it("converts absolute paths inside the workspace", () => {
+ expect(
+ resolveWorkspaceRelativeFilePath("/Users/julius/repo", "/Users/julius/repo/src/main.ts"),
+ ).toBe("src/main.ts");
+ expect(resolveWorkspaceRelativeFilePath("C:\\repo", "c:\\repo\\src\\main.ts")).toBe(
+ "src/main.ts",
+ );
+ });
+
+ it("rejects paths outside the workspace", () => {
+ expect(resolveWorkspaceRelativeFilePath("/repo", "/other/main.ts")).toBeNull();
+ expect(resolveWorkspaceRelativeFilePath("/repo", "../other/main.ts")).toBeNull();
+ expect(resolveWorkspaceRelativeFilePath(null, "/repo/main.ts")).toBeNull();
+ });
+});
+
+describe("file preview types", () => {
+ it("recognizes browser and image previews", () => {
+ expect(isBrowserPreviewFile("reports/summary.html")).toBe(true);
+ expect(isImagePreviewFile("assets/icon.png")).toBe(true);
+ expect(isImagePreviewFile("assets/diagram.SVG?raw=1")).toBe(true);
+ expect(isImagePreviewFile("src/image.ts")).toBe(false);
+ });
+
+ it("identifies SVG images that need web rendering", () => {
+ expect(isSvgImagePreviewFile("assets/diagram.svg#icon")).toBe(true);
+ expect(isSvgImagePreviewFile("assets/photo.png")).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/features/files/filePath.ts b/apps/mobile/src/features/files/filePath.ts
new file mode 100644
index 000000000..385d5c139
--- /dev/null
+++ b/apps/mobile/src/features/files/filePath.ts
@@ -0,0 +1,116 @@
+import {
+ isWorkspaceBrowserPreviewPath,
+ isWorkspaceImagePreviewPath,
+} from "@t3tools/shared/filePreview";
+
+export interface FileBreadcrumb {
+ readonly label: string;
+ readonly path: string;
+ readonly kind: "project" | "directory" | "file";
+}
+
+function isWindowsAbsolutePath(value: string): boolean {
+ return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
+}
+
+function isAbsolutePath(value: string): boolean {
+ return value.startsWith("/") || isWindowsAbsolutePath(value);
+}
+
+function isWindowsPathStyle(value: string): boolean {
+ return isWindowsAbsolutePath(value) || /^[A-Za-z]:\\/.test(value);
+}
+
+function joinPath(base: string, next: string, separator: "/" | "\\"): string {
+ const cleanBase = base.replace(/[\\/]+$/, "");
+ if (separator === "\\") {
+ return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
+ }
+ return `${cleanBase}/${next.replace(/^\/+/, "")}`;
+}
+
+export function basename(path: string): string {
+ const parts = path.split(/[\\/]/).filter(Boolean);
+ return parts.at(-1) ?? path;
+}
+
+export function resolveWorkspaceFilePath(cwd: string, relativePath: string): string {
+ if (isAbsolutePath(relativePath)) {
+ return relativePath;
+ }
+
+ const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
+ return joinPath(cwd, relativePath, separator);
+}
+
+function normalizeRelativePath(value: string): string | null {
+ const segments: string[] = [];
+ for (const segment of value.replaceAll("\\", "/").split("/")) {
+ if (segment.length === 0 || segment === ".") {
+ continue;
+ }
+ if (segment === "..") {
+ if (segments.length === 0) {
+ return null;
+ }
+ segments.pop();
+ continue;
+ }
+ segments.push(segment);
+ }
+ return segments.length > 0 ? segments.join("/") : null;
+}
+
+export function resolveWorkspaceRelativeFilePath(
+ workspaceRoot: string | null | undefined,
+ targetPath: string,
+): string | null {
+ if (!isAbsolutePath(targetPath)) {
+ if (targetPath.startsWith("~/") || targetPath.startsWith("~\\")) {
+ return null;
+ }
+ return normalizeRelativePath(targetPath);
+ }
+ if (!workspaceRoot) {
+ return null;
+ }
+
+ const normalizedTarget = targetPath.replaceAll("\\", "/");
+ const normalizedRoot = workspaceRoot.replaceAll("\\", "/").replace(/\/+$/, "");
+ const caseInsensitive = isWindowsAbsolutePath(targetPath) || isWindowsAbsolutePath(workspaceRoot);
+ const comparableTarget = caseInsensitive ? normalizedTarget.toLowerCase() : normalizedTarget;
+ const comparableRoot = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
+ if (!comparableTarget.startsWith(`${comparableRoot}/`)) {
+ return null;
+ }
+
+ return normalizeRelativePath(normalizedTarget.slice(normalizedRoot.length + 1));
+}
+
+export function isBrowserPreviewFile(path: string): boolean {
+ return isWorkspaceBrowserPreviewPath(path);
+}
+
+export function isImagePreviewFile(path: string): boolean {
+ return isWorkspaceImagePreviewPath(path);
+}
+
+export function isSvgImagePreviewFile(path: string): boolean {
+ return /\.svg$/i.test(path.split(/[?#]/, 1)[0] ?? "");
+}
+
+export function isMarkdownPreviewFile(path: string): boolean {
+ return /\.(?:md|mdx)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
+}
+
+export function fileBreadcrumbs(projectName: string, relativePath: string): FileBreadcrumb[] {
+ const parts = relativePath.split("/").filter(Boolean);
+ return [
+ { label: projectName, path: "", kind: "project" },
+ ...parts.map((part, index) => ({
+ label: part,
+ path: parts.slice(0, index + 1).join("/"),
+ kind: index === parts.length - 1 ? ("file" as const) : ("directory" as const),
+ })),
+ ];
+}
diff --git a/apps/mobile/src/features/files/fileTree.test.ts b/apps/mobile/src/features/files/fileTree.test.ts
new file mode 100644
index 000000000..85383514c
--- /dev/null
+++ b/apps/mobile/src/features/files/fileTree.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { ProjectEntry } from "@t3tools/contracts";
+
+import {
+ buildFileTree,
+ countFileNodes,
+ defaultExpandedTreePaths,
+ firstFilePath,
+ flattenFileTree,
+} from "./fileTree";
+
+const entries = [
+ { kind: "file", path: "README.md" },
+ { kind: "directory", path: "src" },
+ { kind: "file", path: "src/index.ts" },
+ { kind: "file", path: "src/components/App.tsx" },
+ { kind: "file", path: "package.json" },
+] satisfies ReadonlyArray<ProjectEntry>;
+
+describe("mobile file tree helpers", () => {
+ it("builds a deterministic hierarchy with directories before files", () => {
+ const tree = buildFileTree(entries);
+
+ expect(tree.map((node) => `${node.kind}:${node.path}`)).toEqual([
+ "directory:src",
+ "file:package.json",
+ "file:README.md",
+ ]);
+ expect(tree[0]?.children.map((node) => `${node.kind}:${node.path}`)).toEqual([
+ "directory:src/components",
+ "file:src/index.ts",
+ ]);
+ expect(countFileNodes(tree)).toBe(4);
+ expect(firstFilePath(tree)).toBe("src/components/App.tsx");
+ });
+
+ it("flattens expanded directories and hides collapsed descendants", () => {
+ const tree = buildFileTree(entries);
+
+ expect(
+ flattenFileTree({
+ nodes: tree,
+ expanded: new Set(["src"]),
+ }).map((item) => `${item.depth}:${item.node.path}`),
+ ).toEqual(["0:src", "1:src/components", "1:src/index.ts", "0:package.json", "0:README.md"]);
+
+ expect(
+ flattenFileTree({
+ nodes: tree,
+ expanded: new Set(),
+ }).map((item) => item.node.path),
+ ).toEqual(["src", "package.json", "README.md"]);
+ });
+
+ it("includes matching descendants and their ancestors during search", () => {
+ const tree = buildFileTree(entries);
+
+ expect(
+ flattenFileTree({
+ nodes: tree,
+ expanded: new Set(),
+ searchQuery: "app",
+ }).map((item) => item.node.path),
+ ).toEqual(["src", "src/components", "src/components/App.tsx"]);
+ });
+
+ it("supports fuzzy, whitespace-separated path queries", () => {
+ const tree = buildFileTree([
+ {
+ kind: "file",
+ path: ".plans/19-version-control-phase-1-vcs-driver-foundation.md",
+ },
+ {
+ kind: "file",
+ path: ".repos/alchemy-effect/examples/aws-lambda/src/JobNotifications.ts",
+ },
+ { kind: "directory", path: "apps/web/src/components/chat" },
+ { kind: "file", path: "apps/web/src/components/chat/ChatHeader.test.ts" },
+ { kind: "file", path: "apps/web/src/components/chat/ChatHeader.tsx" },
+ { kind: "file", path: "apps/web/src/components/chat/Composer.tsx" },
+ ]);
+
+ const expectedPaths = [
+ "apps",
+ "apps/web",
+ "apps/web/src",
+ "apps/web/src/components",
+ "apps/web/src/components/chat",
+ "apps/web/src/components/chat/ChatHeader.test.ts",
+ "apps/web/src/components/chat/ChatHeader.tsx",
+ ];
+
+ for (const searchQuery of ["chat hea", "cht hdr"]) {
+ expect(
+ flattenFileTree({
+ nodes: tree,
+ expanded: new Set(),
+ searchQuery,
+ }).map((item) => item.node.path),
+ ).toEqual(expectedPaths);
+ }
+ });
+
+ it("expands top-level directories by default", () => {
+ const tree = buildFileTree(entries);
+
+ expect([...defaultExpandedTreePaths(tree)]).toEqual(["src"]);
+ });
+});
diff --git a/apps/mobile/src/features/files/fileTree.ts b/apps/mobile/src/features/files/fileTree.ts
new file mode 100644
index 000000000..28b5822aa
--- /dev/null
+++ b/apps/mobile/src/features/files/fileTree.ts
@@ -0,0 +1,220 @@
+import type { ProjectEntry } from "@t3tools/contracts";
+import { normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking";
+
+export interface FileTreeNode {
+ readonly path: string;
+ readonly name: string;
+ readonly kind: ProjectEntry["kind"];
+ readonly children: ReadonlyArray<FileTreeNode>;
+ readonly searchSegments: ReadonlyArray<string>;
+ readonly searchWords: ReadonlyArray<string>;
+}
+
+export interface VisibleFileTreeNode {
+ readonly node: FileTreeNode;
+ readonly depth: number;
+}
+
+interface MutableFileTreeNode {
+ path: string;
+ name: string;
+ kind: ProjectEntry["kind"];
+ children: Map<string, MutableFileTreeNode>;
+}
+
+function createMutableNode(
+ path: string,
+ name: string,
+ kind: ProjectEntry["kind"],
+): MutableFileTreeNode {
+ return {
+ path,
+ name,
+ kind,
+ children: new Map(),
+ };
+}
+
+function splitSearchWords(value: string): ReadonlyArray<string> {
+ return value
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
+ .split(/[^A-Za-z0-9]+/)
+ .filter(Boolean)
+ .map((word) => word.toLowerCase());
+}
+
+function buildNodeSearchTerms(path: string): {
+ readonly segments: ReadonlyArray<string>;
+ readonly words: ReadonlyArray<string>;
+} {
+ const segments: string[] = [];
+ const words: string[] = [];
+
+ for (const segment of path.split("/")) {
+ if (!segment) {
+ continue;
+ }
+ segments.push(segment.toLowerCase());
+ words.push(...splitSearchWords(segment));
+ }
+
+ return { segments, words };
+}
+
+function freezeNode(node: MutableFileTreeNode): FileTreeNode {
+ const searchTerms = buildNodeSearchTerms(node.path);
+ return {
+ path: node.path,
+ name: node.name,
+ kind: node.kind,
+ children: [...node.children.values()].sort(compareNodes).map(freezeNode),
+ searchSegments: searchTerms.segments,
+ searchWords: searchTerms.words,
+ };
+}
+
+function compareNodes(
+ left: Pick<FileTreeNode, "kind" | "name">,
+ right: Pick<FileTreeNode, "kind" | "name">,
+): number {
+ if (left.kind !== right.kind) {
+ return left.kind === "directory" ? -1 : 1;
+ }
+ return left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" });
+}
+
+export function buildFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
+ const root = createMutableNode("", "", "directory");
+
+ for (const entry of entries) {
+ const parts = entry.path.split("/").filter(Boolean);
+ if (parts.length === 0) {
+ continue;
+ }
+
+ let current = root;
+ for (let index = 0; index < parts.length; index += 1) {
+ const part = parts[index];
+ if (!part) {
+ continue;
+ }
+
+ const path = parts.slice(0, index + 1).join("/");
+ const isLeaf = index === parts.length - 1;
+ const kind = isLeaf ? entry.kind : "directory";
+ let child = current.children.get(part);
+ if (!child) {
+ child = createMutableNode(path, part, kind);
+ current.children.set(part, child);
+ } else if (isLeaf) {
+ child.kind = entry.kind;
+ }
+ current = child;
+ }
+ }
+
+ return [...root.children.values()].sort(compareNodes).map(freezeNode);
+}
+
+export function countFileNodes(nodes: ReadonlyArray<FileTreeNode>): number {
+ let count = 0;
+ for (const node of nodes) {
+ if (node.kind === "file") {
+ count += 1;
+ } else {
+ count += countFileNodes(node.children);
+ }
+ }
+ return count;
+}
+
+export function defaultExpandedTreePaths(nodes: ReadonlyArray<FileTreeNode>): ReadonlySet<string> {
+ const expanded = new Set<string>();
+ for (const node of nodes) {
+ if (node.kind === "directory") {
+ expanded.add(node.path);
+ }
+ }
+ return expanded;
+}
+
+function valueMatchesSearchToken(value: string, token: string, fuzzy: boolean): boolean {
+ return (
+ scoreQueryMatch({
+ value,
+ query: token,
+ exactBase: 0,
+ prefixBase: 2,
+ boundaryBase: 4,
+ includesBase: 6,
+ ...(fuzzy ? { fuzzyBase: 100 } : {}),
+ boundaryMarkers: ["/", "-", "_", "."],
+ }) !== null
+ );
+}
+
+function nodeMatchesSearch(node: FileTreeNode, tokens: ReadonlyArray<string>): boolean {
+ return tokens.every(
+ (token) =>
+ node.searchSegments.some((segment) => valueMatchesSearchToken(segment, token, false)) ||
+ node.searchWords.some((word) => valueMatchesSearchToken(word, token, true)),
+ );
+}
+
+function flattenNode(
+ output: VisibleFileTreeNode[],
+ node: FileTreeNode,
+ depth: number,
+ expanded: ReadonlySet<string>,
+ searchTokens: ReadonlyArray<string>,
+): boolean {
+ const isSearching = searchTokens.length > 0;
+ const matches = isSearching && nodeMatchesSearch(node, searchTokens);
+ let descendantMatches = false;
+ const childOutput: VisibleFileTreeNode[] = [];
+
+ if (node.kind === "directory" && (expanded.has(node.path) || isSearching)) {
+ for (const child of node.children) {
+ if (flattenNode(childOutput, child, depth + 1, expanded, searchTokens)) {
+ descendantMatches = true;
+ }
+ }
+ }
+
+ const visible = !isSearching || matches || descendantMatches;
+ if (!visible) {
+ return false;
+ }
+
+ output.push({ node, depth });
+ output.push(...childOutput);
+ return matches || descendantMatches;
+}
+
+export function flattenFileTree(input: {
+ readonly nodes: ReadonlyArray<FileTreeNode>;
+ readonly expanded: ReadonlySet<string>;
+ readonly searchQuery?: string;
+}): ReadonlyArray<VisibleFileTreeNode> {
+ const output: VisibleFileTreeNode[] = [];
+ const normalizedSearch = normalizeSearchQuery(input.searchQuery ?? "");
+ const searchTokens = normalizedSearch.split(/[\s/\\._-]+/).filter(Boolean);
+ for (const node of input.nodes) {
+ flattenNode(output, node, 0, input.expanded, searchTokens);
+ }
+ return output;
+}
+
+export function firstFilePath(nodes: ReadonlyArray<FileTreeNode>): string | null {
+ for (const node of nodes) {
+ if (node.kind === "file") {
+ return node.path;
+ }
+ const child = firstFilePath(node.children);
+ if (child !== null) {
+ return child;
+ }
+ }
+ return null;
+}
diff --git a/apps/mobile/src/features/files/nativeSourceFileAdapter.test.ts b/apps/mobile/src/features/files/nativeSourceFileAdapter.test.ts
new file mode 100644
index 000000000..937d3a1d3
--- /dev/null
+++ b/apps/mobile/src/features/files/nativeSourceFileAdapter.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ buildNativeSourceRows,
+ buildNativeSourceTokens,
+ nativeSourceRowId,
+} from "./nativeSourceFileAdapter";
+
+describe("nativeSourceFileAdapter", () => {
+ it("maps plain source lines onto context rows with stable line numbers", () => {
+ expect(buildNativeSourceRows(["const value = 1;", "\treturn value;"])).toEqual([
+ {
+ kind: "line",
+ id: nativeSourceRowId(0),
+ fileId: "source-file",
+ content: "const value = 1;",
+ change: "context",
+ newLineNumber: 1,
+ },
+ {
+ kind: "line",
+ id: nativeSourceRowId(1),
+ fileId: "source-file",
+ content: " return value;",
+ change: "context",
+ newLineNumber: 2,
+ },
+ ]);
+ });
+
+ it("maps cached source tokens to the same row identifiers", () => {
+ expect(
+ buildNativeSourceTokens([
+ [{ content: "const", color: "#ff0000", fontStyle: 2 }],
+ [{ content: "\tvalue", color: null, fontStyle: null }],
+ ]),
+ ).toEqual({
+ [nativeSourceRowId(0)]: [{ content: "const", color: "#ff0000", fontStyle: 2 }],
+ [nativeSourceRowId(1)]: [{ content: " value", color: null, fontStyle: null }],
+ });
+ });
+
+ it("clears native tokens while highlighting is unavailable", () => {
+ expect(buildNativeSourceTokens(null)).toEqual({});
+ });
+});
diff --git a/apps/mobile/src/features/files/nativeSourceFileAdapter.ts b/apps/mobile/src/features/files/nativeSourceFileAdapter.ts
new file mode 100644
index 000000000..19abc8021
--- /dev/null
+++ b/apps/mobile/src/features/files/nativeSourceFileAdapter.ts
@@ -0,0 +1,65 @@
+import type {
+ NativeReviewDiffRow,
+ NativeReviewDiffStyle,
+ NativeReviewDiffToken,
+} from "../diffs/nativeReviewDiffSurface";
+import type { SourceHighlightTokens } from "./sourceHighlightingState";
+
+export const NATIVE_SOURCE_ROW_HEIGHT = 24;
+export const NATIVE_SOURCE_CONTENT_WIDTH = 32_000;
+
+export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = {
+ rowHeight: NATIVE_SOURCE_ROW_HEIGHT,
+ contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
+ changeBarWidth: 0,
+ gutterWidth: 58,
+ codePadding: 8,
+ codeFontSize: 13,
+ codeFontWeight: "medium",
+ lineNumberFontSize: 11,
+ lineNumberFontWeight: "medium",
+ emptyStateFontSize: 12,
+ emptyStateFontWeight: "medium",
+};
+
+const SOURCE_FILE_ID = "source-file";
+
+function expandTabs(value: string): string {
+ return value.replace(/\t/g, " ");
+}
+
+export function nativeSourceRowId(index: number): string {
+ return `source-line:${index}`;
+}
+
+export function buildNativeSourceRows(
+ lines: ReadonlyArray<string>,
+): ReadonlyArray<NativeReviewDiffRow> {
+ return lines.map((line, index) => ({
+ kind: "line",
+ id: nativeSourceRowId(index),
+ fileId: SOURCE_FILE_ID,
+ content: expandTabs(line),
+ change: "context",
+ newLineNumber: index + 1,
+ }));
+}
+
+export function buildNativeSourceTokens(
+ tokenLines: SourceHighlightTokens | null,
+): Readonly<Record<string, ReadonlyArray<NativeReviewDiffToken>>> {
+ if (tokenLines === null) {
+ return {};
+ }
+
+ return Object.fromEntries(
+ tokenLines.map((tokens, index) => [
+ nativeSourceRowId(index),
+ tokens.map((token) => ({
+ content: expandTabs(token.content),
+ color: token.color,
+ fontStyle: token.fontStyle,
+ })),
+ ]),
+ );
+}
diff --git a/apps/mobile/src/features/files/sourceHighlightingState.test.ts b/apps/mobile/src/features/files/sourceHighlightingState.test.ts
new file mode 100644
index 000000000..6c4c00e16
--- /dev/null
+++ b/apps/mobile/src/features/files/sourceHighlightingState.test.ts
@@ -0,0 +1,123 @@
+import { AtomRegistry } from "effect/unstable/reactivity";
+import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+
+import {
+ createSourceHighlightAtomFamily,
+ type SourceHighlightTokens,
+} from "./sourceHighlightingState";
+
+const highlightedTokens: SourceHighlightTokens = [
+ [{ content: "const", color: "#0000ff", fontStyle: null }],
+];
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("sourceHighlightingState", () => {
+ it("reuses completed highlighting across equivalent route remounts", async () => {
+ const highlight = vi.fn(async () => highlightedTokens);
+ const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight, idleTtlMs: 1_000 });
+ const registry = AtomRegistry.make({ timeoutResolution: 1 });
+ const input = {
+ path: "src/example.ts",
+ contents: "const value = 1;",
+ theme: "light" as const,
+ };
+ const firstAtom = sourceHighlightAtom(input);
+ const firstUnmount = registry.mount(firstAtom);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.isSuccess(registry.get(firstAtom))).toBe(true);
+ });
+ firstUnmount();
+
+ const remountedAtom = sourceHighlightAtom({ ...input });
+ const secondUnmount = registry.mount(remountedAtom);
+
+ expect(remountedAtom).toBe(firstAtom);
+ expect(AsyncResult.isSuccess(registry.get(remountedAtom))).toBe(true);
+ expect(highlight).toHaveBeenCalledTimes(1);
+
+ secondUnmount();
+ registry.dispose();
+ });
+
+ it("does not reuse highlighting when the source contents change", async () => {
+ const highlight = vi.fn(async () => highlightedTokens);
+ const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
+ const registry = AtomRegistry.make();
+ const firstAtom = sourceHighlightAtom({
+ path: "src/example.ts",
+ contents: "const value = 1;",
+ theme: "light",
+ });
+ const secondAtom = sourceHighlightAtom({
+ path: "src/example.ts",
+ contents: "const value = 2;",
+ theme: "light",
+ });
+ const firstUnmount = registry.mount(firstAtom);
+ const secondUnmount = registry.mount(secondAtom);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.isSuccess(registry.get(firstAtom))).toBe(true);
+ expect(AsyncResult.isSuccess(registry.get(secondAtom))).toBe(true);
+ });
+ expect(secondAtom).not.toBe(firstAtom);
+ expect(highlight).toHaveBeenCalledTimes(2);
+
+ firstUnmount();
+ secondUnmount();
+ registry.dispose();
+ });
+
+ it("recomputes highlighting after the idle cache entry expires", async () => {
+ const highlight = vi.fn(async () => highlightedTokens);
+ const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight, idleTtlMs: 5 });
+ const registry = AtomRegistry.make({ timeoutResolution: 1 });
+ const atom = sourceHighlightAtom({
+ path: "src/example.ts",
+ contents: "const value = 1;",
+ theme: "light",
+ });
+ const firstUnmount = registry.mount(atom);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
+ });
+ firstUnmount();
+ await new Promise((resolve) => setTimeout(resolve, 25));
+
+ const secondUnmount = registry.mount(atom);
+ await vi.waitFor(() => {
+ expect(highlight).toHaveBeenCalledTimes(2);
+ expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
+ });
+
+ secondUnmount();
+ registry.dispose();
+ });
+
+ it("exposes highlighter errors as a failed async result", async () => {
+ const highlight = vi.fn(async () => {
+ throw new Error("highlight failed");
+ });
+ const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
+ const registry = AtomRegistry.make();
+ const atom = sourceHighlightAtom({
+ path: "src/example.ts",
+ contents: "const value = 1;",
+ theme: "light",
+ });
+ const unmount = registry.mount(atom);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
+ });
+
+ unmount();
+ registry.dispose();
+ });
+});
diff --git a/apps/mobile/src/features/files/sourceHighlightingState.ts b/apps/mobile/src/features/files/sourceHighlightingState.ts
new file mode 100644
index 000000000..43363115b
--- /dev/null
+++ b/apps/mobile/src/features/files/sourceHighlightingState.ts
@@ -0,0 +1,50 @@
+import * as Data from "effect/Data";
+import * as Effect from "effect/Effect";
+import { Atom } from "effect/unstable/reactivity";
+
+import {
+ highlightSourceFile,
+ type ReviewDiffTheme,
+ type ReviewHighlightedToken,
+} from "../review/shikiReviewHighlighter";
+
+const SOURCE_HIGHLIGHT_IDLE_TTL_MS = 5 * 60_000;
+
+export interface SourceHighlightInput {
+ readonly path: string;
+ readonly contents: string;
+ readonly theme: ReviewDiffTheme;
+}
+
+export type SourceHighlightTokens = ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
+
+type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighlightTokens>;
+
+class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
+
+class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
+ readonly cause: unknown;
+}> {}
+
+export function createSourceHighlightAtomFamily(options?: {
+ readonly highlight?: SourceHighlighter;
+ readonly idleTtlMs?: number;
+}) {
+ const highlight = options?.highlight ?? highlightSourceFile;
+ const idleTtlMs = options?.idleTtlMs ?? SOURCE_HIGHLIGHT_IDLE_TTL_MS;
+ const family = Atom.family((request: SourceHighlightCacheKey) =>
+ Atom.make(
+ Effect.tryPromise({
+ try: () => highlight(request),
+ catch: (cause) => new SourceHighlightError({ cause }),
+ }),
+ ).pipe(
+ Atom.setIdleTTL(idleTtlMs),
+ Atom.withLabel(`mobile:source-highlight:${request.theme}:${request.path}`),
+ ),
+ );
+
+ return (input: SourceHighlightInput) => family(new SourceHighlightCacheKey(input));
+}
+
+export const sourceHighlightAtom = createSourceHighlightAtomFamily();
diff --git a/apps/mobile/src/features/files/workspace-file-image-cache.test.ts b/apps/mobile/src/features/files/workspace-file-image-cache.test.ts
new file mode 100644
index 000000000..4acb67361
--- /dev/null
+++ b/apps/mobile/src/features/files/workspace-file-image-cache.test.ts
@@ -0,0 +1,64 @@
+import { AtomRegistry } from "effect/unstable/reactivity";
+import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
+
+describe("workspaceFileImageAtom", () => {
+ it("reuses a prefetched image across route remounts", async () => {
+ const prefetch = vi.fn(async () => true);
+ const imageAtom = createWorkspaceFileImageAtomFamily({ idleTtlMs: 1_000, prefetch });
+ const registry = AtomRegistry.make({ timeoutResolution: 1 });
+ const first = imageAtom("https://example.test/image.png");
+ const firstUnmount = registry.mount(first);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.isSuccess(registry.get(first))).toBe(true);
+ });
+ firstUnmount();
+
+ const remounted = imageAtom("https://example.test/image.png");
+ const secondUnmount = registry.mount(remounted);
+
+ expect(remounted).toBe(first);
+ expect(AsyncResult.isSuccess(registry.get(remounted))).toBe(true);
+ expect(prefetch).toHaveBeenCalledTimes(1);
+
+ secondUnmount();
+ registry.dispose();
+ });
+
+ it("prefetches different asset URLs independently", async () => {
+ const prefetch = vi.fn(async () => true);
+ const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch });
+ const registry = AtomRegistry.make();
+ const first = imageAtom("https://example.test/first.png");
+ const second = imageAtom("https://example.test/second.png");
+ const firstUnmount = registry.mount(first);
+ const secondUnmount = registry.mount(second);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.isSuccess(registry.get(first))).toBe(true);
+ expect(AsyncResult.isSuccess(registry.get(second))).toBe(true);
+ });
+ expect(prefetch).toHaveBeenCalledTimes(2);
+
+ firstUnmount();
+ secondUnmount();
+ registry.dispose();
+ });
+
+ it("exposes prefetch failures", async () => {
+ const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
+ const registry = AtomRegistry.make();
+ const atom = imageAtom("https://example.test/missing.png");
+ const unmount = registry.mount(atom);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
+ });
+
+ unmount();
+ registry.dispose();
+ });
+});
diff --git a/apps/mobile/src/features/files/workspace-file-image-cache.ts b/apps/mobile/src/features/files/workspace-file-image-cache.ts
new file mode 100644
index 000000000..3f58f65b4
--- /dev/null
+++ b/apps/mobile/src/features/files/workspace-file-image-cache.ts
@@ -0,0 +1,48 @@
+import * as Data from "effect/Data";
+import * as Effect from "effect/Effect";
+import { Atom } from "effect/unstable/reactivity";
+
+const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
+
+type ImagePrefetch = (uri: string) => Promise<boolean>;
+
+class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
+
+export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
+ readonly cause?: unknown;
+ readonly uri: string;
+}> {}
+
+async function prefetchWithNativeImage(uri: string): Promise<boolean> {
+ const { Image } = await import("react-native");
+ return Image.prefetch(uri);
+}
+
+export function createWorkspaceFileImageAtomFamily(options?: {
+ readonly idleTtlMs?: number;
+ readonly prefetch?: ImagePrefetch;
+}) {
+ const idleTtlMs = options?.idleTtlMs ?? WORKSPACE_IMAGE_IDLE_TTL_MS;
+ const prefetch = options?.prefetch ?? prefetchWithNativeImage;
+ const family = Atom.family((key: WorkspaceImageCacheKey) =>
+ Atom.make(
+ Effect.tryPromise({
+ try: async () => {
+ const cached = await prefetch(key.uri);
+ if (!cached) {
+ throw new WorkspaceImagePrefetchError({ uri: key.uri });
+ }
+ return key.uri;
+ },
+ catch: (cause) =>
+ cause instanceof WorkspaceImagePrefetchError
+ ? cause
+ : new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
+ }),
+ ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`mobile:workspace-image:${key.uri}`)),
+ );
+
+ return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
+}
+
+export const workspaceFileImageAtom = createWorkspaceFileImageAtomFamily();
diff --git a/apps/mobile/src/features/files/workspaceFileAssetUrl.ts b/apps/mobile/src/features/files/workspaceFileAssetUrl.ts
new file mode 100644
index 000000000..70ea3e435
--- /dev/null
+++ b/apps/mobile/src/features/files/workspaceFileAssetUrl.ts
@@ -0,0 +1,31 @@
+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { useMemo } from "react";
+
+import { useAssetUrl } from "../../state/assets";
+import { resolveWorkspaceFilePath } from "./filePath";
+
+export function useWorkspaceFileAssetUrl(props: {
+ readonly cwd: string | null;
+ readonly environmentId: EnvironmentId | null;
+ readonly relativePath: string | null;
+ readonly threadId: ThreadId | null;
+}) {
+ const absolutePath = useMemo(
+ () =>
+ props.cwd !== null && props.relativePath !== null
+ ? resolveWorkspaceFilePath(props.cwd, props.relativePath)
+ : null,
+ [props.cwd, props.relativePath],
+ );
+
+ return useAssetUrl(
+ props.environmentId,
+ absolutePath !== null && props.threadId !== null
+ ? {
+ _tag: "workspace-file",
+ threadId: props.threadId,
+ path: absolutePath,
+ }
+ : null,
+ );
+}
diff --git a/apps/mobile/src/features/home/HomeHeader.tsx b/apps/mobile/src/features/home/HomeHeader.tsx
new file mode 100644
index 000000000..839053523
--- /dev/null
+++ b/apps/mobile/src/features/home/HomeHeader.tsx
@@ -0,0 +1,244 @@
+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 { Stack } from "expo-router";
+import { Text as RNText, View } from "react-native";
+
+import { useThemeColor } from "../../lib/useThemeColor";
+import type { HomeProjectSortOrder } from "./homeThreadList";
+
+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 function HomeHeader(props: {
+ readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
+ 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 onOpenSettings: () => void;
+ readonly onStartNewTask: () => void;
+}) {
+ 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;
+
+ return (
+ <>
+ <Stack.Screen
+ options={{
+ headerShown: true,
+ headerTransparent: true,
+ headerStyle: { backgroundColor: "transparent" },
+ headerShadowVisible: false,
+ headerTintColor: iconColor,
+ headerTitle: "",
+ headerSearchBarOptions: {
+ placeholder: "Search threads",
+ hideNavigationBar: false,
+ onChangeText: (event) => {
+ props.onSearchQueryChange(event.nativeEvent.text);
+ },
+ onCancelButtonPress: () => {
+ props.onSearchQueryChange("");
+ },
+ allowToolbarIntegration: true,
+ },
+ }}
+ />
+
+ <Stack.Toolbar placement="left">
+ <Stack.Toolbar.View hidesSharedBackground>
+ <View
+ style={{
+ width: 128,
+ height: 32,
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 8,
+ }}
+ >
+ <RNText
+ style={{
+ fontFamily: "DMSans_700Bold",
+ fontSize: 17,
+ color: iconColor,
+ letterSpacing: -0.4,
+ }}
+ >
+ T3 Code
+ </RNText>
+ <View
+ style={{
+ backgroundColor: subtleColor,
+ borderRadius: 99,
+ paddingHorizontal: 8,
+ paddingVertical: 3,
+ }}
+ >
+ <RNText
+ style={{
+ fontFamily: "DMSans_700Bold",
+ fontSize: 10,
+ color: mutedColor,
+ letterSpacing: 1.1,
+ textTransform: "uppercase",
+ }}
+ >
+ Alpha
+ </RNText>
+ </View>
+ </View>
+ </Stack.Toolbar.View>
+ </Stack.Toolbar>
+
+ <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>
+
+ <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>
+
+ <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>
+ </>
+ );
+}
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index b79d299f0..34de07ed9 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -2,12 +2,26 @@ import {
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
+import type {
+ EnvironmentId,
+ SidebarProjectGroupingMode,
+ SidebarThreadSortOrder,
+} from "@t3tools/contracts";
+import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
-import { useCallback, useMemo, useState } from "react";
-import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
+import { useCallback, useMemo, useRef, useState } from "react";
+import { ActivityIndicator, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
+import ReanimatedSwipeable, {
+ type SwipeableMethods,
+} from "react-native-gesture-handler/ReanimatedSwipeable";
+import Animated, {
+ Easing,
+ LinearTransition,
+ type ExitAnimationsValues,
+ withDelay,
+ withTiming,
+} from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
-import * as Arr from "effect/Array";
-import * as Order from "effect/Order";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
@@ -15,9 +29,14 @@ import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
-import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "../threads/threadPresentation";
+import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
+import {
+ THREAD_SWIPE_ACTIONS_WIDTH,
+ THREAD_SWIPE_SPRING,
+ ThreadSwipeActions,
+} from "./thread-swipe-actions";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -27,26 +46,17 @@ interface HomeScreenProps {
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly searchQuery: string;
+ readonly selectedEnvironmentId: EnvironmentId | null;
+ readonly projectSortOrder: HomeProjectSortOrder;
+ readonly threadSortOrder: SidebarThreadSortOrder;
+ readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
+ readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
+ readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
}
-interface ProjectGroup {
- readonly key: string;
- readonly project: EnvironmentProject;
- readonly threads: ReadonlyArray<EnvironmentThreadShell>;
-}
-
-const projectGroupActivityOrder = Order.mapInput(
- Order.Struct({
- activityAt: Order.flip(Order.Number),
- }),
- (group: ProjectGroup) => ({
- activityAt: new Date(group.threads[0]!.updatedAt ?? group.threads[0]!.createdAt).getTime(),
- }),
-);
-
/* ─── Status indicator colors ────────────────────────────────────────── */
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
@@ -65,6 +75,33 @@ function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string
}
const COLLAPSED_THREAD_LIMIT = 6;
+const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
+
+function threadRowExit(values: ExitAnimationsValues) {
+ "worklet";
+
+ return {
+ initialValues: {
+ height: values.currentHeight,
+ opacity: 1,
+ originX: values.currentOriginX,
+ },
+ animations: {
+ height: withDelay(
+ 90,
+ withTiming(0, {
+ duration: 170,
+ easing: Easing.inOut(Easing.cubic),
+ }),
+ ),
+ opacity: withDelay(80, withTiming(0, { duration: 100 })),
+ originX: withTiming(values.currentOriginX - values.windowWidth, {
+ duration: 190,
+ easing: Easing.out(Easing.cubic),
+ }),
+ },
+ };
+}
function deriveEmptyState(props: {
readonly catalogState: WorkspaceState;
@@ -133,6 +170,7 @@ function deriveEmptyState(props: {
function ProjectGroupLabel(props: {
readonly project: EnvironmentProject;
+ readonly title: string;
readonly totalThreadCount: number;
readonly isExpanded: boolean;
readonly onToggleExpand: () => void;
@@ -152,7 +190,7 @@ function ProjectGroupLabel(props: {
style={{ letterSpacing: 0.5 }}
numberOfLines={1}
>
- {props.project.title}
+ {props.title}
</Text>
{hiddenCount > 0 ? (
@@ -175,95 +213,172 @@ function ThreadRow(props: {
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly onPress: () => void;
+ readonly onArchive: () => void;
+ readonly onDelete: () => void;
+ readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
+ readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly isLast: boolean;
}) {
+ const swipeableRef = useRef<SwipeableMethods | null>(null);
+ const fullSwipeArmedRef = useRef(false);
+ const { width: windowWidth } = useWindowDimensions();
const separatorColor = useThemeColor("--color-separator");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
+ const cardColor = useThemeColor("--color-card");
+ const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const { bg, fg } = statusColors(props.thread);
const tone = threadStatusTone(props.thread);
- const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
+ const timestamp = relativeTime(
+ props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt,
+ );
const branch = props.thread.branch;
const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
Boolean(part),
);
+ const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
+ if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
+ void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
+ }
+ fullSwipeArmedRef.current = armed;
+ }, []);
return (
- <Pressable onPress={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,
+ <ReanimatedSwipeable
+ ref={swipeableRef}
+ animationOptions={THREAD_SWIPE_SPRING}
+ childrenContainerStyle={{ backgroundColor: cardColor }}
+ containerStyle={{ backgroundColor: cardColor }}
+ dragOffsetFromRightEdge={8}
+ enableTrackpadTwoFingerGesture
+ friction={1}
+ onSwipeableClose={() => {
+ fullSwipeArmedRef.current = false;
+ if (swipeableRef.current) {
+ props.onSwipeableClose(swipeableRef.current);
+ }
+ }}
+ onSwipeableOpenStartDrag={() => {
+ if (swipeableRef.current) {
+ props.onSwipeableWillOpen(swipeableRef.current);
+ }
+ }}
+ onSwipeableWillOpen={() => {
+ const methods = swipeableRef.current;
+ if (!methods) {
+ return;
+ }
+
+ props.onSwipeableWillOpen(methods);
+ if (fullSwipeArmedRef.current) {
+ fullSwipeArmedRef.current = false;
+ methods.close();
+ props.onDelete();
+ }
+ }}
+ overshootFriction={1}
+ overshootRight
+ renderRightActions={(_progress, translation, methods) => (
+ <ThreadSwipeActions
+ backgroundColor={cardColor}
+ fullSwipeThreshold={fullSwipeThreshold}
+ onDelete={props.onDelete}
+ onFullSwipeArmedChange={handleFullSwipeArmedChange}
+ primaryAction={{
+ accessibilityLabel: `Archive ${props.thread.title}`,
+ icon: "archivebox",
+ label: "Archive",
+ onPress: props.onArchive,
+ }}
+ swipeableMethods={methods}
+ threadTitle={props.thread.title}
+ translation={translation}
+ />
+ )}
+ rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
+ >
+ <Pressable
+ accessibilityHint="Swipe left for archive and delete actions"
+ accessibilityLabel={props.thread.title}
+ accessibilityRole="button"
+ className="bg-card"
+ onPress={() => {
+ swipeableRef.current?.close();
+ props.onPress();
}}
+ style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
- {/* Git status indicator */}
<View
style={{
- width: 30,
- height: 30,
- borderRadius: 9,
- backgroundColor: bg,
- alignItems: "center",
- justifyContent: "center",
- marginTop: 2,
+ flexDirection: "row",
+ paddingLeft: 16,
+ paddingRight: 16,
+ paddingVertical: 10,
+ gap: 12,
+ borderBottomWidth: props.isLast ? 0 : 1,
+ borderBottomColor: separatorColor,
}}
>
- <SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
- </View>
-
- {/* Content */}
- <View style={{ flex: 1, gap: 3 }}>
- {/* Title + Status + Timestamp */}
- <View className="flex-row items-center justify-between gap-2">
- <Text
- className="flex-1 text-[15px] 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-[10px] font-t3-bold ${tone.textClassName}`}>
- {tone.label}
- </Text>
- </View>
- <Text
- className="text-[12px] text-foreground-tertiary"
- style={{ fontVariant: ["tabular-nums"] }}
- >
- {timestamp}
- </Text>
- </View>
+ <View
+ style={{
+ width: 30,
+ height: 30,
+ borderRadius: 9,
+ backgroundColor: bg,
+ alignItems: "center",
+ justifyContent: "center",
+ marginTop: 2,
+ }}
+ >
+ <SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
</View>
- {/* Environment + branch */}
- {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 }}>
+ <View className="flex-row items-center justify-between gap-2">
<Text
- className="text-[11px] text-foreground-tertiary"
+ className="flex-1 text-[15px] font-t3-bold leading-[20px] 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-[10px] font-t3-bold ${tone.textClassName}`}>
+ {tone.label}
+ </Text>
+ </View>
+ <Text
+ className="text-[12px] text-foreground-tertiary"
+ style={{ fontVariant: ["tabular-nums"] }}
+ >
+ {timestamp}
+ </Text>
+ </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-[11px] text-foreground-tertiary"
+ numberOfLines={1}
+ style={{ fontFamily: "monospace" }}
+ >
+ {subtitleParts.join(" · ")}
+ </Text>
+ </View>
+ ) : null}
+ </View>
</View>
- </View>
- </Pressable>
+ </Pressable>
+ </ReanimatedSwipeable>
);
}
@@ -323,6 +438,7 @@ function StaleCatalogStatusPill(props: {
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
+ const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
@@ -335,51 +451,50 @@ export function HomeScreen(props: HomeScreenProps) {
});
}, []);
- /* Build project title lookup for search */
- const projectTitleByKey = useMemo(() => {
- const map = new Map<string, string>();
- for (const p of props.projects) {
- map.set(scopedProjectKey(p.environmentId, p.id), p.title);
- }
- return map;
- }, [props.projects]);
-
- /* Filter threads by search query */
- const filteredThreads = useMemo(() => {
- const q = props.searchQuery.trim().toLowerCase();
- if (!q) return props.threads;
- return props.threads.filter((t) => {
- if (t.title.toLowerCase().includes(q)) return true;
- const key = scopedProjectKey(t.environmentId, t.projectId);
- return projectTitleByKey.get(key)?.toLowerCase().includes(q) ?? false;
- });
- }, [props.threads, props.searchQuery, projectTitleByKey]);
-
- /* Group filtered threads by project */
- const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => {
- const byProject = new Map<string, EnvironmentThreadShell[]>();
- for (const thread of filteredThreads) {
- const key = scopedProjectKey(thread.environmentId, thread.projectId);
- const existing = byProject.get(key);
- if (existing) existing.push(thread);
- else byProject.set(key, [thread]);
+ const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
+ if (openSwipeableRef.current !== methods) {
+ openSwipeableRef.current?.close();
+ openSwipeableRef.current = methods;
}
+ }, []);
- const groups: ProjectGroup[] = [];
- for (const project of props.projects) {
- const key = scopedProjectKey(project.environmentId, project.id);
- const threads = byProject.get(key);
- if (threads && threads.length > 0) {
- groups.push({ key, project, threads });
- }
+ const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
+ if (openSwipeableRef.current === methods) {
+ openSwipeableRef.current = null;
}
+ }, []);
- return Arr.sort(groups, projectGroupActivityOrder);
- }, [props.projects, filteredThreads]);
+ const projectGroups = useMemo(
+ () =>
+ buildHomeThreadGroups({
+ projects: props.projects,
+ threads: props.threads,
+ environmentId: props.selectedEnvironmentId,
+ searchQuery: props.searchQuery,
+ projectSortOrder: props.projectSortOrder,
+ threadSortOrder: props.threadSortOrder,
+ projectGroupingMode: props.projectGroupingMode,
+ }),
+ [
+ props.projectGroupingMode,
+ props.projects,
+ props.projectSortOrder,
+ props.searchQuery,
+ props.selectedEnvironmentId,
+ props.threadSortOrder,
+ props.threads,
+ ],
+ );
/* Empty states */
- const hasAnyThreads = props.threads.length > 0;
- const hasResults = filteredThreads.length > 0;
+ const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
+ const hasResults = projectGroups.length > 0;
+ const selectedEnvironmentLabel =
+ props.selectedEnvironmentId === null
+ ? null
+ : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
+ "this environment");
+ const hasSearchQuery = props.searchQuery.trim().length > 0;
const shouldShowConnectionStatus =
props.catalogState.networkStatus === "offline" ||
props.catalogState.hasConnectingEnvironment ||
@@ -396,6 +511,7 @@ export function HomeScreen(props: HomeScreenProps) {
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
+ onScrollBeginDrag={() => openSwipeableRef.current?.close()}
className="flex-1"
contentContainerStyle={{
paddingHorizontal: 16,
@@ -418,8 +534,18 @@ export function HomeScreen(props: HomeScreenProps) {
</View>
) : null}
</View>
- ) : !hasResults ? (
+ ) : !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);
@@ -428,30 +554,52 @@ export function HomeScreen(props: HomeScreenProps) {
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
return (
- <View key={group.key}>
+ <Animated.View
+ key={group.key}
+ collapsable={false}
+ exiting={threadRowExit}
+ layout={THREAD_LAYOUT_TRANSITION}
+ style={{ overflow: "hidden" }}
+ >
<ProjectGroupLabel
- project={group.project}
- totalThreadCount={group.threads.length}
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) => (
- <ThreadRow
- key={`${thread.environmentId}:${thread.id}`}
- thread={thread}
- environmentLabel={
- props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
- }
- onPress={() => props.onSelectThread(thread)}
- isLast={i === visibleThreads.length - 1}
- />
- ))}
+ {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>
- </View>
+ </Animated.View>
);
})
)}
diff --git a/apps/mobile/src/features/home/homeThreadList.test.ts b/apps/mobile/src/features/home/homeThreadList.test.ts
new file mode 100644
index 000000000..cf9b0824a
--- /dev/null
+++ b/apps/mobile/src/features/home/homeThreadList.test.ts
@@ -0,0 +1,223 @@
+import type {
+ EnvironmentProject,
+ EnvironmentThreadShell,
+} from "@t3tools/client-runtime/state/shell";
+import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { buildHomeThreadGroups } from "./homeThreadList";
+
+function makeProject(
+ input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
+): EnvironmentProject {
+ return {
+ workspaceRoot: `/workspaces/${input.id}`,
+ repositoryIdentity: null,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-01T00:00:00.000Z",
+ ...input,
+ };
+}
+
+function makeThread(
+ input: Partial<EnvironmentThreadShell> &
+ Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
+): EnvironmentThreadShell {
+ return {
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-01T00:00:00.000Z",
+ archivedAt: null,
+ session: null,
+ latestUserMessageAt: null,
+ hasPendingApprovals: false,
+ hasPendingUserInput: false,
+ hasActionableProposedPlan: false,
+ ...input,
+ };
+}
+
+function buildGroups(
+ projects: ReadonlyArray<EnvironmentProject>,
+ threads: ReadonlyArray<EnvironmentThreadShell>,
+ overrides: Partial<Parameters<typeof buildHomeThreadGroups>[0]> = {},
+) {
+ return buildHomeThreadGroups({
+ projects,
+ threads,
+ environmentId: null,
+ searchQuery: "",
+ projectSortOrder: "updated_at",
+ threadSortOrder: "updated_at",
+ projectGroupingMode: "repository",
+ ...overrides,
+ });
+}
+
+describe("buildHomeThreadGroups", () => {
+ it("sorts the newest thread first regardless of snapshot order", () => {
+ const environmentId = EnvironmentId.make("environment-1");
+ const project = makeProject({
+ environmentId,
+ id: ProjectId.make("project-1"),
+ title: "T3 Code",
+ });
+ const threads = [
+ makeThread({
+ environmentId,
+ id: ThreadId.make("thread-old"),
+ projectId: project.id,
+ title: "Older thread",
+ updatedAt: "2026-06-02T00:00:00.000Z",
+ }),
+ makeThread({
+ environmentId,
+ id: ThreadId.make("thread-new"),
+ projectId: project.id,
+ title: "Newer thread",
+ updatedAt: "2026-06-03T00:00:00.000Z",
+ }),
+ ];
+
+ expect(buildGroups([project], threads)[0]?.threads.map((thread) => thread.id)).toEqual([
+ "thread-new",
+ "thread-old",
+ ]);
+ });
+
+ it("supports independent project and thread creation-time sorting", () => {
+ const environmentId = EnvironmentId.make("environment-1");
+ const olderProject = makeProject({
+ environmentId,
+ id: ProjectId.make("project-older"),
+ title: "Older project",
+ });
+ const newerProject = makeProject({
+ environmentId,
+ id: ProjectId.make("project-newer"),
+ title: "Newer project",
+ });
+ const threads = [
+ makeThread({
+ environmentId,
+ id: ThreadId.make("old-created"),
+ projectId: olderProject.id,
+ title: "Updated recently",
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-05T00:00:00.000Z",
+ }),
+ makeThread({
+ environmentId,
+ id: ThreadId.make("new-created"),
+ projectId: olderProject.id,
+ title: "Created recently",
+ createdAt: "2026-06-04T00:00:00.000Z",
+ updatedAt: "2026-06-04T00:00:00.000Z",
+ }),
+ makeThread({
+ environmentId,
+ id: ThreadId.make("newest-project-thread"),
+ projectId: newerProject.id,
+ title: "Newest project",
+ createdAt: "2026-06-06T00:00:00.000Z",
+ }),
+ ];
+
+ const groups = buildGroups([olderProject, newerProject], threads, {
+ projectSortOrder: "created_at",
+ threadSortOrder: "created_at",
+ projectGroupingMode: "separate",
+ });
+
+ expect(groups.map((group) => group.representative.id)).toEqual([
+ "project-newer",
+ "project-older",
+ ]);
+ expect(groups[1]?.threads.map((thread) => thread.id)).toEqual(["new-created", "old-created"]);
+ });
+
+ it("filters both projects and threads to one environment", () => {
+ const localEnvironmentId = EnvironmentId.make("environment-local");
+ const remoteEnvironmentId = EnvironmentId.make("environment-remote");
+ const projects = [
+ makeProject({
+ environmentId: localEnvironmentId,
+ id: ProjectId.make("project-local"),
+ title: "Local",
+ }),
+ makeProject({
+ environmentId: remoteEnvironmentId,
+ id: ProjectId.make("project-remote"),
+ title: "Remote",
+ }),
+ ];
+ const threads = projects.map((project) =>
+ makeThread({
+ environmentId: project.environmentId,
+ id: ThreadId.make(`thread-${project.id}`),
+ projectId: project.id,
+ title: project.title,
+ }),
+ );
+
+ const groups = buildGroups(projects, threads, { environmentId: remoteEnvironmentId });
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.representative.environmentId).toBe(remoteEnvironmentId);
+ expect(groups[0]?.threads.map((thread) => thread.environmentId)).toEqual([remoteEnvironmentId]);
+ });
+
+ it("matches web repository, repository-path, and separate grouping modes", () => {
+ const environmentId = EnvironmentId.make("environment-1");
+ const repositoryIdentity = {
+ canonicalKey: "github.com/t3tools/t3code",
+ locator: {
+ source: "git-remote" as const,
+ remoteName: "origin",
+ remoteUrl: "[email protected]:t3tools/t3code.git",
+ },
+ provider: "github",
+ owner: "t3tools",
+ name: "t3code",
+ displayName: "T3 Code",
+ rootPath: "/workspaces/t3code",
+ };
+ const projects = [
+ makeProject({
+ environmentId,
+ id: ProjectId.make("project-web"),
+ title: "Web",
+ workspaceRoot: "/workspaces/t3code/apps/web",
+ repositoryIdentity,
+ }),
+ makeProject({
+ environmentId,
+ id: ProjectId.make("project-mobile"),
+ title: "Mobile",
+ workspaceRoot: "/workspaces/t3code/apps/mobile",
+ repositoryIdentity,
+ }),
+ ];
+ const threads = projects.map((project) =>
+ makeThread({
+ environmentId,
+ id: ThreadId.make(`thread-${project.id}`),
+ projectId: project.id,
+ title: project.title,
+ }),
+ );
+
+ expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
+ expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
+ 2,
+ );
+ expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
+ });
+});
diff --git a/apps/mobile/src/features/home/homeThreadList.ts b/apps/mobile/src/features/home/homeThreadList.ts
new file mode 100644
index 000000000..9f09e894c
--- /dev/null
+++ b/apps/mobile/src/features/home/homeThreadList.ts
@@ -0,0 +1,140 @@
+import {
+ deriveLogicalProjectKey,
+ deriveProjectGroupLabel,
+} from "@t3tools/client-runtime/state/project-grouping";
+import type {
+ EnvironmentProject,
+ EnvironmentThreadShell,
+} from "@t3tools/client-runtime/state/shell";
+import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
+import type {
+ EnvironmentId,
+ SidebarProjectGroupingMode,
+ SidebarProjectSortOrder,
+ SidebarThreadSortOrder,
+} from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+
+import { scopedProjectKey } from "../../lib/scopedEntities";
+
+export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
+
+export interface HomeThreadGroup {
+ readonly key: string;
+ readonly title: string;
+ readonly representative: EnvironmentProject;
+ readonly projects: ReadonlyArray<EnvironmentProject>;
+ readonly threads: ReadonlyArray<EnvironmentThreadShell>;
+}
+
+interface MutableHomeThreadGroup {
+ readonly key: string;
+ readonly projects: EnvironmentProject[];
+ readonly threads: EnvironmentThreadShell[];
+}
+
+function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
+ return group.threads.reduce(
+ (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
+ Number.NEGATIVE_INFINITY,
+ );
+}
+
+export function buildHomeThreadGroups(input: {
+ readonly projects: ReadonlyArray<EnvironmentProject>;
+ readonly threads: ReadonlyArray<EnvironmentThreadShell>;
+ readonly environmentId: EnvironmentId | null;
+ readonly searchQuery: string;
+ readonly projectSortOrder: HomeProjectSortOrder;
+ readonly threadSortOrder: SidebarThreadSortOrder;
+ readonly projectGroupingMode: SidebarProjectGroupingMode;
+}): ReadonlyArray<HomeThreadGroup> {
+ const groups = new Map<string, MutableHomeThreadGroup>();
+ const groupKeyByProjectKey = new Map<string, string>();
+
+ for (const project of input.projects) {
+ if (input.environmentId !== null && project.environmentId !== input.environmentId) {
+ continue;
+ }
+
+ const groupKey = deriveLogicalProjectKey(project, {
+ groupingMode: input.projectGroupingMode,
+ });
+ const physicalKey = scopedProjectKey(project.environmentId, project.id);
+ groupKeyByProjectKey.set(physicalKey, groupKey);
+
+ const existing = groups.get(groupKey);
+ if (existing) {
+ existing.projects.push(project);
+ } else {
+ groups.set(groupKey, { key: groupKey, projects: [project], threads: [] });
+ }
+ }
+
+ for (const thread of input.threads) {
+ if (thread.archivedAt !== null) {
+ continue;
+ }
+ if (input.environmentId !== null && thread.environmentId !== input.environmentId) {
+ continue;
+ }
+
+ const physicalKey = scopedProjectKey(thread.environmentId, thread.projectId);
+ const groupKey = groupKeyByProjectKey.get(physicalKey);
+ if (!groupKey) {
+ continue;
+ }
+ groups.get(groupKey)?.threads.push(thread);
+ }
+
+ const query = input.searchQuery.trim().toLocaleLowerCase();
+ const result: HomeThreadGroup[] = [];
+
+ for (const group of groups.values()) {
+ const representative = group.projects[0];
+ if (!representative || group.threads.length === 0) {
+ continue;
+ }
+
+ const title =
+ group.projects.length > 1
+ ? deriveProjectGroupLabel({ representative, members: group.projects })
+ : representative.title;
+ const groupMatches =
+ query.length === 0 ||
+ title.toLocaleLowerCase().includes(query) ||
+ group.projects.some((project) => project.title.toLocaleLowerCase().includes(query));
+ const matchingThreads = groupMatches
+ ? group.threads
+ : group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
+
+ if (matchingThreads.length === 0) {
+ continue;
+ }
+
+ result.push({
+ key: group.key,
+ title,
+ representative,
+ projects: group.projects,
+ threads: sortThreads(matchingThreads, input.threadSortOrder),
+ });
+ }
+
+ return Arr.sort(
+ result,
+ Order.mapInput(
+ Order.Struct({
+ timestamp: Order.flip(Order.Number),
+ title: Order.String,
+ key: Order.String,
+ }),
+ (group: HomeThreadGroup) => ({
+ timestamp: groupSortTimestamp(group, input.projectSortOrder),
+ title: group.title,
+ key: group.key,
+ }),
+ ),
+ );
+}
diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx
new file mode 100644
index 000000000..faedaed7c
--- /dev/null
+++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx
@@ -0,0 +1,238 @@
+import { SymbolView } from "expo-symbols";
+import type { ComponentProps } from "react";
+import type { ColorValue } from "react-native";
+import { Pressable, View } from "react-native";
+import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
+import Animated, {
+ Extrapolation,
+ interpolate,
+ runOnJS,
+ type SharedValue,
+ useAnimatedReaction,
+ useAnimatedStyle,
+} from "react-native-reanimated";
+
+import { AppText as Text } from "../../components/AppText";
+
+const ACTION_ITEM_WIDTH = 50;
+const ACTION_CIRCLE_SIZE = 36;
+const ACTION_ICON_SIZE = 15;
+
+export const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
+export const THREAD_SWIPE_SPRING = {
+ damping: 26,
+ mass: 0.7,
+ overshootClamping: true,
+ stiffness: 330,
+};
+
+function SwipeActionButton(props: {
+ readonly accessibilityLabel: string;
+ readonly backgroundColor: string;
+ readonly entryRange: readonly [number, number];
+ readonly fullSwipeThreshold: number;
+ readonly icon: ComponentProps<typeof SymbolView>["name"];
+ readonly label: string;
+ readonly onPress: () => void;
+ readonly stretchesOnFullSwipe: boolean;
+ readonly translation: SharedValue<number>;
+}) {
+ const actionStyle = useAnimatedStyle(() => {
+ const reveal = Math.max(-props.translation.value, 0);
+ const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
+ const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
+ const fullSwipeProgress = interpolate(
+ reveal,
+ [THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
+ [0, 1],
+ Extrapolation.CLAMP,
+ );
+
+ return {
+ opacity: props.stretchesOnFullSwipe ? entryProgress : entryProgress * (1 - fullSwipeProgress),
+ transform: [
+ {
+ translateX:
+ interpolate(entryProgress, [0, 1], [22, 0]) -
+ (props.stretchesOnFullSwipe ? 0 : stretch),
+ },
+ { scale: interpolate(entryProgress, [0, 1], [0.78, 1]) },
+ ],
+ };
+ });
+ const circleStyle = useAnimatedStyle(() => {
+ const reveal = Math.max(-props.translation.value, 0);
+ const stretch = props.stretchesOnFullSwipe
+ ? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
+ : 0;
+
+ return {
+ transform: [{ translateX: -stretch }],
+ width: ACTION_CIRCLE_SIZE + stretch,
+ };
+ });
+ const iconStyle = useAnimatedStyle(() => {
+ const reveal = Math.max(-props.translation.value, 0);
+ const stretch = props.stretchesOnFullSwipe
+ ? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
+ : 0;
+ const armedProgress = interpolate(
+ reveal,
+ [props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
+ [0, 1],
+ Extrapolation.CLAMP,
+ );
+
+ return {
+ transform: [{ translateX: -stretch * (0.5 + armedProgress * 0.5) }],
+ };
+ });
+ const labelStyle = useAnimatedStyle(() => {
+ if (!props.stretchesOnFullSwipe) {
+ return { opacity: 1 };
+ }
+
+ const reveal = Math.max(-props.translation.value, 0);
+ const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
+ return {
+ opacity: interpolate(
+ reveal,
+ [props.fullSwipeThreshold - 24, props.fullSwipeThreshold],
+ [1, 0],
+ Extrapolation.CLAMP,
+ ),
+ transform: [{ translateX: -stretch * 0.5 }],
+ };
+ });
+
+ return (
+ <Animated.View
+ style={[
+ {
+ alignItems: "center",
+ height: "100%",
+ justifyContent: "center",
+ width: ACTION_ITEM_WIDTH,
+ zIndex: props.stretchesOnFullSwipe ? 2 : 1,
+ },
+ actionStyle,
+ ]}
+ >
+ <Pressable
+ accessibilityLabel={props.accessibilityLabel}
+ accessibilityRole="button"
+ onPress={props.onPress}
+ style={({ pressed }) => ({
+ alignItems: "center",
+ height: "100%",
+ justifyContent: "center",
+ opacity: pressed ? 0.72 : 1,
+ width: "100%",
+ })}
+ >
+ <View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
+ <Animated.View
+ style={[
+ {
+ backgroundColor: props.backgroundColor,
+ borderRadius: 999,
+ height: ACTION_CIRCLE_SIZE,
+ left: 0,
+ position: "absolute",
+ top: 0,
+ },
+ circleStyle,
+ ]}
+ />
+ <Animated.View
+ style={[
+ {
+ alignItems: "center",
+ height: ACTION_CIRCLE_SIZE,
+ justifyContent: "center",
+ left: 0,
+ position: "absolute",
+ top: 0,
+ width: ACTION_CIRCLE_SIZE,
+ },
+ iconStyle,
+ ]}
+ >
+ <SymbolView
+ name={props.icon}
+ size={ACTION_ICON_SIZE}
+ tintColor="#ffffff"
+ type="monochrome"
+ />
+ </Animated.View>
+ </View>
+ <Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
+ <Text className="text-[10px] font-t3-medium text-foreground-muted">{props.label}</Text>
+ </Animated.View>
+ </Pressable>
+ </Animated.View>
+ );
+}
+
+export function ThreadSwipeActions(props: {
+ readonly backgroundColor: ColorValue;
+ 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 swipeableMethods: SwipeableMethods;
+ readonly threadTitle: string;
+ readonly translation: SharedValue<number>;
+}) {
+ useAnimatedReaction(
+ () => -props.translation.value >= props.fullSwipeThreshold,
+ (armed, previous) => {
+ if (armed !== previous) {
+ runOnJS(props.onFullSwipeArmedChange)(armed);
+ }
+ },
+ [props.fullSwipeThreshold, props.onFullSwipeArmedChange],
+ );
+
+ return (
+ <View
+ style={{
+ backgroundColor: props.backgroundColor,
+ flexDirection: "row",
+ height: "100%",
+ width: THREAD_SWIPE_ACTIONS_WIDTH,
+ }}
+ >
+ <SwipeActionButton
+ accessibilityLabel={props.primaryAction.accessibilityLabel}
+ backgroundColor="#007aff"
+ entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
+ fullSwipeThreshold={props.fullSwipeThreshold}
+ icon={props.primaryAction.icon}
+ label={props.primaryAction.label}
+ onPress={props.primaryAction.onPress}
+ stretchesOnFullSwipe={false}
+ translation={props.translation}
+ />
+ <SwipeActionButton
+ accessibilityLabel={`Delete ${props.threadTitle}`}
+ backgroundColor="#ff2d55"
+ entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
+ fullSwipeThreshold={props.fullSwipeThreshold}
+ icon="trash"
+ label="Delete"
+ onPress={() => {
+ props.swipeableMethods.close();
+ props.onDelete();
+ }}
+ stretchesOnFullSwipe
+ translation={props.translation}
+ />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts
new file mode 100644
index 000000000..cc5d0dd04
--- /dev/null
+++ b/apps/mobile/src/features/home/useThreadListActions.ts
@@ -0,0 +1,142 @@
+import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
+import * as Cause from "effect/Cause";
+import * as Haptics from "expo-haptics";
+import { useCallback, useRef } from "react";
+import { Alert } from "react-native";
+
+import { scopedThreadKey } from "../../lib/scopedEntities";
+import { threadEnvironment } from "../../state/threads";
+import { useAtomCommand } from "../../state/use-atom-command";
+
+type ThreadListAction = "archive" | "unarchive" | "delete";
+
+function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
+ const error = Cause.squash(cause);
+ if (error instanceof Error && error.message.trim().length > 0) {
+ return error.message;
+ }
+ const verb =
+ action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
+ return `The thread could not be ${verb}.`;
+}
+
+function selectionHaptic(): void {
+ if (process.env.EXPO_OS === "ios") {
+ void Haptics.selectionAsync();
+ }
+}
+
+function actionFailureTitle(action: ThreadListAction): string {
+ if (action === "archive") return "Could not archive thread";
+ if (action === "unarchive") return "Could not unarchive thread";
+ return "Could not delete thread";
+}
+
+function useThreadActionExecutor(
+ onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
+) {
+ const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
+ const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
+ const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
+ const inFlightThreadKeys = useRef(new Set<string>());
+
+ const executeAction = useCallback(
+ async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
+ const key = scopedThreadKey(thread.environmentId, thread.id);
+ if (inFlightThreadKeys.current.has(key)) {
+ return;
+ }
+
+ inFlightThreadKeys.current.add(key);
+ selectionHaptic();
+ try {
+ const mutation =
+ action === "archive"
+ ? archiveMutation
+ : action === "unarchive"
+ ? unarchiveMutation
+ : deleteMutation;
+ const result = await mutation({
+ environmentId: thread.environmentId,
+ input: { threadId: thread.id },
+ });
+ if (result._tag === "Failure") {
+ Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
+ return;
+ }
+ onCompleted?.(action, thread);
+ } finally {
+ inFlightThreadKeys.current.delete(key);
+ }
+ },
+ [archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
+ );
+
+ return executeAction;
+}
+
+function useConfirmDeleteThread(
+ executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
+) {
+ return useCallback(
+ (thread: EnvironmentThreadShell) => {
+ Alert.alert(
+ "Delete thread?",
+ `“${thread.title}” will be permanently deleted, including its terminal history.`,
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Delete",
+ style: "destructive",
+ onPress: () => {
+ void executeAction("delete", thread);
+ },
+ },
+ ],
+ );
+ },
+ [executeAction],
+ );
+}
+
+export function useThreadListActions(): {
+ readonly archiveThread: (thread: EnvironmentThreadShell) => void;
+ readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
+} {
+ const executeAction = useThreadActionExecutor();
+
+ const archiveThread = useCallback(
+ (thread: EnvironmentThreadShell) => {
+ void executeAction("archive", thread);
+ },
+ [executeAction],
+ );
+
+ const confirmDeleteThread = useConfirmDeleteThread(executeAction);
+
+ return { archiveThread, confirmDeleteThread };
+}
+
+export function useArchivedThreadListActions(
+ onCompleted: (thread: EnvironmentThreadShell) => void,
+): {
+ readonly unarchiveThread: (thread: EnvironmentThreadShell) => void;
+ readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
+} {
+ const handleCompleted = useCallback(
+ (_action: ThreadListAction, thread: EnvironmentThreadShell) => {
+ onCompleted(thread);
+ },
+ [onCompleted],
+ );
+ const executeAction = useThreadActionExecutor(handleCompleted);
+ const unarchiveThread = useCallback(
+ (thread: EnvironmentThreadShell) => {
+ void executeAction("unarchive", thread);
+ },
+ [executeAction],
+ );
+ const confirmDeleteThread = useConfirmDeleteThread(executeAction);
+
+ return { unarchiveThread, confirmDeleteThread };
+}
diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts
index d6d09221d..7030ac77e 100644
--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts
+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts
@@ -695,6 +695,15 @@ export async function highlightCodeSnippet(input: {
return highlightLines(input.code, language, SHIKI_THEME_NAME_BY_SCHEME[input.theme]);
}
+export async function highlightSourceFile(input: {
+ readonly path: string;
+ readonly contents: string;
+ readonly theme: ReviewDiffTheme;
+}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
+ const language = await resolveLanguageFromPath(input.path);
+ return highlightLines(input.contents, language, SHIKI_THEME_NAME_BY_SCHEME[input.theme]);
+}
+
async function highlightPatchLinesInChunks(input: {
readonly lines: ReadonlyArray<string>;
readonly language: string;
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index fbfde4e78..624e8fe14 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -62,6 +62,7 @@ export interface ThreadDetailScreenProps {
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
+ readonly threadCwd: string | null;
readonly selectedThreadQueueCount: number;
readonly serverConfig: T3ServerConfig | null;
readonly layoutVariant?: LayoutVariant;
@@ -309,6 +310,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
+ workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 9b9c4a71d..558635571 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -4,6 +4,7 @@ import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
+import { useRouter } from "expo-router";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
Markdown,
@@ -54,6 +55,7 @@ import {
import { buildReviewParsedDiff } from "../review/reviewModel";
import { cn } from "../../lib/cn";
import type { LayoutVariant } from "../../lib/layout";
+import { buildThreadFilesNavigation } from "../../lib/routes";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
import {
@@ -64,7 +66,9 @@ import {
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
import { relativeTime } from "../../lib/time";
import type { ThreadContentPresentation } from "./threadContentPresentation";
+import { ThreadWorkLog } from "./thread-work-log";
import { useAssetUrl } from "../../state/assets";
+import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const THREAD_FEED_END_THRESHOLD = 80;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
@@ -83,6 +87,7 @@ function formatMessageTime(input: string): string {
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
+ readonly workspaceRoot?: string | null;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly contentPresentation: ThreadContentPresentation;
readonly agentLabel: string;
@@ -120,32 +125,6 @@ function MessageAttachmentImage(props: {
);
}
-function stripShellWrapper(value: string): string {
- const trimmed = value.trim();
- const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
- return (match?.[1] ?? trimmed).trim();
-}
-
-function compactActivityDetail(detail: string | null): string | null {
- if (!detail) {
- return null;
- }
-
- const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
- return cleaned.length > 0 ? cleaned : null;
-}
-
-function buildActivityRows(
- activities: Extract<ThreadFeedEntry, { type: "activity-group" }>["activities"],
-) {
- return activities.map((activity) => ({
- ...activity,
- detail: compactActivityDetail(activity.detail),
- }));
-}
-
-const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
-
const MARKDOWN_COLORS = {
light: {
body: "#111111",
@@ -155,10 +134,12 @@ const MARKDOWN_COLORS = {
blockquoteBackground: "rgba(0, 0, 0, 0.02)",
codeBackground: "rgba(0, 0, 0, 0.04)",
codeText: "#262626",
+ inlineCodeText: "#5f6368",
horizontalRule: "rgba(0, 0, 0, 0.08)",
userBody: "#ffffff",
userCodeBackground: "rgba(255, 255, 255, 0.22)",
userCodeText: "#ffffff",
+ userInlineCodeText: "rgba(255, 255, 255, 0.82)",
userFenceBackground: "rgba(0, 0, 0, 0.16)",
userFenceText: "#ffffff",
},
@@ -170,10 +151,12 @@ const MARKDOWN_COLORS = {
blockquoteBackground: "rgba(255, 255, 255, 0.03)",
codeBackground: "rgba(255, 255, 255, 0.06)",
codeText: "#e5e5e5",
+ inlineCodeText: "#b8bcc2",
horizontalRule: "rgba(255, 255, 255, 0.08)",
userBody: "#ffffff",
userCodeBackground: "rgba(255, 255, 255, 0.18)",
userCodeText: "#ffffff",
+ userInlineCodeText: "rgba(255, 255, 255, 0.82)",
userFenceBackground: "rgba(0, 0, 0, 0.28)",
userFenceText: "#ffffff",
},
@@ -202,27 +185,18 @@ interface ReviewCommentColors {
const failedMarkdownFaviconHosts = new Set<string>();
const markdownLinkStyles = StyleSheet.create({
- favicon: {
+ inlineIcon: {
width: 14,
height: 14,
- borderRadius: 3,
marginHorizontal: 3,
transform: [{ translateY: 2 }],
},
- file: {
- borderRadius: 5,
- borderWidth: StyleSheet.hairlineWidth,
- fontFamily: "DMSans_500Medium",
- fontSize: 13,
- lineHeight: 20,
- paddingHorizontal: 6,
- paddingVertical: 2,
+ favicon: {
+ borderRadius: 3,
},
- fileIcon: {
- width: 15,
- height: 15,
- marginRight: 4,
- transform: [{ translateY: 2 }],
+ file: {
+ fontFamily: "DMSans_700Bold",
+ fontWeight: "700",
},
});
@@ -250,7 +224,7 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
source={{
uri: `https://www.google.com/s2/favicons?domain=${encodeURIComponent(props.host)}&sz=32`,
}}
- style={markdownLinkStyles.favicon}
+ style={[markdownLinkStyles.inlineIcon, markdownLinkStyles.favicon]}
onError={() => {
failedMarkdownFaviconHosts.add(props.host);
setFailed(true);
@@ -287,11 +261,9 @@ function useReviewCommentColors(): ReviewCommentColors {
);
}
-function useMarkdownStyles(): MarkdownStyleSets {
+function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets {
const colorScheme = useColorScheme();
const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"];
- const inlineChipBackground = String(useThemeColor("--color-subtle"));
- const inlineSkillBackground = String(useThemeColor("--color-inline-skill-background"));
const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground"));
return useMemo(() => {
@@ -302,10 +274,12 @@ function useMarkdownStyles(): MarkdownStyleSets {
const markdownBlockquoteBorder = colors.blockquoteBorder;
const markdownCodeBg = colors.codeBackground;
const markdownCodeText = colors.codeText;
+ const markdownInlineCodeText = colors.inlineCodeText;
const markdownHrColor = colors.horizontalRule;
const markdownUserBodyColor = colors.userBody;
const markdownUserCodeBg = colors.userCodeBackground;
const markdownUserCodeText = colors.userCodeText;
+ const markdownUserInlineCodeText = colors.userInlineCodeText;
const markdownUserFenceBg = colors.userFenceBackground;
const markdownUserFenceText = colors.userFenceText;
@@ -394,28 +368,23 @@ function useMarkdownStyles(): MarkdownStyleSets {
};
const createMarkdownRenderers = (
- inlineBackgroundColor: string,
inlineTextColor: string,
+ inlineCodeTextColor: string,
blockBackgroundColor: string,
blockTextColor: string,
+ preserveSoftBreaks: boolean,
): CustomRenderers => ({
link: ({ children, href = "" }) => {
const presentation = resolveMarkdownLinkPresentation(href);
if (presentation.kind === "file") {
return (
<NativeText
- style={[
- markdownLinkStyles.file,
- {
- backgroundColor: inlineBackgroundColor,
- borderColor: markdownHrColor,
- color: inlineTextColor,
- },
- ]}
+ onPress={() => onLinkPress(href)}
+ style={[markdownLinkStyles.file, { color: inlineTextColor }]}
>
<Image
source={markdownFileIconSource(presentation.icon)}
- style={markdownLinkStyles.fileIcon}
+ style={markdownLinkStyles.inlineIcon}
/>
{presentation.label}
</NativeText>
@@ -492,28 +461,24 @@ function useMarkdownStyles(): MarkdownStyleSets {
),
code_inline: ({ content }) => {
const value = content ?? "";
- const wrapsPoorly =
- value.length > 24 || value.includes("/") || value.includes("\\") || value.includes(":");
return (
<NativeText
style={{
- color: inlineTextColor,
+ color: inlineCodeTextColor,
fontFamily: "ui-monospace",
fontSize: 12,
- lineHeight: 18,
- ...(wrapsPoorly
- ? { opacity: 0.82 }
- : {
- backgroundColor: inlineBackgroundColor,
- borderRadius: 4,
- paddingHorizontal: 3,
- }),
+ lineHeight: 22,
}}
>
{value}
</NativeText>
);
},
+ ...(preserveSoftBreaks
+ ? {
+ soft_break: () => <NativeText>{"\n"}</NativeText>,
+ }
+ : {}),
code_block: ({ content, language }) => (
<View
style={{
@@ -619,23 +584,23 @@ function useMarkdownStyles(): MarkdownStyleSets {
theme: userTheme,
styles: userStyles,
renderers: createMarkdownRenderers(
- markdownUserCodeBg,
markdownUserCodeText,
+ markdownUserInlineCodeText,
markdownUserFenceBg,
markdownUserFenceText,
+ true,
),
nativeTextStyle: {
color: markdownUserBodyColor,
strongColor: markdownUserBodyColor,
mutedColor: markdownUserBodyColor,
linkColor: markdownUserBodyColor,
+ inlineCodeColor: markdownUserInlineCodeText,
codeColor: markdownUserCodeText,
codeBackgroundColor: markdownUserCodeBg,
codeBlockBackgroundColor: markdownUserFenceBg,
- fileBackgroundColor: "rgba(255, 255, 255, 0.12)",
fileTextColor: "#ffffff",
- skillBackgroundColor: "rgba(217, 70, 239, 0.24)",
- skillTextColor: "#ffffff",
+ skillTextColor: "#f0abfc",
quoteMarkerColor: markdownUserBodyColor,
dividerColor: markdownUserBodyColor,
fontSize: 15,
@@ -649,22 +614,22 @@ function useMarkdownStyles(): MarkdownStyleSets {
theme: assistantTheme,
styles: assistantStyles,
renderers: createMarkdownRenderers(
- markdownCodeBg,
markdownCodeText,
+ markdownInlineCodeText,
markdownCodeBg,
markdownCodeText,
+ false,
),
nativeTextStyle: {
color: markdownBodyColor,
strongColor: markdownStrongColor,
mutedColor: markdownBodyColor,
linkColor: markdownLinkColor,
+ inlineCodeColor: markdownInlineCodeText,
codeColor: markdownCodeText,
codeBackgroundColor: markdownCodeBg,
codeBlockBackgroundColor: markdownCodeBg,
- fileBackgroundColor: inlineChipBackground,
fileTextColor: markdownCodeText,
- skillBackgroundColor: inlineSkillBackground,
skillTextColor: inlineSkillForeground,
quoteMarkerColor: markdownBlockquoteBorder,
dividerColor: markdownHrColor,
@@ -676,7 +641,7 @@ function useMarkdownStyles(): MarkdownStyleSets {
},
},
};
- }, [colors, inlineChipBackground, inlineSkillBackground, inlineSkillForeground]);
+ }, [colors, inlineSkillForeground, onLinkPress]);
}
function renderFeedEntry(
@@ -692,11 +657,13 @@ function renderFeedEntry(
readonly onToggleWorkRow: (rowId: string) => void;
readonly onToggleTurnFold: (turnId: TurnId) => void;
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
+ readonly onMarkdownLinkPress: (href: string) => void;
readonly iconSubtleColor: string | import("react-native").ColorValue;
readonly userBubbleColor: string | import("react-native").ColorValue;
readonly markdownStyles: MarkdownStyleSets;
readonly reviewCommentColors: ReviewCommentColors;
readonly reviewCommentBubbleWidth: number;
+ readonly userBubbleMaxWidth: number;
},
) {
const entry = info.item;
@@ -745,9 +712,10 @@ function renderFeedEntry(
return (
<View className="mb-5 items-end">
<View
- className="max-w-[85%] gap-2 rounded-[20px] px-3.5 py-2.5"
+ className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
style={{
backgroundColor: userBubbleColor,
+ maxWidth: props.userBubbleMaxWidth,
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
}}
>
@@ -757,6 +725,7 @@ function renderFeedEntry(
markdownStyles={styles}
reviewCommentColors={props.reviewCommentColors}
skills={props.skills}
+ onLinkPress={props.onMarkdownLinkPress}
/>
) : null}
{attachments.map((attachment) => {
@@ -803,6 +772,7 @@ function renderFeedEntry(
markdown={message.text}
skills={props.skills}
textStyle={styles.nativeTextStyle}
+ onLinkPress={props.onMarkdownLinkPress}
/>
) : (
<Markdown
@@ -868,123 +838,17 @@ function renderFeedEntry(
);
}
- const rows = buildActivityRows(entry.activities).filter(
- (activity) => !(activity.toolLike && activity.status === "neutral"),
- );
- if (rows.length === 0) {
- return null;
- }
- const isExpanded = props.expandedWorkGroups[entry.id] ?? false;
- const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
- const visibleRows = hasOverflow && !isExpanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
- const hiddenCount = rows.length - visibleRows.length;
- const onlyToolRows = rows.every((row) => row.toolLike);
- const headerTitle = onlyToolRows
- ? rows.length === 1
- ? "1 tool call"
- : `${rows.length} tool calls`
- : "Work log";
-
return (
- <View className="mb-3 rounded-[16px] border border-neutral-300/70 bg-background px-2 py-2.5 dark:border-white/[0.1] dark:bg-white/[0.035]">
- <View className="mb-1.5 flex-row items-center justify-between gap-3 px-2">
- <Text className="font-t3-medium text-xs text-foreground">{headerTitle}</Text>
- {hasOverflow ? (
- <Pressable
- accessibilityRole="button"
- accessibilityState={{ expanded: isExpanded }}
- onPress={() => props.onToggleWorkGroup(entry.id)}
- className="flex-row items-center gap-1"
- >
- <Text className="font-t3-medium text-xs text-foreground-muted">
- {isExpanded ? "Show less" : `Show ${hiddenCount} more`}
- </Text>
- <SymbolView
- name={isExpanded ? "chevron.up" : "chevron.down"}
- size={12}
- tintColor={iconSubtleColor}
- type="monochrome"
- />
- </Pressable>
- ) : null}
- </View>
- {visibleRows.map((row, index) => (
- <Pressable
- key={row.id}
- accessibilityRole={row.fullDetail ? "button" : undefined}
- accessibilityState={
- row.fullDetail ? { expanded: props.expandedWorkRows[row.id] ?? false } : undefined
- }
- onPress={() => {
- if (row.fullDetail) {
- props.onToggleWorkRow(row.id);
- }
- }}
- onLongPress={() => props.onCopyWorkRow(row.id, row.copyText)}
- className={cn(
- "rounded-lg px-2 py-1.5",
- index > 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]",
- )}
- >
- <View className="flex-row items-center gap-2">
- <View className="w-4 items-center justify-center">
- <SymbolView
- name={
- row.status === "failure"
- ? "xmark"
- : row.status === "success"
- ? "checkmark"
- : row.status === "neutral"
- ? "minus"
- : "terminal"
- }
- size={row.status ? 11 : 13}
- tintColor={row.status === "failure" ? "#e11d48" : iconSubtleColor}
- type="monochrome"
- />
- </View>
- <Text
- className="min-w-0 flex-1 text-[12px] leading-[18px] text-neutral-700 dark:text-neutral-300"
- numberOfLines={props.expandedWorkRows[row.id] ? undefined : 1}
- >
- {row.detail ? `${row.summary} - ${row.detail}` : row.summary}
- </Text>
- {row.fullDetail ? (
- <SymbolView
- name={props.expandedWorkRows[row.id] ? "chevron.up" : "chevron.down"}
- size={11}
- tintColor={iconSubtleColor}
- type="monochrome"
- />
- ) : null}
- {props.copiedRowId === row.id ? (
- <Text className="shrink-0 font-t3-medium text-[10px] text-emerald-600 dark:text-emerald-400">
- Copied
- </Text>
- ) : null}
- </View>
- {row.fullDetail && props.expandedWorkRows[row.id] ? (
- <ScrollView
- horizontal
- nestedScrollEnabled
- directionalLockEnabled
- showsHorizontalScrollIndicator
- bounces={false}
- className="mt-2 rounded-lg bg-neutral-100 dark:bg-black/20"
- contentContainerStyle={{ paddingHorizontal: 10, paddingVertical: 8 }}
- >
- <Text
- selectable
- className="text-[11px] leading-[17px] text-neutral-600 dark:text-neutral-400"
- style={{ fontFamily: "ui-monospace" }}
- >
- {row.fullDetail}
- </Text>
- </ScrollView>
- ) : null}
- </Pressable>
- ))}
- </View>
+ <ThreadWorkLog
+ activities={entry.activities}
+ copiedRowId={props.copiedRowId}
+ expanded={props.expandedWorkGroups[entry.id] ?? false}
+ expandedRows={props.expandedWorkRows}
+ iconSubtleColor={iconSubtleColor}
+ onCopyRow={props.onCopyWorkRow}
+ onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
+ onToggleRow={props.onToggleWorkRow}
+ />
);
}
@@ -993,6 +857,7 @@ function UserMessageContent(props: {
readonly markdownStyles: MarkdownStyleSet;
readonly reviewCommentColors: ReviewCommentColors;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
+ readonly onLinkPress: (href: string) => void;
}) {
const segments = parseReviewCommentMessageSegments(props.text);
const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
@@ -1003,6 +868,8 @@ function UserMessageContent(props: {
markdown={props.text}
skills={props.skills}
textStyle={props.markdownStyles.nativeTextStyle}
+ preserveSoftBreaks
+ onLinkPress={props.onLinkPress}
/>
);
}
@@ -1042,6 +909,8 @@ function UserMessageContent(props: {
markdown={text}
skills={props.skills}
textStyle={props.markdownStyles.nativeTextStyle}
+ preserveSoftBreaks
+ onLinkPress={props.onLinkPress}
/>
) : (
<Markdown
@@ -1254,6 +1123,7 @@ function ThreadFeedPlaceholder(props: {
}
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
+ const router = useRouter();
const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const scrollFrameRef = useRef<number | null>(null);
@@ -1283,6 +1153,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
} | null>(null);
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 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;
@@ -1290,16 +1161,56 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const userBubbleColor = useThemeColor("--color-user-bubble");
- const markdownStyles = useMarkdownStyles();
+ const onMarkdownLinkPress = useCallback(
+ (href: string) => {
+ const presentation = resolveMarkdownLinkPresentation(href);
+ if (presentation.kind === "file") {
+ const relativePath = resolveWorkspaceRelativeFilePath(
+ props.workspaceRoot,
+ presentation.path,
+ );
+ if (relativePath) {
+ void Haptics.selectionAsync();
+ router.push(
+ buildThreadFilesNavigation(
+ { environmentId: props.environmentId, threadId: props.threadId },
+ relativePath,
+ presentation.line,
+ ),
+ );
+ }
+ return;
+ }
+
+ if (presentation.href) {
+ void Linking.openURL(presentation.href);
+ }
+ },
+ [props.environmentId, props.threadId, props.workspaceRoot, router],
+ );
+ const markdownStyles = useMarkdownStyles(onMarkdownLinkPress);
const reviewCommentColors = useReviewCommentColors();
+ // LegendList does not invalidate visible rows when only the renderItem closure changes.
+ // Keep row-local interaction props in extraData so disclosures and copy feedback repaint.
const listAppearanceData = useMemo(
() => ({
+ copiedRowId,
+ expandedWorkGroups,
+ expandedWorkRows,
iconSubtleColor,
markdownStyles,
reviewCommentColors,
userBubbleColor,
}),
- [iconSubtleColor, markdownStyles, reviewCommentColors, userBubbleColor],
+ [
+ copiedRowId,
+ expandedWorkGroups,
+ expandedWorkRows,
+ iconSubtleColor,
+ markdownStyles,
+ reviewCommentColors,
+ userBubbleColor,
+ ],
);
const presentedFeed = useMemo(
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
@@ -1490,11 +1401,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleWorkRow,
onToggleTurnFold,
onPressImage,
+ onMarkdownLinkPress,
iconSubtleColor,
userBubbleColor,
markdownStyles,
reviewCommentColors,
reviewCommentBubbleWidth,
+ userBubbleMaxWidth,
skills: props.skills,
}),
[
@@ -1508,7 +1421,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
markdownStyles,
reviewCommentColors,
reviewCommentBubbleWidth,
+ userBubbleMaxWidth,
onCopyWorkRow,
+ onMarkdownLinkPress,
onPressImage,
onToggleTurnFold,
onToggleWorkGroup,
diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx
index a66f20821..59b9af442 100644
--- a/apps/mobile/src/features/threads/ThreadGitControls.tsx
+++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx
@@ -14,7 +14,7 @@ import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback, useMemo } from "react";
import { Alert, Linking } from "react-native";
-import { buildThreadReviewRoutePath } from "../../lib/routes";
+import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
import {
basename,
getTerminalStatusLabel,
@@ -69,6 +69,7 @@ export function ThreadGitControls(props: {
readonly gitStatus: VcsStatusResult | null;
readonly gitOperationLabel: string | null;
readonly canOpenTerminal: boolean;
+ readonly canOpenFiles: boolean;
readonly projectScripts: ReadonlyArray<ProjectScript>;
readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
readonly onOpenTerminal: (terminalId?: string | null) => void;
@@ -259,6 +260,14 @@ export function ThreadGitControls(props: {
>
<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={() =>
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 6d0bd2307..51f5832f5 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -420,6 +420,7 @@ export function ThreadRouteScreen() {
gitStatus={gitStatus.data}
gitOperationLabel={gitState.gitOperationLabel}
canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
+ canOpenFiles={Boolean(selectedThreadProject?.workspaceRoot)}
projectScripts={selectedThreadProject?.scripts ?? []}
terminalSessions={terminalMenuSessions}
onOpenTerminal={handleOpenTerminal}
@@ -452,6 +453,7 @@ export function ThreadRouteScreen() {
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
+ threadCwd={selectedThreadCwd}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
onOpenDrawer={handleOpenDrawer}
onOpenConnectionEditor={handleOpenConnectionEditor}
diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx
new file mode 100644
index 000000000..244998eb3
--- /dev/null
+++ b/apps/mobile/src/features/threads/thread-work-log.tsx
@@ -0,0 +1,261 @@
+import * as Haptics from "expo-haptics";
+import { SymbolView, type SFSymbol } from "expo-symbols";
+import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
+
+import { AppText as Text } from "../../components/AppText";
+import { cn } from "../../lib/cn";
+import type { ThreadFeedActivity } from "../../lib/threadActivity";
+
+const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
+const WORK_LOG_LAYOUT_ANIMATION = {
+ duration: 180,
+ create: {
+ type: LayoutAnimation.Types.easeInEaseOut,
+ property: LayoutAnimation.Properties.opacity,
+ },
+ update: { type: LayoutAnimation.Types.easeInEaseOut },
+ delete: {
+ type: LayoutAnimation.Types.easeInEaseOut,
+ property: LayoutAnimation.Properties.opacity,
+ },
+} as const;
+
+function triggerDisclosureFeedback() {
+ LayoutAnimation.configureNext(WORK_LOG_LAYOUT_ANIMATION);
+ void Haptics.selectionAsync();
+}
+
+function stripShellWrapper(value: string): string {
+ const trimmed = value.trim();
+ const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
+ return (match?.[1] ?? trimmed).trim();
+}
+
+function compactActivityDetail(detail: string | null): string | null {
+ if (!detail) {
+ return null;
+ }
+
+ const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
+ return cleaned.length > 0 ? cleaned : null;
+}
+
+function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
+ switch (icon) {
+ case "agent":
+ return "sparkles";
+ case "alert":
+ return "exclamationmark.triangle";
+ case "check":
+ return "checkmark";
+ case "command":
+ return "terminal";
+ case "edit":
+ return "square.and.pencil";
+ case "eye":
+ return "eye";
+ case "globe":
+ return "globe";
+ case "hammer":
+ return "hammer";
+ case "message":
+ return "bubble.left";
+ case "warning":
+ return "xmark";
+ case "wrench":
+ return "wrench";
+ case "zap":
+ return "bolt";
+ }
+}
+
+export function ThreadWorkLog(props: {
+ readonly activities: ReadonlyArray<ThreadFeedActivity>;
+ readonly copiedRowId: string | null;
+ readonly expanded: boolean;
+ readonly expandedRows: Readonly<Record<string, boolean>>;
+ readonly iconSubtleColor: import("react-native").ColorValue;
+ readonly onCopyRow: (rowId: string, value: string) => void;
+ readonly onToggleGroup: () => void;
+ readonly onToggleRow: (rowId: string) => void;
+}) {
+ const colorScheme = useColorScheme();
+ const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
+ const rows = props.activities
+ .filter((activity) => !(activity.toolLike && activity.status === "neutral"))
+ .map((activity) => ({ ...activity, detail: compactActivityDetail(activity.detail) }));
+
+ if (rows.length === 0) {
+ return null;
+ }
+
+ const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
+ const visibleRows =
+ hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
+ const hiddenCount = rows.length - visibleRows.length;
+ const onlyToolRows = rows.every((row) => row.toolLike);
+
+ return (
+ <View className="-mx-1 mb-3 px-1 py-0.5">
+ {!onlyToolRows ? (
+ <Text className="px-0.5 pb-0.5 font-t3-medium text-[11px] text-foreground-muted opacity-60">
+ work log
+ </Text>
+ ) : null}
+
+ <View className="gap-px">
+ {visibleRows.map((row) => {
+ const expanded = props.expandedRows[row.id] ?? false;
+ const canExpand = row.fullDetail !== null;
+ const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
+ const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
+
+ return (
+ <View key={row.id}>
+ <Pressable
+ accessibilityRole={canExpand ? "button" : undefined}
+ accessibilityLabel={displayText}
+ accessibilityHint={
+ canExpand
+ ? "Double tap to show full details. Long press to copy."
+ : "Long press to copy."
+ }
+ accessibilityState={canExpand ? { expanded } : undefined}
+ hitSlop={4}
+ onPress={() => {
+ if (canExpand) {
+ triggerDisclosureFeedback();
+ props.onToggleRow(row.id);
+ }
+ }}
+ onLongPress={() => props.onCopyRow(row.id, row.copyText)}
+ style={({ pressed }) => ({
+ backgroundColor: pressed ? pressedBackground : "transparent",
+ })}
+ className="rounded-md px-0.5 py-0.5"
+ >
+ <View className="min-h-9 flex-row items-center gap-1.5">
+ <View className="h-5 w-5 shrink-0 items-center justify-center">
+ <SymbolView
+ name={workRowSymbolName(row.icon)}
+ size={14}
+ weight="medium"
+ tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
+ type="monochrome"
+ />
+ </View>
+
+ <Text
+ className="min-w-0 flex-1 text-xs leading-5 text-foreground"
+ numberOfLines={1}
+ >
+ <Text
+ className={cn(
+ "font-t3-medium text-foreground",
+ iconIsDestructive && "text-rose-600 dark:text-rose-400",
+ )}
+ >
+ {row.summary}
+ </Text>
+ {row.detail ? (
+ <Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
+ ) : null}
+ </Text>
+
+ <View className="shrink-0 flex-row items-center gap-px">
+ {props.copiedRowId === row.id ? (
+ <Text className="pr-1 font-t3-medium text-[10px] text-emerald-600 dark:text-emerald-400">
+ Copied
+ </Text>
+ ) : null}
+ <View className="h-4 w-4 items-center justify-center">
+ {canExpand ? (
+ <SymbolView
+ name={expanded ? "chevron.up" : "chevron.down"}
+ size={11}
+ tintColor={props.iconSubtleColor}
+ type="monochrome"
+ />
+ ) : null}
+ </View>
+ <View className="h-4 w-4 items-center justify-center">
+ {row.status ? (
+ <SymbolView
+ name={
+ row.status === "failure"
+ ? "xmark"
+ : row.status === "success"
+ ? "checkmark"
+ : "minus"
+ }
+ size={11}
+ tintColor={row.status === "failure" ? "#e11d48" : props.iconSubtleColor}
+ type="monochrome"
+ />
+ ) : null}
+ </View>
+ </View>
+ </View>
+ </Pressable>
+
+ {expanded && row.fullDetail ? (
+ <View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
+ <ScrollView
+ nestedScrollEnabled
+ directionalLockEnabled
+ showsVerticalScrollIndicator
+ style={{ maxHeight: 240 }}
+ contentContainerStyle={{ paddingRight: 8 }}
+ >
+ <Text
+ selectable
+ className="text-[11px] leading-[17px] text-foreground-muted"
+ style={{ fontFamily: "ui-monospace" }}
+ >
+ {row.fullDetail}
+ </Text>
+ </ScrollView>
+ </View>
+ ) : null}
+ </View>
+ );
+ })}
+ </View>
+
+ {hasOverflow ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ expanded: props.expanded }}
+ accessibilityLabel={
+ props.expanded
+ ? "Show fewer tool calls"
+ : `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
+ }
+ hitSlop={4}
+ onPress={() => {
+ triggerDisclosureFeedback();
+ props.onToggleGroup();
+ }}
+ style={({ pressed }) => ({
+ backgroundColor: pressed ? pressedBackground : "transparent",
+ })}
+ className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
+ >
+ <View className="h-5 w-5 items-center justify-center">
+ <SymbolView
+ name={props.expanded ? "chevron.up" : "chevron.down"}
+ size={13}
+ tintColor={props.iconSubtleColor}
+ type="monochrome"
+ />
+ </View>
+ <Text className="font-t3-medium text-xs text-foreground opacity-80">
+ {props.expanded
+ ? "Show fewer tool calls"
+ : `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
+ </Text>
+ </Pressable>
+ ) : null}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/lib/markdownLinks.test.ts b/apps/mobile/src/lib/markdownLinks.test.ts
index 90153d0af..ff57287b7 100644
--- a/apps/mobile/src/lib/markdownLinks.test.ts
+++ b/apps/mobile/src/lib/markdownLinks.test.ts
@@ -16,26 +16,47 @@ describe("resolveMarkdownLinkPresentation", () => {
resolveMarkdownLinkPresentation("file:///Users/julius/project/src/main.ts#L42C7"),
).toEqual({
kind: "file",
+ href: "file:///Users/julius/project/src/main.ts#L42C7",
icon: "typescript",
label: "main.ts:42:7",
+ path: "/Users/julius/project/src/main.ts",
+ line: 42,
+ column: 7,
});
});
it("recognizes relative source paths and bare filenames", () => {
expect(resolveMarkdownLinkPresentation("apps/mobile/src/index.ts:10")).toEqual({
kind: "file",
+ href: "apps/mobile/src/index.ts:10",
icon: "typescript",
label: "index.ts:10",
+ path: "apps/mobile/src/index.ts",
+ line: 10,
});
expect(resolveMarkdownLinkPresentation("AGENTS.md")).toEqual({
kind: "file",
+ href: "AGENTS.md",
icon: "agents",
label: "AGENTS.md",
+ path: "AGENTS.md",
});
expect(resolveMarkdownLinkPresentation("package.json")).toEqual({
kind: "file",
+ href: "package.json",
icon: "package",
label: "package.json",
+ path: "package.json",
+ });
+ });
+
+ it("extracts line fragments from relative file links", () => {
+ expect(resolveMarkdownLinkPresentation("src/main.ts#L18C2")).toMatchObject({
+ kind: "file",
+ path: "src/main.ts",
+ line: 18,
+ column: 2,
+ label: "main.ts:18:2",
});
});
diff --git a/apps/mobile/src/lib/nativeMarkdownText.test.ts b/apps/mobile/src/lib/nativeMarkdownText.test.ts
index 9d5c55686..6e41f2243 100644
--- a/apps/mobile/src/lib/nativeMarkdownText.test.ts
+++ b/apps/mobile/src/lib/nativeMarkdownText.test.ts
@@ -7,6 +7,7 @@ import {
nativeMarkdownDocumentRuns,
nativeMarkdownListItemBlocks,
nativeMarkdownTextRuns,
+ nativeMarkdownWithPreservedSoftBreaks,
} from "@t3tools/mobile-markdown-text/markdown";
describe("nativeMarkdownTextRuns", () => {
@@ -54,7 +55,11 @@ describe("nativeMarkdownTextRuns", () => {
externalHost: "example.com",
},
{ text: " " },
- { text: "README.md:12", fileIcon: "readme" },
+ {
+ text: "README.md:12",
+ href: "file:///repo/README.md#L12",
+ fileIcon: "readme",
+ },
]);
});
@@ -73,6 +78,21 @@ describe("nativeMarkdownTextRuns", () => {
expect(nativeMarkdownTextRuns(node)).toEqual([{ text: "first second\nthird" }]);
});
+ it("can preserve soft breaks for authored user messages", () => {
+ const node: MarkdownNode = {
+ type: "paragraph",
+ children: [
+ { type: "text", content: "first" },
+ { type: "soft_break" },
+ { type: "text", content: "second" },
+ ],
+ };
+
+ expect(nativeMarkdownTextRuns(nativeMarkdownWithPreservedSoftBreaks(node))).toEqual([
+ { text: "first\nsecond" },
+ ]);
+ });
+
it("normalizes common inline HTML and entities", () => {
const node: MarkdownNode = {
type: "paragraph",
@@ -130,7 +150,7 @@ describe("nativeMarkdownTextRuns", () => {
});
describe("nativeMarkdownDocumentRuns", () => {
- it("decorates known skill references as selectable skill chips", () => {
+ it("decorates known skill references as selectable skill links", () => {
const node: MarkdownNode = {
type: "document",
children: [
diff --git a/apps/mobile/src/lib/routes.test.ts b/apps/mobile/src/lib/routes.test.ts
new file mode 100644
index 000000000..773de9d84
--- /dev/null
+++ b/apps/mobile/src/lib/routes.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from "vite-plus/test";
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+
+import { buildThreadFilesNavigation, buildThreadFilesRoutePath } from "./routes";
+
+const thread = {
+ environmentId: EnvironmentId.make("environment-1"),
+ threadId: ThreadId.make("thread-1"),
+};
+
+describe("thread file routes", () => {
+ it("includes an optional source line in string routes", () => {
+ expect(buildThreadFilesRoutePath(thread, "src/main.ts", 42)).toBe(
+ "/threads/environment-1/thread-1/files/src/main.ts?line=42",
+ );
+ });
+
+ it("encodes each file path segment without encoding separators", () => {
+ expect(buildThreadFilesRoutePath(thread, "docs/My File#1.md")).toBe(
+ "/threads/environment-1/thread-1/files/docs/My%20File%231.md",
+ );
+ });
+
+ it("builds typed navigation params for a file and source line", () => {
+ expect(buildThreadFilesNavigation(thread, "src/main.ts", 42)).toEqual({
+ pathname: "/threads/[environmentId]/[threadId]/files/[...path]",
+ params: {
+ environmentId: "environment-1",
+ threadId: "thread-1",
+ path: ["src", "main.ts"],
+ line: "42",
+ },
+ });
+ });
+
+ it("targets the files index when no file path is provided", () => {
+ expect(buildThreadFilesNavigation(thread)).toEqual({
+ pathname: "/threads/[environmentId]/[threadId]/files",
+ params: {
+ environmentId: "environment-1",
+ threadId: "thread-1",
+ },
+ });
+ });
+});
diff --git a/apps/mobile/src/lib/routes.ts b/apps/mobile/src/lib/routes.ts
index 56d566321..3a33e2ee0 100644
--- a/apps/mobile/src/lib/routes.ts
+++ b/apps/mobile/src/lib/routes.ts
@@ -32,6 +32,27 @@ export function buildThreadReviewRoutePath(
return `${buildThreadRoutePath(input)}/review`;
}
+export function buildThreadFilesRoutePath(
+ input: ThreadRouteInput | PlainThreadRouteInput,
+ relativePath?: string | null,
+ line?: number | null,
+): string {
+ const basePath = `${buildThreadRoutePath(input)}/files`;
+ if (!relativePath) {
+ return basePath;
+ }
+
+ const pathSegments = relativePath.split("/").filter((segment) => segment.length > 0);
+ if (pathSegments.length === 0) {
+ return basePath;
+ }
+
+ const encodedPath = pathSegments.map(encodeURIComponent).join("/");
+ const lineParam =
+ Number.isFinite(line) && Number(line) > 0 ? `?line=${Math.floor(Number(line))}` : "";
+ return `${basePath}/${encodedPath}${lineParam}`;
+}
+
export function buildThreadTerminalRoutePath(
input: ThreadRouteInput | PlainThreadRouteInput,
terminalId?: string | null,
@@ -71,6 +92,38 @@ export function buildThreadTerminalNavigation(
};
}
+export function buildThreadFilesNavigation(
+ input: ThreadRouteInput | PlainThreadRouteInput,
+ relativePath?: string | null,
+ line?: number | null,
+): Href {
+ const environmentId = String(input.environmentId);
+ const threadId = String("threadId" in input ? input.threadId : input.id);
+ const path = relativePath?.split("/").filter((segment) => segment.length > 0) ?? [];
+
+ if (path.length === 0) {
+ return {
+ pathname: "/threads/[environmentId]/[threadId]/files",
+ params: { environmentId, threadId },
+ };
+ }
+
+ const params: {
+ environmentId: string;
+ threadId: string;
+ path: string[];
+ line?: string;
+ } = { environmentId, threadId, path };
+ if (Number.isFinite(line) && Number(line) > 0) {
+ params.line = String(Math.floor(Number(line)));
+ }
+
+ return {
+ pathname: "/threads/[environmentId]/[threadId]/files/[...path]",
+ params,
+ };
+}
+
export function dismissRoute(router: Router) {
if (router.canGoBack()) {
router.back();
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts
index b500752c5..f5d8f4bdf 100644
--- a/apps/mobile/src/lib/threadActivity.test.ts
+++ b/apps/mobile/src/lib/threadActivity.test.ts
@@ -161,14 +161,65 @@ describe("buildThreadFeed", () => {
turnId: "turn-1",
summary: "Run tests",
detail: "bun run test",
- fullDetail: null,
- copyText: "Run tests\nbun run test",
+ fullDetail: "/bin/zsh -lc 'bun run test'",
+ copyText: "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
+ icon: "command",
toolLike: true,
status: "success",
},
]);
});
+ it("keeps MCP inputs available to expanded mobile work rows", () => {
+ const turnId = TurnId.make("turn-mcp");
+ const thread = makeThread({
+ id: ThreadId.make("thread-mcp"),
+ projectId: ProjectId.make("project-1"),
+ title: "Expandable MCP call",
+ latestTurn: {
+ turnId,
+ state: "completed",
+ requestedAt: "2026-04-01T00:00:00.000Z",
+ startedAt: "2026-04-01T00:00:01.000Z",
+ completedAt: "2026-04-01T00:00:03.000Z",
+ assistantMessageId: null,
+ },
+ activities: [
+ makeActivity({
+ id: EventId.make("mcp-completed"),
+ kind: "tool.completed",
+ tone: "tool",
+ summary: "Call repository tool",
+ createdAt: "2026-04-01T00:00:02.000Z",
+ turnId,
+ payload: {
+ title: "Call repository tool",
+ itemType: "mcp_tool_call",
+ detail: "repository.search",
+ status: "completed",
+ data: {
+ item: {
+ server: "repository",
+ tool: "search",
+ arguments: { query: "work log" },
+ },
+ },
+ },
+ }),
+ ],
+ });
+
+ const group = buildThreadFeed(thread, [], null)[0];
+ expect(group).toMatchObject({ type: "activity-group" });
+ if (!group || group.type !== "activity-group") {
+ return;
+ }
+
+ expect(group.activities[0]?.icon).toBe("wrench");
+ expect(group.activities[0]?.fullDetail).toContain('"query": "work log"');
+ expect(group.activities[0]?.fullDetail).toContain("repository.search");
+ });
+
it("folds settled turn work while leaving the terminal answer visible", () => {
const turnId = TurnId.make("turn-1");
const thread = makeThread({
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index d6daa01d0..bef46e46e 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -40,6 +40,19 @@ export interface ThreadFeedActivity {
readonly detail: string | null;
readonly fullDetail: string | null;
readonly copyText: string;
+ readonly icon:
+ | "agent"
+ | "alert"
+ | "check"
+ | "command"
+ | "edit"
+ | "eye"
+ | "globe"
+ | "hammer"
+ | "message"
+ | "warning"
+ | "wrench"
+ | "zap";
readonly toolLike: boolean;
readonly status: "success" | "failure" | "neutral" | null;
}
@@ -60,6 +73,7 @@ interface WorkLogEntry {
itemType?: ToolLifecycleItemType;
requestKind?: PendingApproval["requestKind"];
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
+ toolData?: unknown;
}
interface DerivedWorkLogEntry extends WorkLogEntry {
@@ -214,7 +228,7 @@ function resolvePendingUserInputAnswer(
function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
-): WorkLogEntry[] {
+): DerivedWorkLogEntry[] {
const ordered = Arr.sort(activities, activityOrder);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
@@ -225,9 +239,7 @@ function deriveWorkLogEntries(
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
- return collapseDerivedWorkLogEntries(entries).map(
- ({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
- );
+ return collapseDerivedWorkLogEntries(entries);
}
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
@@ -301,6 +313,12 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
if (title) {
entry.toolTitle = title;
}
+ if (itemType === "mcp_tool_call") {
+ const data = asRecord(payload?.data);
+ if (data?.item !== undefined) {
+ entry.toolData = data.item;
+ }
+ }
if (itemType) {
entry.itemType = itemType;
}
@@ -365,6 +383,7 @@ function mergeDerivedWorkLogEntries(
const requestKind = next.requestKind ?? previous.requestKind;
const collapseKey = next.collapseKey ?? previous.collapseKey;
const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
+ const toolData = next.toolData ?? previous.toolData;
return {
...previous,
...next,
@@ -377,6 +396,7 @@ function mergeDerivedWorkLogEntries(
...(requestKind ? { requestKind } : {}),
...(collapseKey ? { collapseKey } : {}),
...(toolLifecycleStatus ? { toolLifecycleStatus } : {}),
+ ...(toolData !== undefined ? { toolData } : {}),
};
}
@@ -480,6 +500,52 @@ function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] {
return "neutral";
}
+function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
+ if (
+ entry.activityKind === "user-input.requested" ||
+ entry.activityKind === "user-input.resolved"
+ ) {
+ return "message";
+ }
+ if (entry.activityKind === "runtime.warning") return "warning";
+ if (entry.requestKind === "command") return "command";
+ if (entry.requestKind === "file-read") return "eye";
+ if (entry.requestKind === "file-change") return "edit";
+ if (entry.itemType === "command_execution" || entry.command) return "command";
+ if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
+ if (entry.itemType === "web_search") return "globe";
+ if (entry.itemType === "image_view") return "eye";
+ if (entry.itemType === "mcp_tool_call") return "wrench";
+ if (entry.itemType === "dynamic_tool_call" || entry.itemType === "collab_agent_tool_call") {
+ return "hammer";
+ }
+ if (entry.tone === "error") return "alert";
+ if (entry.tone === "thinking") return "agent";
+ if (entry.tone === "info") return "check";
+ return "zap";
+}
+
+function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
+ const blocks: string[] = [];
+ const appendUniqueBlock = (value: string | null | undefined) => {
+ const trimmed = value?.trim();
+ if (trimmed && !blocks.includes(trimmed)) {
+ blocks.push(trimmed);
+ }
+ };
+
+ if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) {
+ appendUniqueBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`);
+ }
+ appendUniqueBlock(entry.rawCommand ?? entry.command);
+ appendUniqueBlock(entry.detail);
+ if ((entry.changedFiles?.length ?? 0) > 0) {
+ appendUniqueBlock(entry.changedFiles!.join("\n"));
+ }
+
+ return blocks.length > 0 ? blocks.join("\n\n") : null;
+}
+
function workEntryPreview(
workEntry: Pick<WorkLogEntry, "detail" | "command" | "changedFiles">,
): string | null {
@@ -1226,11 +1292,7 @@ export function buildThreadFeed(
.map<RawThreadFeedEntry>((entry) => {
const summary = workEntryHeading(entry);
const detail = workEntryPreview(entry);
- const normalizedFullDetail = entry.detail
- ? unwrapKnownShellCommandWrapper(entry.detail)
- : null;
- const fullDetail =
- normalizedFullDetail && normalizedFullDetail !== detail ? normalizedFullDetail : null;
+ const fullDetail = buildWorkEntryExpandedBody(entry);
return {
type: "activity",
id: entry.id,
@@ -1243,6 +1305,7 @@ export function buildThreadFeed(
summary,
detail,
fullDetail,
+ icon: workEntryIcon(entry),
copyText: [summary, detail, fullDetail]
.filter((value, index, values): value is string => {
return Boolean(value) && values.indexOf(value) === index;
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index 9d431140d..29b1db251 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -89,6 +89,42 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
+ it.effect("issues exact workspace URLs for image previews", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-asset-image-workspace-",
+ });
+ const assetsDirectory = path.join(root, "assets");
+ const imagePath = path.join(assetsDirectory, "icon.png");
+ const siblingPath = path.join(assetsDirectory, "other.png");
+ yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
+ yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
+ yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
+ const canonicalImagePath = yield* fileSystem.realPath(imagePath);
+
+ const result = yield* issueAssetUrl({
+ resource: {
+ _tag: "workspace-file",
+ threadId: ThreadId.make("thread-1"),
+ path: imagePath,
+ },
+ workspaceRoot: root,
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separatorIndex = suffix.indexOf("/");
+ const token = suffix.slice(0, separatorIndex);
+
+ expect(yield* resolveAsset(token, "icon.png")).toEqual({
+ kind: "file",
+ path: canonicalImagePath,
+ });
+ expect(yield* resolveAsset(token, "other.png")).toBeNull();
+ expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
+ }).pipe(Effect.provide(testLayer)),
+ );
+
it.effect("issues exact attachment capabilities by attachment id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig;
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index 659413f47..ae5086e97 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -1,5 +1,11 @@
import type { AssetResource } from "@t3tools/contracts";
import { AssetAccessError } from "@t3tools/contracts";
+import {
+ isWorkspaceImagePreviewPath,
+ isWorkspacePreviewEntryPath,
+ WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
+ WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
+} from "@t3tools/shared/filePreview";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -24,22 +30,14 @@ export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
-const PREVIEWABLE_EXTENSIONS = new Set([".htm", ".html", ".pdf"]);
const PREVIEW_ASSET_EXTENSIONS = new Set([
- ...PREVIEWABLE_EXTENSIONS,
- ".avif",
+ ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
+ ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
".css",
- ".gif",
- ".ico",
- ".jpeg",
- ".jpg",
".js",
".mjs",
".otf",
- ".png",
- ".svg",
".ttf",
- ".webp",
".woff",
".woff2",
]);
@@ -52,6 +50,13 @@ const AssetClaimsSchema = Schema.Union([
baseRelativePath: Schema.String,
expiresAt: Schema.Number,
}),
+ Schema.Struct({
+ version: Schema.Literal(1),
+ kind: Schema.Literal("workspace-file-exact"),
+ workspaceRoot: Schema.String,
+ relativePath: Schema.String,
+ expiresAt: Schema.Number,
+ }),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment"),
@@ -144,8 +149,8 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
- if (!PREVIEWABLE_EXTENSIONS.has(path.extname(resolved.relativePath).toLowerCase())) {
- return yield* failAccess("Only HTML and PDF files can open in the browser.");
+ if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
+ return yield* failAccess("Only browser documents and images can be previewed.");
}
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot,
@@ -154,15 +159,24 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
if (!canonicalFile) {
return yield* failAccess("Workspace asset was not found.");
}
- claims = {
- version: 1,
- kind: "workspace-file",
- workspaceRoot: yield* fileSystem
- .realPath(workspaceRoot)
- .pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
- baseRelativePath: path.dirname(resolved.relativePath),
- expiresAt,
- };
+ const canonicalWorkspaceRoot = yield* fileSystem
+ .realPath(workspaceRoot)
+ .pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause)));
+ claims = isWorkspaceImagePreviewPath(resolved.relativePath)
+ ? {
+ version: 1,
+ kind: "workspace-file-exact",
+ workspaceRoot: canonicalWorkspaceRoot,
+ relativePath: resolved.relativePath,
+ expiresAt,
+ }
+ : {
+ version: 1,
+ kind: "workspace-file",
+ workspaceRoot: canonicalWorkspaceRoot,
+ baseRelativePath: path.dirname(resolved.relativePath),
+ expiresAt,
+ };
fileName = path.basename(resolved.relativePath);
break;
}
@@ -268,6 +282,16 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
const decodedPath = decodeRelativePath(relativePath);
if (decodedPath === null) return null;
const path = yield* Path.Path;
+ if (claims.kind === "workspace-file-exact") {
+ if (decodedPath !== path.basename(claims.relativePath)) return null;
+ const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFile({
+ workspaceRoot: claims.workspaceRoot,
+ relativePath: claims.relativePath,
+ });
+ return exactWorkspaceFile
+ ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
+ : null;
+ }
const segments = decodedPath.split(/[\\/]/);
if (
decodedPath.length === 0 ||
diff --git a/apps/web/src/AppRoot.test.tsx b/apps/web/src/AppRoot.test.tsx
new file mode 100644
index 000000000..9112e31cb
--- /dev/null
+++ b/apps/web/src/AppRoot.test.tsx
@@ -0,0 +1,22 @@
+import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
+import { RouterProvider } from "@tanstack/react-router";
+import { describe, expect, it } from "vite-plus/test";
+
+import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
+import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
+import type { AppRouter } from "./router";
+import { AppRoot } from "./AppRoot";
+
+describe("AppRoot", () => {
+ it("shares the application atom registry with routed UI and the Electron browser host", () => {
+ const root = AppRoot({ router: {} as AppRouter });
+
+ expect(root.type).toBe(AppAtomRegistryProvider);
+ const children = Children.toArray(
+ (root as ReactElement<{ readonly children: ReactNode }>).props.children,
+ );
+ expect(children).toHaveLength(2);
+ expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
+ expect(isValidElement(children[1]) && children[1].type).toBe(ElectronBrowserHost);
+ });
+});
diff --git a/apps/web/src/AppRoot.tsx b/apps/web/src/AppRoot.tsx
new file mode 100644
index 000000000..1ecb9f6b7
--- /dev/null
+++ b/apps/web/src/AppRoot.tsx
@@ -0,0 +1,19 @@
+import { RouterProvider } from "@tanstack/react-router";
+
+import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
+import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
+import type { AppRouter } from "./router";
+
+/**
+ * Owns renderer-wide providers. The Electron browser host intentionally sits
+ * outside the router so its webviews survive route transitions, but it must
+ * share the same atom registry as routed UI.
+ */
+export function AppRoot({ router }: { readonly router: AppRouter }) {
+ return (
+ <AppAtomRegistryProvider>
+ <RouterProvider router={router} />
+ <ElectronBrowserHost />
+ </AppAtomRegistryProvider>
+ );
+}
diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx
index 856654323..cdd33fa15 100644
--- a/apps/web/src/browser/HostedBrowserWebview.tsx
+++ b/apps/web/src/browser/HostedBrowserWebview.tsx
@@ -9,7 +9,7 @@ import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
import { useActiveBrowserRecordingTabId } from "./browserRecording";
import { useBrowserSurfaceStore } from "./browserSurfaceStore";
-import { acquireDesktopTab } from "./desktopTabLifetime";
+import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
interface ElectronWebview extends HTMLElement {
@@ -34,13 +34,21 @@ export function HostedBrowserWebview(props: {
const { threadRef, tabId, initialUrl } = props;
const config = usePreviewWebviewConfig(threadRef.environmentId);
const initialSrcRef = useRef(initialUrl ?? "about:blank");
+ const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
const webviewRef = useRef<ElectronWebview | null>(null);
const presentation = useBrowserSurfaceStore(useShallow((state) => state.byTabId[tabId] ?? null));
const recording = useActiveBrowserRecordingTabId() === tabId;
usePreviewBridge({ threadRef, tabId });
- useEffect(() => acquireDesktopTab(tabId), [tabId]);
+ useEffect(() => {
+ const lease = acquireDesktopTab(tabId);
+ tabLeaseRef.current = lease;
+ return () => {
+ if (tabLeaseRef.current === lease) tabLeaseRef.current = null;
+ lease.release();
+ };
+ }, [tabId]);
const setWebviewRef = useCallback((node: HTMLElement | null) => {
webviewRef.current = node as ElectronWebview | null;
@@ -51,19 +59,34 @@ export function HostedBrowserWebview(props: {
const webview = webviewRef.current;
const bridge = previewBridge;
if (!webview || !config || !bridge) return;
+ let disposed = false;
const register = () => {
- try {
- const webContentsId = webview.getWebContentsId();
- if (Number.isInteger(webContentsId) && webContentsId > 0) {
- void bridge.registerWebview(tabId, webContentsId);
+ const lease = tabLeaseRef.current;
+ if (!lease) return;
+ void (async () => {
+ try {
+ // The main-process tab and the DOM webview are created by separate
+ // effects. Wait for the former so registration cannot race and fail
+ // with PreviewTabNotFoundError on a fast about:blank attachment.
+ await lease.ready;
+ if (disposed || webviewRef.current !== webview) return;
+ const webContentsId = webview.getWebContentsId();
+ if (Number.isInteger(webContentsId) && webContentsId > 0) {
+ await bridge.registerWebview(tabId, webContentsId);
+ }
+ } catch {
+ // did-attach/dom-ready will retry if the guest was not ready yet.
}
- } catch {
- // A later dom-ready will retry registration.
- }
+ })();
};
+ webview.addEventListener("did-attach", register);
webview.addEventListener("dom-ready", register);
register();
- return () => webview.removeEventListener("dom-ready", register);
+ return () => {
+ disposed = true;
+ webview.removeEventListener("did-attach", register);
+ webview.removeEventListener("dom-ready", register);
+ };
}, [config, tabId]);
if (!config) return null;
diff --git a/apps/web/src/browser/desktopTabLifetime.test.ts b/apps/web/src/browser/desktopTabLifetime.test.ts
new file mode 100644
index 000000000..1e3b1632b
--- /dev/null
+++ b/apps/web/src/browser/desktopTabLifetime.test.ts
@@ -0,0 +1,45 @@
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const { closeTab, createTab } = vi.hoisted(() => ({
+ closeTab: vi.fn(async () => undefined),
+ createTab: vi.fn<() => Promise<void>>(),
+}));
+
+vi.mock("~/components/preview/previewBridge", () => ({
+ previewBridge: { closeTab, createTab },
+}));
+
+import { acquireDesktopTab } from "./desktopTabLifetime";
+
+describe("desktopTabLifetime", () => {
+ beforeEach(() => {
+ closeTab.mockClear();
+ createTab.mockClear();
+ });
+
+ it("shares tab creation readiness across concurrent leases", async () => {
+ let resolveCreation: (() => void) | undefined;
+ createTab.mockReturnValueOnce(
+ new Promise<void>((resolve) => {
+ resolveCreation = resolve;
+ }),
+ );
+
+ const first = acquireDesktopTab("tab_readiness");
+ const second = acquireDesktopTab("tab_readiness");
+
+ expect(createTab).toHaveBeenCalledOnce();
+ expect(first.ready).toBe(second.ready);
+
+ let ready = false;
+ void first.ready.then(() => {
+ ready = true;
+ });
+ await Promise.resolve();
+ expect(ready).toBe(false);
+
+ resolveCreation?.();
+ await first.ready;
+ expect(ready).toBe(true);
+ });
+});
diff --git a/apps/web/src/browser/desktopTabLifetime.ts b/apps/web/src/browser/desktopTabLifetime.ts
index 4254c7e6a..d621f6dc3 100644
--- a/apps/web/src/browser/desktopTabLifetime.ts
+++ b/apps/web/src/browser/desktopTabLifetime.ts
@@ -3,28 +3,42 @@ import { previewBridge } from "~/components/preview/previewBridge";
interface DesktopTabLease {
references: number;
closeTimer: number | null;
+ ready: Promise<void>;
}
const leases = new Map<string, DesktopTabLease>();
-export function acquireDesktopTab(tabId: string): () => void {
- const current = leases.get(tabId) ?? { references: 0, closeTimer: null };
+export interface AcquiredDesktopTab {
+ readonly ready: Promise<void>;
+ readonly release: () => void;
+}
+
+export function acquireDesktopTab(tabId: string): AcquiredDesktopTab {
+ const current =
+ leases.get(tabId) ??
+ ({
+ references: 0,
+ closeTimer: null,
+ ready: previewBridge?.createTab(tabId) ?? Promise.resolve(),
+ } satisfies DesktopTabLease);
if (current.closeTimer !== null) window.clearTimeout(current.closeTimer);
current.references += 1;
current.closeTimer = null;
leases.set(tabId, current);
- if (current.references === 1) void previewBridge?.createTab(tabId);
- return () => {
- const lease = leases.get(tabId);
- if (!lease) return;
- lease.references = Math.max(0, lease.references - 1);
- if (lease.references > 0) return;
- lease.closeTimer = window.setTimeout(() => {
- const latest = leases.get(tabId);
- if (!latest || latest.references > 0) return;
- leases.delete(tabId);
- void previewBridge?.closeTab(tabId);
- }, 0);
+ return {
+ ready: current.ready,
+ release: () => {
+ const lease = leases.get(tabId);
+ if (!lease) return;
+ lease.references = Math.max(0, lease.references - 1);
+ if (lease.references > 0) return;
+ lease.closeTimer = window.setTimeout(() => {
+ const latest = leases.get(tabId);
+ if (!latest || latest.references > 0) return;
+ leases.delete(tabId);
+ void previewBridge?.closeTab(tabId);
+ }, 0);
+ },
};
}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 90a6dcdc3..ea63b96f6 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -111,12 +111,12 @@ import {
useRightPanelStore,
} from "../rightPanelStore";
import {
- applyPreviewServerSnapshot,
isPreviewSupportedInRuntime,
- removePreviewSession,
setActivePreviewTab,
useThreadPreviewState,
} from "../previewStateStore";
+import { addBrowserSurface } from "./preview/addBrowserSurface";
+import { closePreviewSession } from "./preview/closePreviewSession";
import { subscribePreviewAction } from "./preview/previewActionBus";
import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic";
import { PreviewAutomationOwner } from "./preview/PreviewAutomationOwner";
@@ -2746,23 +2746,8 @@ function ChatViewContent(props: ChatViewProps) {
}, [activeThreadRef, dismissPlanSidebarForCurrentTurn]);
const createBrowserSurface = useCallback(() => {
if (!activeThreadRef) return;
- const activeTabId = activePreviewState.activeTabId;
- if (activeTabId) {
- useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);
- return;
- }
- void (async () => {
- const result = await openPreview({
- environmentId: activeThreadRef.environmentId,
- input: { threadId: activeThreadRef.threadId },
- });
- if (result._tag === "Failure") {
- return;
- }
- applyPreviewServerSnapshot(activeThreadRef, result.value);
- useRightPanelStore.getState().openBrowser(activeThreadRef, result.value.tabId);
- })();
- }, [activePreviewState.activeTabId, activeThreadRef, openPreview]);
+ void addBrowserSurface({ threadRef: activeThreadRef, openPreview });
+ }, [activeThreadRef, openPreview]);
const addDiffSurface = useCallback(() => {
if (!activeThreadRef || !isServerThread || !isGitRepo) return;
useRightPanelStore.getState().open(activeThreadRef, "diff");
@@ -2807,8 +2792,14 @@ function ChatViewContent(props: ChatViewProps) {
search: (previous) => ({ ...stripDiffSearchParams(previous), diff: undefined }),
});
}
- createBrowserSurface();
+ const activeTabId = activePreviewState.activeTabId;
+ if (activeTabId) {
+ useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);
+ } else {
+ createBrowserSurface();
+ }
}, [
+ activePreviewState.activeTabId,
activeThreadRef,
createBrowserSurface,
diffOpen,
@@ -2993,10 +2984,11 @@ function ChatViewContent(props: ChatViewProps) {
for (const surface of surfaces) {
if (surface.kind === "preview" && surface.resourceId) {
- removePreviewSession(activeThreadRef, surface.resourceId);
- void closePreview({
- environmentId: activeThreadRef.environmentId,
- input: { threadId: activeThreadRef.threadId, tabId: surface.resourceId },
+ void closePreviewSession({
+ closePreview,
+ snapshot: activePreviewState.sessions[surface.resourceId] ?? null,
+ tabId: surface.resourceId,
+ threadRef: activeThreadRef,
});
}
if (surface.kind === "terminal") {
@@ -3020,6 +3012,7 @@ function ChatViewContent(props: ChatViewProps) {
},
[
activeThreadRef,
+ activePreviewState.sessions,
closePreview,
closeTerminalMutation,
diffOpen,
diff --git a/apps/web/src/components/preview/addBrowserSurface.test.ts b/apps/web/src/components/preview/addBrowserSurface.test.ts
new file mode 100644
index 000000000..5dfc1a42e
--- /dev/null
+++ b/apps/web/src/components/preview/addBrowserSurface.test.ts
@@ -0,0 +1,52 @@
+import type { PreviewOpenInput, PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
+import { AsyncResult } from "effect/unstable/reactivity";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import {
+ applyPreviewServerSnapshot,
+ readThreadPreviewState,
+ resetPreviewStateForTests,
+} from "~/previewStateStore";
+import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore";
+
+import { addBrowserSurface } from "./addBrowserSurface";
+
+const threadRef = {
+ environmentId: "local" as ScopedThreadRef["environmentId"],
+ threadId: "thread-1" as ScopedThreadRef["threadId"],
+};
+
+const snapshot = (tabId: string): PreviewSessionSnapshot => ({
+ threadId: threadRef.threadId,
+ tabId,
+ navStatus: { _tag: "Idle" },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: `2026-06-18T19:00:0${tabId.at(-1) ?? "0"}.000Z`,
+});
+
+beforeEach(() => {
+ resetPreviewStateForTests();
+ useRightPanelStore.setState({ byThreadKey: {} });
+});
+
+describe("addBrowserSurface", () => {
+ it("creates another preview session when a browser tab is already active", async () => {
+ const first = snapshot("tab-1");
+ const second = snapshot("tab-2");
+ applyPreviewServerSnapshot(threadRef, first);
+ useRightPanelStore.getState().openBrowser(threadRef, first.tabId);
+ const openPreview = vi.fn(async (_input: PreviewOpenInput) => AsyncResult.success(second));
+
+ await addBrowserSurface({ threadRef, openPreview: ({ input }) => openPreview(input) });
+
+ expect(openPreview).toHaveBeenCalledWith({ threadId: "thread-1" });
+ expect(Object.keys(readThreadPreviewState(threadRef).sessions)).toEqual(["tab-1", "tab-2"]);
+ expect(
+ selectThreadRightPanelState(
+ useRightPanelStore.getState().byThreadKey,
+ threadRef,
+ ).surfaces.map((surface) => surface.id),
+ ).toEqual(["browser:tab-1", "browser:tab-2"]);
+ });
+});
diff --git a/apps/web/src/components/preview/addBrowserSurface.ts b/apps/web/src/components/preview/addBrowserSurface.ts
new file mode 100644
index 000000000..4eecac695
--- /dev/null
+++ b/apps/web/src/components/preview/addBrowserSurface.ts
@@ -0,0 +1,24 @@
+import {
+ mapAtomCommandResult,
+ type AtomCommandResult,
+} from "@t3tools/client-runtime/state/runtime";
+import type { ScopedThreadRef } from "@t3tools/contracts";
+
+import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
+import { useRightPanelStore } from "~/rightPanelStore";
+
+import { openPreviewSession } from "./openPreviewSession";
+
+/** Creates a new browser tab. Reopening an existing tab is a separate UI action. */
+export async function addBrowserSurface<E>(input: {
+ readonly threadRef: ScopedThreadRef;
+ readonly openPreview: OpenPreviewMutation<E>;
+}): Promise<AtomCommandResult<void, E>> {
+ const result = await openPreviewSession({
+ openPreview: input.openPreview,
+ threadRef: input.threadRef,
+ });
+ return mapAtomCommandResult(result, (snapshot) => {
+ useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
+ });
+}
diff --git a/apps/web/src/components/preview/closePreviewSession.test.ts b/apps/web/src/components/preview/closePreviewSession.test.ts
new file mode 100644
index 000000000..d61d2975a
--- /dev/null
+++ b/apps/web/src/components/preview/closePreviewSession.test.ts
@@ -0,0 +1,79 @@
+import type {
+ PreviewCloseInput,
+ PreviewSessionSnapshot,
+ ScopedThreadRef,
+} from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import { AsyncResult } from "effect/unstable/reactivity";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import {
+ applyPreviewServerSnapshot,
+ readThreadPreviewState,
+ resetPreviewStateForTests,
+} from "~/previewStateStore";
+
+import { closePreviewSession } from "./closePreviewSession";
+
+const threadRef = {
+ environmentId: "local" as ScopedThreadRef["environmentId"],
+ threadId: "thread-1" as ScopedThreadRef["threadId"],
+};
+
+const snapshot: PreviewSessionSnapshot = {
+ threadId: threadRef.threadId,
+ tabId: "tab-1",
+ navStatus: {
+ _tag: "Success",
+ url: "http://localhost:3000/",
+ title: "Local app",
+ },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: "2026-06-18T19:00:00.000Z",
+};
+
+beforeEach(resetPreviewStateForTests);
+
+describe("closePreviewSession", () => {
+ it("suppresses stale server snapshots while the close is in flight", async () => {
+ applyPreviewServerSnapshot(threadRef, snapshot);
+ let finishClose: (() => void) | undefined;
+ const closePreview = vi.fn(
+ (_input: PreviewCloseInput) =>
+ new Promise<ReturnType<typeof AsyncResult.success<void>>>((resolve) => {
+ finishClose = () => resolve(AsyncResult.success(undefined));
+ }),
+ );
+
+ const closing = closePreviewSession({
+ closePreview: ({ input }) => closePreview(input),
+ snapshot,
+ tabId: snapshot.tabId,
+ threadRef,
+ });
+
+ expect(readThreadPreviewState(threadRef).sessions).toEqual({});
+ applyPreviewServerSnapshot(threadRef, snapshot);
+ expect(readThreadPreviewState(threadRef).sessions).toEqual({});
+
+ finishClose?.();
+ await closing;
+ expect(closePreview).toHaveBeenCalledWith({ threadId: "thread-1", tabId: "tab-1" });
+ });
+
+ it("restores the last snapshot when the server close fails", async () => {
+ applyPreviewServerSnapshot(threadRef, snapshot);
+
+ const result = await closePreviewSession({
+ closePreview: async () => AsyncResult.failure(Cause.fail(new Error("close failed"))),
+ snapshot,
+ tabId: snapshot.tabId,
+ threadRef,
+ });
+
+ expect(result._tag).toBe("Failure");
+ expect(readThreadPreviewState(threadRef).snapshot).toEqual(snapshot);
+ expect(readThreadPreviewState(threadRef).sessions).toEqual({ [snapshot.tabId]: snapshot });
+ });
+});
diff --git a/apps/web/src/components/preview/closePreviewSession.ts b/apps/web/src/components/preview/closePreviewSession.ts
new file mode 100644
index 000000000..5073029f6
--- /dev/null
+++ b/apps/web/src/components/preview/closePreviewSession.ts
@@ -0,0 +1,37 @@
+import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
+import type {
+ EnvironmentId,
+ PreviewCloseInput,
+ PreviewSessionSnapshot,
+ ScopedThreadRef,
+} from "@t3tools/contracts";
+
+import { beginPreviewSessionClose, cancelPreviewSessionClose } from "~/previewStateStore";
+
+interface ClosePreviewSessionInput<E> {
+ readonly closePreview: (input: {
+ readonly environmentId: EnvironmentId;
+ readonly input: PreviewCloseInput;
+ }) => Promise<AtomCommandResult<void, E>>;
+ readonly snapshot: PreviewSessionSnapshot | null;
+ readonly tabId: string;
+ readonly threadRef: ScopedThreadRef;
+}
+
+/**
+ * Optimistically closes a preview while suppressing stale list responses for
+ * the same tab. A failed close restores the last known snapshot.
+ */
+export async function closePreviewSession<E>(
+ input: ClosePreviewSessionInput<E>,
+): Promise<AtomCommandResult<void, E>> {
+ beginPreviewSessionClose(input.threadRef, input.tabId);
+ const result = await input.closePreview({
+ environmentId: input.threadRef.environmentId,
+ input: { threadId: input.threadRef.threadId, tabId: input.tabId },
+ });
+ if (result._tag === "Failure") {
+ cancelPreviewSessionClose(input.threadRef, input.snapshot, input.tabId);
+ }
+ return result;
+}
diff --git a/apps/web/src/components/preview/openPreviewSession.test.ts b/apps/web/src/components/preview/openPreviewSession.test.ts
index 81db47c4e..2e84fec5e 100644
--- a/apps/web/src/components/preview/openPreviewSession.test.ts
+++ b/apps/web/src/components/preview/openPreviewSession.test.ts
@@ -28,6 +28,24 @@ const snapshot: PreviewSessionSnapshot = {
beforeEach(resetPreviewStateForTests);
describe("openPreviewSession", () => {
+ it("creates an idle tab without recording a recently visited URL", async () => {
+ const idleSnapshot: PreviewSessionSnapshot = {
+ ...snapshot,
+ tabId: "tab-blank",
+ navStatus: { _tag: "Idle" },
+ };
+ const open = vi.fn(async (_input: PreviewOpenInput) => AsyncResult.success(idleSnapshot));
+
+ await openPreviewSession({
+ openPreview: ({ input }) => open(input),
+ threadRef,
+ });
+
+ expect(open).toHaveBeenCalledWith({ threadId: "thread-1" });
+ expect(readThreadPreviewState(threadRef).snapshot).toEqual(idleSnapshot);
+ expect(readThreadPreviewState(threadRef).recentlySeenUrls).toEqual([]);
+ });
+
it("applies the RPC response without waiting for a preview event", async () => {
const open = vi.fn(async (_input: PreviewOpenInput) => AsyncResult.success(snapshot));
diff --git a/apps/web/src/components/preview/openPreviewSession.ts b/apps/web/src/components/preview/openPreviewSession.ts
index 1fd11bb58..f86ea31a1 100644
--- a/apps/web/src/components/preview/openPreviewSession.ts
+++ b/apps/web/src/components/preview/openPreviewSession.ts
@@ -14,7 +14,7 @@ interface OpenPreviewSessionInput<E> {
readonly input: PreviewOpenInput;
}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
threadRef: ScopedThreadRef;
- url: string;
+ url?: string;
}
export async function openPreviewSession<E>(
@@ -24,7 +24,7 @@ export async function openPreviewSession<E>(
environmentId: input.threadRef.environmentId,
input: {
threadId: input.threadRef.threadId,
- url: input.url,
+ ...(input.url === undefined ? {} : { url: input.url }),
},
});
if (result._tag === "Failure") {
@@ -32,9 +32,11 @@ export async function openPreviewSession<E>(
}
const snapshot = result.value;
applyPreviewServerSnapshot(input.threadRef, snapshot);
- rememberPreviewUrl(
- input.threadRef,
- snapshot.navStatus._tag === "Idle" ? input.url : snapshot.navStatus.url,
- );
+ if (input.url !== undefined) {
+ rememberPreviewUrl(
+ input.threadRef,
+ snapshot.navStatus._tag === "Idle" ? input.url : snapshot.navStatus.url,
+ );
+ }
return result;
}
diff --git a/apps/web/src/lib/archivedThreadsState.ts b/apps/web/src/lib/archivedThreadsState.ts
index b39123e0e..2d52383c0 100644
--- a/apps/web/src/lib/archivedThreadsState.ts
+++ b/apps/web/src/lib/archivedThreadsState.ts
@@ -1,53 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import {
type ArchivedSnapshotEntry,
+ createArchivedThreadSnapshotsAtomFamily,
makeArchivedThreadsEnvironmentKey,
- parseArchivedThreadsEnvironmentKey,
} from "@t3tools/client-runtime/state/threads";
import type { EnvironmentId } from "@t3tools/contracts";
-import * as Cause from "effect/Cause";
-import * as Option from "effect/Option";
-import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import { orchestrationEnvironment } from "../state/orchestration";
import { appAtomRegistry } from "../rpc/atomRegistry";
-const archivedSnapshotsAtom = Atom.family((environmentKey: string) =>
- Atom.make((get) => {
- const snapshots: ArchivedSnapshotEntry[] = [];
- let error: string | null = null;
- let isLoading = false;
-
- for (const environmentId of parseArchivedThreadsEnvironmentKey(environmentKey)) {
- const result = get(
- orchestrationEnvironment.archivedShellSnapshot({
- environmentId,
- input: {},
- }),
- );
- isLoading ||= result.waiting;
- const snapshot = Option.getOrNull(AsyncResult.value(result));
- if (snapshot !== null) {
- snapshots.push({ environmentId, snapshot });
- }
- if (error === null && result._tag === "Failure") {
- const cause = Cause.squash(result.cause);
- error =
- cause instanceof Error && cause.message.trim().length > 0
- ? cause.message
- : "Failed to load archived threads.";
- }
- }
-
- return {
- snapshots,
- error,
- isLoading,
- };
- }).pipe(Atom.withLabel(`web:archived-thread-snapshots:${environmentKey}`)),
-);
-
function archivedSnapshotAtom(environmentId: EnvironmentId) {
return orchestrationEnvironment.archivedShellSnapshot({
environmentId,
@@ -55,6 +17,11 @@ function archivedSnapshotAtom(environmentId: EnvironmentId) {
});
}
+const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
+ getSnapshotAtom: archivedSnapshotAtom,
+ labelPrefix: "web:archived-thread-snapshots",
+});
+
export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
}
diff --git a/apps/web/src/lib/threadSort.ts b/apps/web/src/lib/threadSort.ts
index 9dc31cbbc..ac3dea3ac 100644
--- a/apps/web/src/lib/threadSort.ts
+++ b/apps/web/src/lib/threadSort.ts
@@ -1,86 +1,7 @@
-import type { ProjectId } from "@t3tools/contracts";
-import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
-import type { Thread } from "../types";
-
-export type ThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
- latestUserMessageAt?: string | null;
- messages?: ReadonlyArray<Pick<Thread["messages"][number], "createdAt" | "role">>;
-};
-
-export function toSortableTimestamp(iso: string | undefined): number | null {
- if (!iso) return null;
- const ms = Date.parse(iso);
- return Number.isFinite(ms) ? ms : null;
-}
-
-function getFirstSortableTimestamp(...values: Array<string | null | undefined>): number | null {
- for (const value of values) {
- const timestamp = toSortableTimestamp(value ?? undefined);
- if (timestamp !== null) {
- return timestamp;
- }
- }
-
- return null;
-}
-
-function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
- if (thread.latestUserMessageAt) {
- return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
- }
-
- let latestUserMessageTimestamp: number | null = null;
-
- for (const message of thread.messages ?? []) {
- if (message.role !== "user") continue;
- const messageTimestamp = toSortableTimestamp(message.createdAt);
- if (messageTimestamp === null) continue;
- latestUserMessageTimestamp =
- latestUserMessageTimestamp === null
- ? messageTimestamp
- : Math.max(latestUserMessageTimestamp, messageTimestamp);
- }
-
- if (latestUserMessageTimestamp !== null) {
- return latestUserMessageTimestamp;
- }
-
- return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY;
-}
-
-export function getThreadSortTimestamp(
- thread: ThreadSortInput,
- sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
-): number {
- if (sortOrder === "created_at") {
- return (
- getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY
- );
- }
- return getLatestUserMessageTimestamp(thread);
-}
-
-export function sortThreads<T extends Pick<Thread, "id"> & ThreadSortInput>(
- threads: readonly T[],
- sortOrder: SidebarThreadSortOrder,
-): T[] {
- return threads.toSorted((left, right) => {
- const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
- const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
- const byTimestamp =
- rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
- if (byTimestamp !== 0) return byTimestamp;
- return right.id.localeCompare(left.id);
- });
-}
-
-export function getLatestThreadForProject<
- T extends Pick<Thread, "id" | "projectId" | "archivedAt"> & ThreadSortInput,
->(threads: readonly T[], projectId: ProjectId, sortOrder: SidebarThreadSortOrder): T | null {
- return (
- sortThreads(
- threads.filter((thread) => thread.projectId === projectId && thread.archivedAt === null),
- sortOrder,
- )[0] ?? null
- );
-}
+export {
+ getLatestThreadForProject,
+ getThreadSortTimestamp,
+ sortThreads,
+ toSortableTimestamp,
+ type ThreadSortInput,
+} from "@t3tools/client-runtime/state/thread-sort";
diff --git a/apps/web/src/logicalProject.ts b/apps/web/src/logicalProject.ts
index f9040dae9..8204222b3 100644
--- a/apps/web/src/logicalProject.ts
+++ b/apps/web/src/logicalProject.ts
@@ -1,184 +1,14 @@
-import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
-import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
-import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
-import type { UnifiedSettings } from "@t3tools/contracts/settings";
-import { normalizeProjectPathForComparison } from "./lib/projectPaths";
-
-export interface ProjectGroupingSettings {
- sidebarProjectGroupingMode: SidebarProjectGroupingMode;
- sidebarProjectGroupingOverrides: Record<string, SidebarProjectGroupingMode>;
-}
-
-export type ProjectGroupingMode = SidebarProjectGroupingMode;
-
-export function selectProjectGroupingSettings(settings: UnifiedSettings): ProjectGroupingSettings {
- return {
- sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
- sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
- };
-}
-
-function uniqueNonEmptyValues(values: ReadonlyArray<string | null | undefined>): string[] {
- const seen = new Set<string>();
- const unique: string[] = [];
- for (const value of values) {
- const trimmed = value?.trim();
- if (!trimmed || seen.has(trimmed)) {
- continue;
- }
- seen.add(trimmed);
- unique.push(trimmed);
- }
- return unique;
-}
-
-function deriveRepositoryRelativeProjectPath(
- project: Pick<EnvironmentProject, "workspaceRoot" | "repositoryIdentity">,
-): string | null {
- const rootPath = project.repositoryIdentity?.rootPath?.trim();
- if (!rootPath) {
- return null;
- }
-
- const normalizedProjectPath = normalizeProjectPathForComparison(project.workspaceRoot);
- const normalizedRootPath = normalizeProjectPathForComparison(rootPath);
- if (normalizedProjectPath.length === 0 || normalizedRootPath.length === 0) {
- return null;
- }
-
- if (normalizedProjectPath === normalizedRootPath) {
- return "";
- }
-
- const separator = normalizedRootPath.includes("\\") ? "\\" : "/";
- const rootPrefix = `${normalizedRootPath}${separator}`;
- if (!normalizedProjectPath.startsWith(rootPrefix)) {
- return null;
- }
-
- return normalizedProjectPath.slice(rootPrefix.length).replaceAll("\\", "/");
-}
-
-export function derivePhysicalProjectKeyFromPath(environmentId: string, cwd: string): string {
- return `${environmentId}:${normalizeProjectPathForComparison(cwd)}`;
-}
-
-export function derivePhysicalProjectKey(
- project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
-): string {
- return derivePhysicalProjectKeyFromPath(project.environmentId, project.workspaceRoot);
-}
-
-export function deriveProjectGroupingOverrideKey(
- project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
-): string {
- return derivePhysicalProjectKey(project);
-}
-
-// Key under which a project's manual sort order (projectOrder) is stored.
-// Must stay aligned with the drag handlers and readers in `Sidebar`.
-export function getProjectOrderKey(
- project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
-): string {
- return derivePhysicalProjectKey(project);
-}
-
-export function resolveProjectGroupingMode(
- project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
- settings: ProjectGroupingSettings,
-): SidebarProjectGroupingMode {
- return (
- settings.sidebarProjectGroupingOverrides?.[deriveProjectGroupingOverrideKey(project)] ??
- settings.sidebarProjectGroupingMode
- );
-}
-
-function deriveRepositoryScopedKey(
- project: Pick<EnvironmentProject, "workspaceRoot" | "repositoryIdentity">,
- groupingMode: SidebarProjectGroupingMode,
-): string | null {
- const canonicalKey = project.repositoryIdentity?.canonicalKey;
- if (!canonicalKey) {
- return null;
- }
-
- if (groupingMode === "repository") {
- return canonicalKey;
- }
-
- const relativeProjectPath = deriveRepositoryRelativeProjectPath(project);
- if (relativeProjectPath === null) {
- return canonicalKey;
- }
-
- return relativeProjectPath.length === 0
- ? canonicalKey
- : `${canonicalKey}::${relativeProjectPath}`;
-}
-
-export function deriveLogicalProjectKey(
- project: Pick<
- EnvironmentProject,
- "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity"
- >,
- options?: {
- groupingMode?: SidebarProjectGroupingMode;
- },
-): string {
- const groupingMode = options?.groupingMode ?? "repository";
- if (groupingMode === "separate") {
- return derivePhysicalProjectKey(project);
- }
-
- return (
- deriveRepositoryScopedKey(project, groupingMode) ??
- derivePhysicalProjectKey(project) ??
- scopedProjectKey(scopeProjectRef(project.environmentId, project.id))
- );
-}
-
-export function deriveLogicalProjectKeyFromSettings(
- project: Pick<
- EnvironmentProject,
- "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity"
- >,
- settings: ProjectGroupingSettings,
-): string {
- return deriveLogicalProjectKey(project, {
- groupingMode: resolveProjectGroupingMode(project, settings),
- });
-}
-
-export function deriveLogicalProjectKeyFromRef(
- projectRef: ScopedProjectRef,
- project:
- | Pick<EnvironmentProject, "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity">
- | null
- | undefined,
- options?: {
- groupingMode?: SidebarProjectGroupingMode;
- },
-): string {
- return project ? deriveLogicalProjectKey(project, options) : scopedProjectKey(projectRef);
-}
-
-export function deriveProjectGroupLabel(input: {
- representative: Pick<EnvironmentProject, "title" | "repositoryIdentity">;
- members: ReadonlyArray<Pick<EnvironmentProject, "title" | "repositoryIdentity">>;
-}): string {
- const sharedDisplayNames = uniqueNonEmptyValues(
- input.members.map((member) => member.repositoryIdentity?.displayName),
- );
- if (sharedDisplayNames.length === 1) {
- return sharedDisplayNames[0]!;
- }
-
- const sharedRepositoryNames = uniqueNonEmptyValues(
- input.members.map((member) => member.repositoryIdentity?.name),
- );
- if (sharedRepositoryNames.length === 1) {
- return sharedRepositoryNames[0]!;
- }
-
- return input.representative.title;
-}
+export {
+ deriveLogicalProjectKey,
+ deriveLogicalProjectKeyFromRef,
+ deriveLogicalProjectKeyFromSettings,
+ derivePhysicalProjectKey,
+ derivePhysicalProjectKeyFromPath,
+ deriveProjectGroupLabel,
+ deriveProjectGroupingOverrideKey,
+ getProjectOrderKey,
+ resolveProjectGroupingMode,
+ selectProjectGroupingSettings,
+ type ProjectGroupingMode,
+ type ProjectGroupingSettings,
+} from "@t3tools/client-runtime/state/project-grouping";
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index 8d56b6877..7d56d572f 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -1,7 +1,6 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { ClerkProvider } from "@clerk/react";
-import { RouterProvider } from "@tanstack/react-router";
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
import "@fontsource-variable/dm-sans/index.css";
@@ -17,7 +16,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig";
import { getRouter } from "./router";
import { APP_DISPLAY_NAME } from "./branding";
import { syncDocumentWindowControlsOverlayClass } from "./lib/windowControlsOverlay";
-import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
+import { AppRoot } from "./AppRoot";
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
const history = isElectron ? createHashHistory() : createBrowserHistory();
@@ -32,12 +31,7 @@ document.title = APP_DISPLAY_NAME;
const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;
-const app = (
- <>
- <RouterProvider router={router} />
- <ElectronBrowserHost />
- </>
-);
+const app = <AppRoot router={router} />;
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
diff --git a/apps/web/src/previewStateStore.test.ts b/apps/web/src/previewStateStore.test.ts
index 458bfb5e5..d2bf2e7c2 100644
--- a/apps/web/src/previewStateStore.test.ts
+++ b/apps/web/src/previewStateStore.test.ts
@@ -7,10 +7,11 @@ import {
applyPreviewDesktopState,
applyPreviewServerEvent,
applyPreviewServerSnapshot,
+ beginPreviewSessionClose,
+ cancelPreviewSessionClose,
previewStateAtom,
readThreadPreviewState,
rememberPreviewUrl,
- removePreviewSession,
removePreviewThread,
resetPreviewStateForTests,
setActivePreviewTab,
@@ -182,7 +183,7 @@ describe("previewStateStore (single-tab)", () => {
applyPreviewServerSnapshot(ref, first);
applyPreviewServerSnapshot(ref, second);
- removePreviewSession(ref, second.tabId);
+ beginPreviewSessionClose(ref, second.tabId);
const state = readThreadPreviewState(ref);
expect(Object.keys(state.sessions)).toEqual([first.tabId]);
@@ -193,7 +194,7 @@ describe("previewStateStore (single-tab)", () => {
it("treats a late server close event after optimistic removal as a no-op", () => {
const snapshot = makeSnapshot();
applyPreviewServerSnapshot(ref, snapshot);
- removePreviewSession(ref, snapshot.tabId);
+ beginPreviewSessionClose(ref, snapshot.tabId);
applyPreviewServerEvent(ref, {
type: "closed",
@@ -207,6 +208,30 @@ describe("previewStateStore (single-tab)", () => {
expect(state.snapshot).toBeNull();
});
+ it("does not resurrect an intentionally closed tab from a stale list snapshot", () => {
+ const snapshot = makeSnapshot();
+ applyPreviewServerSnapshot(ref, snapshot);
+ beginPreviewSessionClose(ref, snapshot.tabId);
+
+ applyPreviewServerSnapshot(ref, snapshot);
+
+ const state = readThreadPreviewState(ref);
+ expect(state.sessions).toEqual({});
+ expect(state.snapshot).toBeNull();
+ });
+
+ it("can restore a suppressed tab after a failed close", () => {
+ const snapshot = makeSnapshot();
+ applyPreviewServerSnapshot(ref, snapshot);
+ beginPreviewSessionClose(ref, snapshot.tabId);
+
+ cancelPreviewSessionClose(ref, snapshot, snapshot.tabId);
+
+ const state = readThreadPreviewState(ref);
+ expect(state.sessions).toEqual({ [snapshot.tabId]: snapshot });
+ expect(state.snapshot).toEqual(snapshot);
+ });
+
it("closed event for a different tab is a no-op", () => {
const snapshot = makeSnapshot({ tabId: "tab_a" });
applyPreviewServerEvent(ref, {
diff --git a/apps/web/src/previewStateStore.ts b/apps/web/src/previewStateStore.ts
index 572d19750..7f8f85761 100644
--- a/apps/web/src/previewStateStore.ts
+++ b/apps/web/src/previewStateStore.ts
@@ -28,6 +28,8 @@ export interface DesktopPreviewOverlay {
export interface ThreadPreviewState {
snapshot: PreviewSessionSnapshot | null;
sessions: Record<string, PreviewSessionSnapshot>;
+ /** Tabs intentionally closed by this client. Stale list snapshots must not resurrect them. */
+ suppressedTabIds: ReadonlySet<string>;
activeTabId: string | null;
desktopOverlay: DesktopPreviewOverlay | null;
desktopByTabId: Record<string, DesktopPreviewOverlay>;
@@ -37,6 +39,7 @@ export interface ThreadPreviewState {
const EMPTY_THREAD_PREVIEW_STATE: ThreadPreviewState = Object.freeze({
snapshot: null,
sessions: {},
+ suppressedTabIds: new Set<string>(),
activeTabId: null,
desktopOverlay: null,
desktopByTabId: {},
@@ -162,6 +165,7 @@ export function applyPreviewServerEvent(ref: ScopedThreadRef, event: PreviewEven
case "opened":
case "navigated": {
const snapshot = event.snapshot;
+ if (current.suppressedTabIds.has(snapshot.tabId)) return current;
const recentlySeenUrls =
snapshot.navStatus._tag === "Idle"
? current.recentlySeenUrls
@@ -221,6 +225,7 @@ export function applyPreviewServerSnapshot(
desktopByTabId: {},
};
}
+ if (current.suppressedTabIds.has(snapshot.tabId)) return current;
const existing = current.sessions[snapshot.tabId];
if (existing && existing.updatedAt > snapshot.updatedAt) return current;
const recentlySeenUrls =
@@ -255,8 +260,43 @@ export function applyPreviewDesktopState(
});
}
-export function removePreviewSession(ref: ScopedThreadRef, tabId: string): void {
- updateThreadPreviewState(ref, (current) => removeSession(current, tabId));
+export function beginPreviewSessionClose(ref: ScopedThreadRef, tabId: string): void {
+ updateThreadPreviewState(ref, (current) => {
+ const suppressedTabIds = new Set(current.suppressedTabIds);
+ suppressedTabIds.add(tabId);
+ return {
+ ...removeSession(current, tabId),
+ suppressedTabIds,
+ };
+ });
+}
+
+export function cancelPreviewSessionClose(
+ ref: ScopedThreadRef,
+ snapshot: PreviewSessionSnapshot | null,
+ tabId: string,
+): void {
+ updateThreadPreviewState(ref, (current) => {
+ if (!current.suppressedTabIds.has(tabId)) return current;
+ const suppressedTabIds = new Set(current.suppressedTabIds);
+ suppressedTabIds.delete(tabId);
+ if (!snapshot) {
+ return { ...current, suppressedTabIds };
+ }
+ const recentlySeenUrls =
+ snapshot.navStatus._tag !== "Idle"
+ ? dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url)
+ : current.recentlySeenUrls;
+ return {
+ ...current,
+ snapshot,
+ sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
+ suppressedTabIds,
+ activeTabId: snapshot.tabId,
+ desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
+ recentlySeenUrls,
+ };
+ });
}
export function setActivePreviewTab(ref: ScopedThreadRef, tabId: string): void {
diff --git a/apps/web/src/router.ts b/apps/web/src/router.ts
index f85b080f7..86ba9d69a 100644
--- a/apps/web/src/router.ts
+++ b/apps/web/src/router.ts
@@ -1,7 +1,5 @@
-import { createElement } from "react";
import { createRouter, RouterHistory } from "@tanstack/react-router";
-import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
import { routeTree } from "./routeTree.gen";
export function getRouter(history: RouterHistory) {
@@ -9,7 +7,6 @@ export function getRouter(history: RouterHistory) {
routeTree,
history,
context: {},
- Wrap: ({ children }) => createElement(AppAtomRegistryProvider, undefined, children),
});
}
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 87fba65e2..d9e198897 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -83,6 +83,10 @@
"types": "./src/state/projects.ts",
"default": "./src/state/projects.ts"
},
+ "./state/project-grouping": {
+ "types": "./src/state/projectGrouping.ts",
+ "default": "./src/state/projectGrouping.ts"
+ },
"./state/relay": {
"types": "./src/state/relayDiscovery.ts",
"default": "./src/state/relayDiscovery.ts"
@@ -119,6 +123,10 @@
"types": "./src/state/threads.ts",
"default": "./src/state/threads.ts"
},
+ "./state/thread-sort": {
+ "types": "./src/state/threadSort.ts",
+ "default": "./src/state/threadSort.ts"
+ },
"./state/vcs": {
"types": "./src/state/vcs.ts",
"default": "./src/state/vcs.ts"
diff --git a/packages/client-runtime/src/state/archivedThreads.ts b/packages/client-runtime/src/state/archivedThreads.ts
index 9fbb19f63..7441d46cf 100644
--- a/packages/client-runtime/src/state/archivedThreads.ts
+++ b/packages/client-runtime/src/state/archivedThreads.ts
@@ -1,13 +1,22 @@
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import * as Arr from "effect/Array";
+import * as Cause from "effect/Cause";
import { pipe } from "effect/Function";
+import * as Option from "effect/Option";
import * as Order from "effect/Order";
+import { AsyncResult, Atom } from "effect/unstable/reactivity";
export interface ArchivedSnapshotEntry {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot;
}
+export interface ArchivedThreadSnapshotsState {
+ readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
+ readonly error: string | null;
+ readonly isLoading: boolean;
+}
+
const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
const environmentIdOrder = Order.String as Order.Order<EnvironmentId>;
@@ -28,3 +37,38 @@ export function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<E
Arr.map((environmentId) => EnvironmentId.make(environmentId)),
);
}
+
+export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
+ readonly getSnapshotAtom: (
+ environmentId: EnvironmentId,
+ ) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationShellSnapshot, E>>;
+ readonly labelPrefix: string;
+}) {
+ return Atom.family((environmentKey: string) =>
+ Atom.make((get): ArchivedThreadSnapshotsState => {
+ const snapshots: ArchivedSnapshotEntry[] = [];
+ let error: string | null = null;
+ let isLoading = false;
+
+ for (const environmentId of parseArchivedThreadsEnvironmentKey(environmentKey)) {
+ const result = get(options.getSnapshotAtom(environmentId));
+ isLoading ||= result.waiting;
+
+ const snapshot = Option.getOrNull(AsyncResult.value(result));
+ if (snapshot !== null) {
+ snapshots.push({ environmentId, snapshot });
+ }
+
+ if (error === null && result._tag === "Failure") {
+ const cause = Cause.squash(result.cause);
+ error =
+ cause instanceof Error && cause.message.trim().length > 0
+ ? cause.message
+ : "Failed to load archived threads.";
+ }
+ }
+
+ return { snapshots, error, isLoading };
+ }).pipe(Atom.withLabel(`${options.labelPrefix}:${environmentKey}`)),
+ );
+}
diff --git a/packages/client-runtime/src/state/projectGrouping.ts b/packages/client-runtime/src/state/projectGrouping.ts
new file mode 100644
index 000000000..549942be2
--- /dev/null
+++ b/packages/client-runtime/src/state/projectGrouping.ts
@@ -0,0 +1,183 @@
+import { scopedProjectKey, scopeProjectRef } from "../environment/scoped.ts";
+import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
+import type { UnifiedSettings } from "@t3tools/contracts/settings";
+
+import type { EnvironmentProject } from "./models.ts";
+import { normalizeProjectPathForComparison } from "./projects.ts";
+
+export interface ProjectGroupingSettings {
+ readonly sidebarProjectGroupingMode: SidebarProjectGroupingMode;
+ readonly sidebarProjectGroupingOverrides: Record<string, SidebarProjectGroupingMode>;
+}
+
+export type ProjectGroupingMode = SidebarProjectGroupingMode;
+
+export function selectProjectGroupingSettings(settings: UnifiedSettings): ProjectGroupingSettings {
+ return {
+ sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
+ sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
+ };
+}
+
+function uniqueNonEmptyValues(values: ReadonlyArray<string | null | undefined>): string[] {
+ const seen = new Set<string>();
+ const unique: string[] = [];
+ for (const value of values) {
+ const trimmed = value?.trim();
+ if (!trimmed || seen.has(trimmed)) {
+ continue;
+ }
+ seen.add(trimmed);
+ unique.push(trimmed);
+ }
+ return unique;
+}
+
+function deriveRepositoryRelativeProjectPath(
+ project: Pick<EnvironmentProject, "workspaceRoot" | "repositoryIdentity">,
+): string | null {
+ const rootPath = project.repositoryIdentity?.rootPath?.trim();
+ if (!rootPath) {
+ return null;
+ }
+
+ const normalizedProjectPath = normalizeProjectPathForComparison(project.workspaceRoot);
+ const normalizedRootPath = normalizeProjectPathForComparison(rootPath);
+ if (normalizedProjectPath.length === 0 || normalizedRootPath.length === 0) {
+ return null;
+ }
+
+ if (normalizedProjectPath === normalizedRootPath) {
+ return "";
+ }
+
+ const separator = normalizedRootPath.includes("\\") ? "\\" : "/";
+ const rootPrefix = `${normalizedRootPath}${separator}`;
+ if (!normalizedProjectPath.startsWith(rootPrefix)) {
+ return null;
+ }
+
+ return normalizedProjectPath.slice(rootPrefix.length).replaceAll("\\", "/");
+}
+
+export function derivePhysicalProjectKeyFromPath(environmentId: string, cwd: string): string {
+ return `${environmentId}:${normalizeProjectPathForComparison(cwd)}`;
+}
+
+export function derivePhysicalProjectKey(
+ project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
+): string {
+ return derivePhysicalProjectKeyFromPath(project.environmentId, project.workspaceRoot);
+}
+
+export function deriveProjectGroupingOverrideKey(
+ project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
+): string {
+ return derivePhysicalProjectKey(project);
+}
+
+export function getProjectOrderKey(
+ project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
+): string {
+ return derivePhysicalProjectKey(project);
+}
+
+export function resolveProjectGroupingMode(
+ project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
+ settings: ProjectGroupingSettings,
+): SidebarProjectGroupingMode {
+ return (
+ settings.sidebarProjectGroupingOverrides?.[deriveProjectGroupingOverrideKey(project)] ??
+ settings.sidebarProjectGroupingMode
+ );
+}
+
+function deriveRepositoryScopedKey(
+ project: Pick<EnvironmentProject, "workspaceRoot" | "repositoryIdentity">,
+ groupingMode: SidebarProjectGroupingMode,
+): string | null {
+ const canonicalKey = project.repositoryIdentity?.canonicalKey;
+ if (!canonicalKey) {
+ return null;
+ }
+
+ if (groupingMode === "repository") {
+ return canonicalKey;
+ }
+
+ const relativeProjectPath = deriveRepositoryRelativeProjectPath(project);
+ if (relativeProjectPath === null) {
+ return canonicalKey;
+ }
+
+ return relativeProjectPath.length === 0
+ ? canonicalKey
+ : `${canonicalKey}::${relativeProjectPath}`;
+}
+
+export function deriveLogicalProjectKey(
+ project: Pick<
+ EnvironmentProject,
+ "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity"
+ >,
+ options?: {
+ readonly groupingMode?: SidebarProjectGroupingMode;
+ },
+): string {
+ const groupingMode = options?.groupingMode ?? "repository";
+ if (groupingMode === "separate") {
+ return derivePhysicalProjectKey(project);
+ }
+
+ return (
+ deriveRepositoryScopedKey(project, groupingMode) ??
+ derivePhysicalProjectKey(project) ??
+ scopedProjectKey(scopeProjectRef(project.environmentId, project.id))
+ );
+}
+
+export function deriveLogicalProjectKeyFromSettings(
+ project: Pick<
+ EnvironmentProject,
+ "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity"
+ >,
+ settings: ProjectGroupingSettings,
+): string {
+ return deriveLogicalProjectKey(project, {
+ groupingMode: resolveProjectGroupingMode(project, settings),
+ });
+}
+
+export function deriveLogicalProjectKeyFromRef(
+ projectRef: ScopedProjectRef,
+ project:
+ | Pick<EnvironmentProject, "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity">
+ | null
+ | undefined,
+ options?: {
+ readonly groupingMode?: SidebarProjectGroupingMode;
+ },
+): string {
+ return project ? deriveLogicalProjectKey(project, options) : scopedProjectKey(projectRef);
+}
+
+export function deriveProjectGroupLabel(input: {
+ readonly representative: Pick<EnvironmentProject, "title" | "repositoryIdentity">;
+ readonly members: ReadonlyArray<Pick<EnvironmentProject, "title" | "repositoryIdentity">>;
+}): string {
+ const sharedDisplayNames = uniqueNonEmptyValues(
+ input.members.map((member) => member.repositoryIdentity?.displayName),
+ );
+ if (sharedDisplayNames.length === 1) {
+ return sharedDisplayNames[0]!;
+ }
+
+ const sharedRepositoryNames = uniqueNonEmptyValues(
+ input.members.map((member) => member.repositoryIdentity?.name),
+ );
+ if (sharedRepositoryNames.length === 1) {
+ return sharedRepositoryNames[0]!;
+ }
+
+ return input.representative.title;
+}
diff --git a/packages/client-runtime/src/state/threadSort.ts b/packages/client-runtime/src/state/threadSort.ts
new file mode 100644
index 000000000..4da184962
--- /dev/null
+++ b/packages/client-runtime/src/state/threadSort.ts
@@ -0,0 +1,101 @@
+import type { ProjectId } from "@t3tools/contracts";
+import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+
+export interface ThreadSortInput {
+ readonly createdAt: string;
+ readonly updatedAt: string;
+ readonly latestUserMessageAt?: string | null;
+ readonly messages?: ReadonlyArray<{
+ readonly createdAt: string;
+ readonly role: string;
+ }>;
+}
+
+export function toSortableTimestamp(iso: string | undefined): number | null {
+ if (!iso) return null;
+ const ms = Date.parse(iso);
+ return Number.isFinite(ms) ? ms : null;
+}
+
+function getFirstSortableTimestamp(...values: Array<string | null | undefined>): number | null {
+ for (const value of values) {
+ const timestamp = toSortableTimestamp(value ?? undefined);
+ if (timestamp !== null) {
+ return timestamp;
+ }
+ }
+
+ return null;
+}
+
+function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
+ if (thread.latestUserMessageAt) {
+ return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
+ }
+
+ let latestUserMessageTimestamp: number | null = null;
+
+ for (const message of thread.messages ?? []) {
+ if (message.role !== "user") continue;
+ const messageTimestamp = toSortableTimestamp(message.createdAt);
+ if (messageTimestamp === null) continue;
+ latestUserMessageTimestamp =
+ latestUserMessageTimestamp === null
+ ? messageTimestamp
+ : Math.max(latestUserMessageTimestamp, messageTimestamp);
+ }
+
+ if (latestUserMessageTimestamp !== null) {
+ return latestUserMessageTimestamp;
+ }
+
+ return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY;
+}
+
+export function getThreadSortTimestamp(
+ thread: ThreadSortInput,
+ sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
+): number {
+ if (sortOrder === "created_at") {
+ return (
+ getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY
+ );
+ }
+ return getLatestUserMessageTimestamp(thread);
+}
+
+export function sortThreads<T extends { readonly id: string } & ThreadSortInput>(
+ threads: readonly T[],
+ sortOrder: SidebarThreadSortOrder,
+): T[] {
+ return Arr.sort(
+ threads,
+ Order.mapInput(
+ Order.Struct({
+ timestamp: Order.flip(Order.Number),
+ id: Order.flip(Order.String),
+ }),
+ (thread: T) => ({
+ timestamp: getThreadSortTimestamp(thread, sortOrder),
+ id: thread.id,
+ }),
+ ),
+ );
+}
+
+export function getLatestThreadForProject<
+ T extends {
+ readonly id: string;
+ readonly projectId: ProjectId;
+ readonly archivedAt: string | null;
+ } & ThreadSortInput,
+>(threads: readonly T[], projectId: ProjectId, sortOrder: SidebarThreadSortOrder): T | null {
+ return (
+ sortThreads(
+ threads.filter((thread) => thread.projectId === projectId && thread.archivedAt === null),
+ sortOrder,
+ )[0] ?? null
+ );
+}
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 3b3d46a02..23705178b 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -163,6 +163,10 @@
"types": "./src/preview.ts",
"import": "./src/preview.ts"
},
+ "./filePreview": {
+ "types": "./src/filePreview.ts",
+ "import": "./src/filePreview.ts"
+ },
"./hostProcess": {
"types": "./src/hostProcess.ts",
"import": "./src/hostProcess.ts"
diff --git a/packages/shared/src/filePreview.test.ts b/packages/shared/src/filePreview.test.ts
new file mode 100644
index 000000000..eb8b7d1e8
--- /dev/null
+++ b/packages/shared/src/filePreview.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ isWorkspaceBrowserPreviewPath,
+ isWorkspaceImagePreviewPath,
+ isWorkspacePreviewEntryPath,
+} from "./filePreview.ts";
+
+describe("workspace file previews", () => {
+ it.each(["report.html", "report.HTM", "document.pdf?download=1"])(
+ "recognizes browser preview path %s",
+ (path) => {
+ expect(isWorkspaceBrowserPreviewPath(path)).toBe(true);
+ expect(isWorkspacePreviewEntryPath(path)).toBe(true);
+ },
+ );
+
+ it.each([
+ "icon.png",
+ "photo.JPEG",
+ "animation.gif",
+ "vector.svg#mark",
+ "texture.webp",
+ "image.avif",
+ ])("recognizes image preview path %s", (path) => {
+ expect(isWorkspaceImagePreviewPath(path)).toBe(true);
+ expect(isWorkspacePreviewEntryPath(path)).toBe(true);
+ });
+
+ it.each(["README.md", "src/index.ts", "image.png.ts", "png"])(
+ "rejects non-preview path %s",
+ (path) => {
+ expect(isWorkspacePreviewEntryPath(path)).toBe(false);
+ },
+ );
+});
diff --git a/packages/shared/src/filePreview.ts b/packages/shared/src/filePreview.ts
new file mode 100644
index 000000000..c9d15e14c
--- /dev/null
+++ b/packages/shared/src/filePreview.ts
@@ -0,0 +1,29 @@
+export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const;
+
+export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
+ ".avif",
+ ".gif",
+ ".ico",
+ ".jpeg",
+ ".jpg",
+ ".png",
+ ".svg",
+ ".webp",
+] as const;
+
+function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
+ const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? "";
+ return extensions.some((extension) => pathWithoutQuery.endsWith(extension));
+}
+
+export function isWorkspaceBrowserPreviewPath(path: string): boolean {
+ return hasPreviewExtension(path, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS);
+}
+
+export function isWorkspaceImagePreviewPath(path: string): boolean {
+ return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);
+}
+
+export function isWorkspacePreviewEntryPath(path: string): boolean {
+ return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6d8189362..9b9312da6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -247,7 +247,7 @@ importers:
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
expo:
specifier: ^56.0.0
expo-asset:
specifier: ~56.0.15
@@ -362,6 +362,9 @@ importers:
react-native-svg:
specifier: 15.15.4
+ react-native-webview:
+ specifier: ^13.16.1
react-native-worklets:
specifier: 0.8.3
@@ -8453,6 +8456,12 @@ packages:
peerDependencies:
react-native: '*'
+ resolution: {integrity: sha512-If0eHhoEdOYDcHsX+xBFwHMbWBGK1BvGDQDQdVkwtSIXiq1uiqjkpWVP2uQ1as94J0CzvFE9PUNDuhiX0Z6ubw==}
+ peerDependencies:
+ react: '*'
+ react-native: '*'
+
resolution: {integrity: sha512-oCBJROyLU7yG/1R8s0INMflygTH71bx+5XcYkH0CM938TlhSoVbiunE1WVW5FZa51vwYqfLie/IXMX2s1Kh3eg==}
peerDependencies:
@@ -10784,7 +10793,7 @@ snapshots:
base-64: 1.0.0
react: 19.2.3
@@ -11396,7 +11405,7 @@ snapshots:
connect: 3.7.0
debug: 4.4.3
dnssd-advertise: 1.1.4
expo-server: 56.0.4
fetch-nodeshim: 0.4.10
getenv: 2.0.0
@@ -11494,7 +11503,7 @@ snapshots:
dependencies:
react: 19.2.3
@@ -11561,7 +11570,7 @@ snapshots:
dependencies:
anser: 1.4.10
react: 19.2.3
stacktrace-parser: 0.1.11
@@ -11593,7 +11602,7 @@ snapshots:
postcss: 8.5.15
resolve-from: 5.0.0
optionalDependencies:
transitivePeerDependencies:
- bufferutil
- supports-color
@@ -11615,7 +11624,7 @@ snapshots:
dependencies:
anser: 1.4.10
pretty-format: 29.7.0
react: 19.2.3
@@ -11693,7 +11702,7 @@ snapshots:
dependencies:
debug: 4.4.3
expo-server: 56.0.4
@@ -11717,7 +11726,7 @@ snapshots:
'@expo/[email protected](ab3f255d102c60ba0fd2bbe4e47ba584)':
dependencies:
react: 19.2.3
sf-symbols-typescript: 2.2.0
@@ -14450,7 +14459,7 @@ snapshots:
react-refresh: 0.14.2
optionalDependencies:
'@babel/runtime': 7.29.7
expo-widgets: 56.0.16(ab3f255d102c60ba0fd2bbe4e47ba584)
transitivePeerDependencies:
- '@babel/core'
@@ -15316,12 +15325,12 @@ snapshots:
dependencies:
dependencies:
'@expo/image-utils': 0.10.1([email protected])
react: 19.2.3
@@ -15346,14 +15355,14 @@ snapshots:
dependencies:
'@expo/schema-utils': 56.0.1
resolve-from: 5.0.0
semver: 7.8.1
dependencies:
barcode-detector: 3.2.0(@types/[email protected])
react: 19.2.3
transitivePeerDependencies:
@@ -15361,25 +15370,25 @@ snapshots:
dependencies:
react: 19.2.3
dependencies:
'@expo/env': 2.3.0
transitivePeerDependencies:
- supports-color
dependencies:
dependencies:
expo-dev-menu-interface: 56.0.1([email protected])
@@ -15391,18 +15400,18 @@ snapshots:
dependencies:
'@expo/schema-utils': 56.0.1
expo-manifests: 56.0.4([email protected])
dependencies:
dependencies:
expo-dev-menu-interface: 56.0.1([email protected])
@@ -15410,40 +15419,40 @@ snapshots:
dependencies:
dependencies:
fontfaceobserver: 2.3.0
react: 19.2.3
dependencies:
react: 19.2.3
dependencies:
dependencies:
dependencies:
expo-image-loader: 56.0.3([email protected])
dependencies:
react: 19.2.3
@@ -15458,7 +15467,7 @@ snapshots:
dependencies:
expo-json-utils: 56.0.0
@@ -15487,7 +15496,7 @@ snapshots:
dependencies:
react: 19.2.3
@@ -15495,7 +15504,7 @@ snapshots:
'@expo/image-utils': 0.10.1([email protected])
abort-controller: 3.0.0
badgin: 1.2.3
expo-application: 56.0.3([email protected])
react: 19.2.3
@@ -15506,7 +15515,7 @@ snapshots:
dependencies:
react: 19.2.3
@@ -15525,7 +15534,7 @@ snapshots:
color: 4.2.3
debug: 4.4.3
escape-string-regexp: 4.0.0
@@ -15561,7 +15570,7 @@ snapshots:
dependencies:
@@ -15569,7 +15578,7 @@ snapshots:
dependencies:
'@expo/config-plugins': 56.0.8([email protected])
'@expo/image-utils': 0.10.1([email protected])
xml2js: 0.6.0
transitivePeerDependencies:
- supports-color
@@ -15580,7 +15589,7 @@ snapshots:
dependencies:
'@expo-google-fonts/material-symbols': 0.4.38
react: 19.2.3
@@ -15588,7 +15597,7 @@ snapshots:
dependencies:
dependencies:
@@ -15598,7 +15607,7 @@ snapshots:
arg: 4.1.3
chalk: 4.1.2
debug: 4.4.3
expo-eas-client: 56.0.1
expo-manifests: 56.0.4([email protected])
expo-structured-headers: 56.0.0
@@ -15617,14 +15626,14 @@ snapshots:
dependencies:
[email protected](ab3f255d102c60ba0fd2bbe4e47ba584):
dependencies:
'@expo/plist': 0.7.0
'@expo/ui': 56.0.15(ab3f255d102c60ba0fd2bbe4e47ba584)
react: 19.2.3
transitivePeerDependencies:
@@ -15635,7 +15644,7 @@ snapshots:
- react-native-reanimated
- react-native-worklets
dependencies:
'@babel/runtime': 7.29.7
@@ -15665,6 +15674,7 @@ snapshots:
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- '@babel/core'
- bufferutil
@@ -18139,6 +18149,13 @@ snapshots:
whatwg-url-without-unicode: 8.0.0-3
+ dependencies:
+ escape-string-regexp: 4.0.0
+ invariant: 2.2.4
+ react: 19.2.3
+
dependencies:
'@babel/core': 7.29.7