From eba28035d2abc82da42db1705a35cbec855e5eb3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 4 May 2026 19:29:02 -0700 Subject: [PATCH] Add inline review comment selection to mobile diffs - render comment rows and line selection state in the native diff view - wire long-press/tap gestures to start and complete review comments - tighten shared diff utilities and add coverage --- apps/mobile/global.css | 30 ++- .../ios/T3ReviewDiffModule.swift | 10 +- .../t3-review-diff/ios/T3ReviewDiffView.swift | 194 ++++++++++++++++++ .../nativeReviewDiffModule.ts | 18 +- .../review/reviewCommentSelection.test.ts | 60 ++++++ .../features/review/reviewCommentSelection.ts | 89 +++++++- .../src/features/threads/ThreadFeed.tsx | 63 ++++-- .../ThreadTerminalDrawer.browser.tsx | 77 ++++++- .../src/components/ThreadTerminalDrawer.tsx | 39 +++- apps/web/src/lib/contextWindow.test.ts | 17 ++ apps/web/src/lib/contextWindow.ts | 2 +- apps/web/src/lib/lruCache.test.ts | 9 + apps/web/src/lib/lruCache.ts | 4 + apps/web/src/lib/threadSort.test.ts | 48 +++++ apps/web/src/lib/threadSort.ts | 17 +- 15 files changed, 640 insertions(+), 37 deletions(-) create mode 100644 apps/mobile/src/features/review/reviewCommentSelection.test.ts diff --git a/apps/mobile/global.css b/apps/mobile/global.css index 387f6b51bd..bbd1cb0be0 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -62,19 +62,24 @@ --color-status-bar: #f2f2f7; /* Markdown */ - --color-md-body: #262626; - --color-md-strong: #171717; + --color-md-body: #111111; + --color-md-strong: #000000; --color-md-link: #2563eb; --color-md-blockquote-border: rgba(0, 0, 0, 0.08); --color-md-blockquote-bg: rgba(0, 0, 0, 0.02); --color-md-code-bg: rgba(0, 0, 0, 0.04); --color-md-code-text: #262626; - --color-md-user-code-bg: rgba(255, 255, 255, 0.55); - --color-md-user-code-text: #262626; - --color-md-user-fence-bg: rgba(0, 0, 0, 0.04); - --color-md-user-fence-text: #1e3a5f; + --color-md-user-code-bg: rgba(255, 255, 255, 0.22); + --color-md-user-code-text: #ffffff; + --color-md-user-fence-bg: rgba(0, 0, 0, 0.16); + --color-md-user-fence-text: #ffffff; --color-md-hr: rgba(0, 0, 0, 0.08); + /* iMessage-style user bubble */ + --color-user-bubble: #007aff; + --color-user-bubble-foreground: #ffffff; + --color-user-bubble-foreground-muted: rgba(255, 255, 255, 0.78); + /* Drawer / modal backdrop */ --color-backdrop: rgba(0, 0, 0, 0.22); --color-drawer: rgba(255, 255, 255, 0.99); @@ -151,12 +156,17 @@ --color-md-blockquote-bg: rgba(255, 255, 255, 0.03); --color-md-code-bg: rgba(255, 255, 255, 0.06); --color-md-code-text: #e5e5e5; - --color-md-user-code-bg: rgba(255, 255, 255, 0.1); - --color-md-user-code-text: #e5e5e5; - --color-md-user-fence-bg: rgba(255, 255, 255, 0.08); - --color-md-user-fence-text: #e5e5e5; + --color-md-user-code-bg: rgba(255, 255, 255, 0.18); + --color-md-user-code-text: #ffffff; + --color-md-user-fence-bg: rgba(0, 0, 0, 0.28); + --color-md-user-fence-text: #ffffff; --color-md-hr: rgba(255, 255, 255, 0.08); + /* iMessage-style user bubble */ + --color-user-bubble: #0a84ff; + --color-user-bubble-foreground: #ffffff; + --color-user-bubble-foreground-muted: rgba(255, 255, 255, 0.78); + /* Drawer / modal backdrop */ --color-backdrop: rgba(0, 0, 0, 0.48); --color-drawer: rgba(14, 14, 14, 0.99); diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift index f74ced123e..f196716599 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift @@ -29,6 +29,14 @@ public class T3ReviewDiffModule: Module { view.setViewedFileIdsJson(viewedFileIdsJson) } + Prop("selectedRowIdsJson") { (view: T3ReviewDiffView, selectedRowIdsJson: String) in + view.setSelectedRowIdsJson(selectedRowIdsJson) + } + + Prop("collapsedCommentIdsJson") { (view: T3ReviewDiffView, collapsedCommentIdsJson: String) in + view.setCollapsedCommentIdsJson(collapsedCommentIdsJson) + } + Prop("appearanceScheme") { (view: T3ReviewDiffView, appearanceScheme: String) in view.setAppearanceScheme(appearanceScheme) } @@ -49,7 +57,7 @@ public class T3ReviewDiffModule: Module { view.setContentWidth(CGFloat(contentWidth)) } - Events("onDebug", "onToggleFile", "onToggleViewedFile") + 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 678932d5ee..57cf17f700 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -16,6 +16,9 @@ private struct ReviewDiffNativeRow: Decodable { let oldLineNumber: Int? let newLineNumber: Int? let wordDiffRanges: [ReviewDiffNativeWordDiffRange]? + let commentText: String? + let commentRangeLabel: String? + let commentSectionTitle: String? } private struct ReviewDiffNativeWordDiffRange: Decodable { @@ -317,6 +320,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { let onDebug = EventDispatcher() let onToggleFile = EventDispatcher() let onToggleViewedFile = EventDispatcher() + let onPressLine = EventDispatcher() + let onToggleComment = EventDispatcher() public required init(appContext: AppContext? = nil) { super.init(appContext: appContext) @@ -340,6 +345,12 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { contentView.onToggleViewedFile = { [weak self] fileId in self?.onToggleViewedFile(["fileId": fileId]) } + contentView.onPressLine = { [weak self] payload in + self?.onPressLine(payload) + } + contentView.onToggleComment = { [weak self] commentId in + self?.onToggleComment(["commentId": commentId]) + } contentView.onDrawMetrics = { [weak self] metrics in self?.emitDebug("draw-metrics", metrics) } @@ -487,6 +498,15 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { contentView.viewedFileIds = decodeFileIdSet(viewedFileIdsJson) } + func setSelectedRowIdsJson(_ selectedRowIdsJson: String) { + contentView.selectedRowIds = decodeFileIdSet(selectedRowIdsJson) + } + + func setCollapsedCommentIdsJson(_ collapsedCommentIdsJson: String) { + contentView.collapsedCommentIds = decodeFileIdSet(collapsedCommentIdsJson) + updateContentMetrics() + } + private func decodeFileIdSet(_ json: String) -> Set { guard let data = json.data(using: .utf8) else { return [] @@ -718,6 +738,17 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { setNeedsDisplayForVisibleBounds() } } + var selectedRowIds: Set = [] { + didSet { + setNeedsDisplayForVisibleBounds() + } + } + var collapsedCommentIds: Set = [] { + didSet { + rebuildRowLayout() + setNeedsDisplayForVisibleBounds() + } + } var style = ReviewDiffNativeStyle.resolve(nil) { didSet { tokenAttributedStringsByRowId.removeAll() @@ -760,6 +791,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { var isVerticalScrollActive = false var onToggleFile: ((String) -> Void)? var onToggleViewedFile: ((String) -> Void)? + var onPressLine: (([String: Any]) -> Void)? + var onToggleComment: ((String) -> Void)? var onDrawMetrics: (([String: Any]) -> Void)? private var stickyWidth: CGFloat { @@ -780,6 +813,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { if row.kind == "notice" { return max(style.rowHeight * 2, 44) } + if row.kind == "comment" { + return collapsedCommentIds.contains(row.id) ? 44 : 124 + } return style.rowHeight } @@ -871,12 +907,22 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return gesture }() + private lazy var longPressGesture: UILongPressGestureRecognizer = { + let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:))) + gesture.delegate = self + gesture.cancelsTouchesInView = false + gesture.minimumPressDuration = 0.28 + return gesture + }() + override init(frame: CGRect) { super.init(frame: frame) isOpaque = true contentMode = .redraw addGestureRecognizer(horizontalPanGesture) addGestureRecognizer(tapGesture) + addGestureRecognizer(longPressGesture) + tapGesture.require(toFail: longPressGesture) } func invalidateVisibleViewport() { @@ -893,6 +939,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { contentMode = .redraw addGestureRecognizer(horizontalPanGesture) addGestureRecognizer(tapGesture) + addGestureRecognizer(longPressGesture) + tapGesture.require(toFail: longPressGesture) } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { @@ -934,6 +982,16 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { } let row = rows[rowIndex] + if row.kind == "comment" { + onToggleComment?(row.id) + return + } + + if row.kind == "line" { + onPressLine?(linePressPayload(for: row, gesture: "tap")) + return + } + guard row.kind == "file" else { return } @@ -943,6 +1001,45 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { handleFileHeaderTap(row: row, rect: rect, point: point) } + @objc private func handleLongPress(_ gesture: UILongPressGestureRecognizer) { + guard gesture.state == .began else { + return + } + + let point = gesture.location(in: self) + guard let rowIndex = rowIndex(at: verticalOffset + point.y), + rows.indices.contains(rowIndex) else { + return + } + + let row = rows[rowIndex] + guard row.kind == "line" else { + return + } + + onPressLine?(linePressPayload(for: row, gesture: "longPress")) + } + + private func linePressPayload(for row: ReviewDiffNativeRow, gesture: String) -> [String: Any] { + var payload: [String: Any] = [ + "rowId": row.id, + "fileId": resolvedFileId(for: row), + "gesture": gesture + ] + + if let oldLineNumber = row.oldLineNumber { + payload["oldLineNumber"] = oldLineNumber + } + if let newLineNumber = row.newLineNumber { + payload["newLineNumber"] = newLineNumber + } + if let change = row.change { + payload["change"] = change + } + + return payload + } + private func handleFileHeaderTap(row: ReviewDiffNativeRow, rect: CGRect, point: CGPoint) { let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: rect) let fileId = resolvedFileId(for: row) @@ -1418,6 +1515,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { drawHunkRow(row, rect: fullRect, context: context) case "notice": drawNoticeRow(row, rect: fullRect, context: context) + case "comment": + drawCommentRow(row, rect: fullRect, context: context) default: drawCodeRow(row, rect: fullRect, context: context) } @@ -1524,6 +1623,59 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { ) } + private func drawCommentRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { + guard !collapsedFileIds.contains(resolvedFileId(for: row)) else { + return + } + + theme.background.setFill() + context.fill(rect) + + let isCollapsed = collapsedCommentIds.contains(row.id) + let cardInset = CGFloat(8) + let cardRect = rect.insetBy(dx: cardInset, dy: 5) + let cardPath = UIBezierPath(roundedRect: cardRect, cornerRadius: 10) + theme.headerBackground.setFill() + cardPath.fill() + theme.border.withAlphaComponent(0.85).setStroke() + cardPath.lineWidth = 1 + cardPath.stroke() + + let chevronRect = CGRect(x: cardRect.minX + 10, y: cardRect.minY + 11, width: 16, height: 16) + drawDisclosureChevron(rect: chevronRect, color: theme.mutedText, collapsed: isCollapsed) + + let title = "Comment on \(row.commentRangeLabel ?? "line")" + drawSingleLineText( + title, + rect: CGRect( + x: chevronRect.maxX + 10, + y: cardRect.minY + 8, + width: max(24, cardRect.width - chevronRect.maxX - 28), + height: fileHeaderSubtextFont.lineHeight + 4 + ), + color: theme.mutedText, + font: fileHeaderSubtextFont + ) + + guard !isCollapsed else { + return + } + + let body = row.commentText?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + drawMultilineText( + body.isEmpty ? "Comment" : body, + rect: CGRect( + x: cardRect.minX + 18, + y: cardRect.minY + 42, + width: max(24, cardRect.width - 36), + height: max(20, cardRect.height - 56) + ), + color: theme.text, + font: fileHeaderSubtextFont, + maximumLineCount: 3 + ) + } + private func fileHeaderPathLayout( for row: ReviewDiffNativeRow, cardRect: CGRect @@ -1762,6 +1914,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let change = row.change ?? "context" rowBackground(for: change).setFill() context.fill(rect) + drawSelectionOverlay(row, rect: rect, context: context) if change == "add" { theme.addBar.setFill() @@ -1811,6 +1964,23 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { context.restoreGState() } + private func drawSelectionOverlay( + _ row: ReviewDiffNativeRow, + rect: CGRect, + context: CGContext + ) { + guard selectedRowIds.contains(row.id) else { + return + } + + let selectionColor = theme.hunkText.withAlphaComponent(0.22) + selectionColor.setFill() + context.fill(rect) + + theme.hunkText.withAlphaComponent(0.95).setFill() + context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) + } + private func drawWordDiffRanges( _ row: ReviewDiffNativeRow, rowRect: CGRect, @@ -1891,6 +2061,30 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { (text as NSString).draw(in: rect, withAttributes: attributes) } + private func drawMultilineText( + _ text: String, + rect: CGRect, + color: UIColor, + font: UIFont, + maximumLineCount: Int + ) { + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineBreakMode = .byTruncatingTail + paragraphStyle.lineSpacing = 2 + + let attributes: [NSAttributedString.Key: Any] = [ + .font: font, + .foregroundColor: color, + .paragraphStyle: paragraphStyle, + .ligature: 0, + ] + let maxHeight = CGFloat(maximumLineCount) * (font.lineHeight + paragraphStyle.lineSpacing) + (text as NSString).draw( + in: CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: min(rect.height, maxHeight)), + withAttributes: attributes + ) + } + private func centeredTextY(in rect: CGRect, font: UIFont) -> CGFloat { rect.midY - font.lineHeight / 2 } diff --git a/apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffModule.ts b/apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffModule.ts index d75be5cae4..bdea03f5b3 100644 --- a/apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffModule.ts +++ b/apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffModule.ts @@ -11,7 +11,7 @@ interface ExpoGlobalWithViewConfig { } export interface NativeReviewDiffRow { - readonly kind: "file" | "hunk" | "line" | "notice"; + readonly kind: "file" | "hunk" | "line" | "notice" | "comment"; readonly id: string; readonly fileId?: string; readonly filePath?: string; @@ -31,6 +31,9 @@ export interface NativeReviewDiffRow { readonly oldLineNumber?: number | null; readonly newLineNumber?: number | null; readonly wordDiffRanges?: ReadonlyArray; + readonly commentText?: string; + readonly commentRangeLabel?: string; + readonly commentSectionTitle?: string; } export interface NativeReviewDiffWordDiffRange { @@ -100,6 +103,8 @@ export interface NativeReviewDiffViewProps extends ViewProps { readonly tokensResetKey?: string; readonly collapsedFileIdsJson?: string; readonly viewedFileIdsJson?: string; + readonly selectedRowIdsJson?: string; + readonly collapsedCommentIdsJson?: string; readonly appearanceScheme: "light" | "dark"; readonly themeJson: string; readonly styleJson?: string; @@ -108,6 +113,17 @@ export interface NativeReviewDiffViewProps extends ViewProps { readonly onDebug?: (event: NativeSyntheticEvent>) => void; readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void; readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void; + readonly onPressLine?: ( + event: NativeSyntheticEvent<{ + readonly rowId?: string; + readonly fileId?: string; + readonly gesture?: "tap" | "longPress"; + readonly oldLineNumber?: number; + readonly newLineNumber?: number; + readonly change?: "context" | "add" | "delete"; + }>, + ) => void; + readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void; } let cachedNativeReviewDiffView: ComponentType | undefined; diff --git a/apps/mobile/src/features/review/reviewCommentSelection.test.ts b/apps/mobile/src/features/review/reviewCommentSelection.test.ts new file mode 100644 index 0000000000..f6ed60cc25 --- /dev/null +++ b/apps/mobile/src/features/review/reviewCommentSelection.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; + +import { + countReviewCommentContexts, + formatReviewCommentContext, + parseReviewInlineComments, + type ReviewCommentTarget, +} from "./reviewCommentSelection"; + +function makeTarget(): ReviewCommentTarget { + return { + sectionId: "section-1", + sectionTitle: "Working tree", + filePath: "apps/demo/src/main.ts", + startIndex: 0, + endIndex: 1, + lines: [ + { + kind: "line", + id: "line-1", + change: "delete", + oldLineNumber: 7, + newLineNumber: null, + content: "const retryLimit = 2;", + additionTokenIndex: null, + deletionTokenIndex: 0, + comparison: null, + }, + { + kind: "line", + id: "line-2", + change: "add", + oldLineNumber: null, + newLineNumber: 7, + content: "const retryLimit = 4;", + additionTokenIndex: 0, + deletionTokenIndex: null, + comparison: null, + }, + ], + }; +} + +describe("review comment serialization", () => { + it("preserves enough metadata for inline diff rendering", () => { + const serialized = formatReviewCommentContext(makeTarget(), "Please keep this configurable."); + + expect(countReviewCommentContexts(serialized)).toBe(1); + expect(parseReviewInlineComments(serialized)).toEqual([ + expect.objectContaining({ + sectionId: "section-1", + sectionTitle: "Working tree", + filePath: "apps/demo/src/main.ts", + startIndex: 0, + endIndex: 1, + text: "Please keep this configurable.", + }), + ]); + }); +}); diff --git a/apps/mobile/src/features/review/reviewCommentSelection.ts b/apps/mobile/src/features/review/reviewCommentSelection.ts index fbc27f82cb..5c116de409 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.ts @@ -3,6 +3,7 @@ import { useSyncExternalStore } from "react"; import type { ReviewRenderableLineRow } from "./reviewModel"; export interface ReviewCommentTarget { + readonly sectionId: string; readonly sectionTitle: string; readonly filePath: string; readonly lines: ReadonlyArray; @@ -10,8 +11,21 @@ export interface ReviewCommentTarget { readonly endIndex: number; } +export interface ReviewInlineComment { + readonly id: string; + readonly sectionId: string; + readonly sectionTitle: string; + readonly filePath: string; + readonly startIndex: number; + readonly endIndex: number; + readonly rangeLabel: string; + readonly text: string; +} + let currentTarget: ReviewCommentTarget | null = null; const listeners = new Set<() => void>(); +const REVIEW_COMMENT_BLOCK_PATTERN = /]*)>\s*([\s\S]*?)<\/review_comment>/g; +const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g; function emitChange() { listeners.forEach((listener) => listener()); @@ -73,11 +87,12 @@ export function getReviewChangeMarker(change: ReviewRenderableLineRow["change"]) } export function buildReviewCommentTarget( - target: Pick, + target: Pick, anchorIndex: number, lineIndex: number, ): ReviewCommentTarget { return { + sectionId: target.sectionId, sectionTitle: target.sectionTitle, filePath: target.filePath, lines: target.lines, @@ -142,9 +157,51 @@ function formatReviewSelectedDiff(target: ReviewCommentTarget): string { ].join("\n"); } +function escapeReviewCommentAttribute(value: string): string { + return value.replace(/&/g, "&").replace(/"/g, """).replace(/ { + const attributes: Record = {}; + for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) { + attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? ""); + } + return attributes; +} + +function readNonNegativeInteger(value: string | undefined): number | null { + if (value === undefined || !/^\d+$/.test(value)) { + return null; + } + return Number(value); +} + +function extractReviewCommentText(rawBody: string): string { + const fenceIndex = rawBody.indexOf("```diff"); + const commentBody = fenceIndex >= 0 ? rawBody.slice(0, fenceIndex) : rawBody; + return commentBody.trim(); +} + export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string { + const rangeLabel = formatReviewSelectedRangeLabel(target); return [ - "", + [ + "", + ].join(""), comment.trim(), "```diff", formatReviewSelectedDiff(target), @@ -154,5 +211,31 @@ export function formatReviewCommentContext(target: ReviewCommentTarget, comment: } export function countReviewCommentContexts(value: string): number { - return Array.from(value.matchAll(//g)).length; + return Array.from(value.matchAll(/ { + const comments: ReviewInlineComment[] = []; + for (const [index, match] of Array.from(value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)).entries()) { + const attributes = readReviewCommentAttributes(match[1] ?? ""); + const startIndex = readNonNegativeInteger(attributes.startIndex); + const endIndex = readNonNegativeInteger(attributes.endIndex); + const filePath = attributes.filePath?.trim(); + const sectionId = attributes.sectionId?.trim(); + if (!filePath || !sectionId || startIndex === null || endIndex === null) { + continue; + } + + comments.push({ + id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`, + sectionId, + sectionTitle: attributes.sectionTitle?.trim() || "Review", + filePath, + startIndex: Math.min(startIndex, endIndex), + endIndex: Math.max(startIndex, endIndex), + rangeLabel: attributes.rangeLabel?.trim() || "line", + text: extractReviewCommentText(match[2] ?? ""), + }); + } + return comments; } diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 5e265920be..5841a89165 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -110,6 +110,7 @@ function useMarkdownStyles(): MarkdownStyleSets { const codeBg = useThemeColor("--color-md-code-bg"); const codeText = useThemeColor("--color-md-code-text"); const hrColor = useThemeColor("--color-md-hr"); + const userBodyColor = useThemeColor("--color-user-bubble-foreground"); const userCodeBg = useThemeColor("--color-md-user-code-bg"); const userCodeText = useThemeColor("--color-md-user-code-text"); const userFenceBg = useThemeColor("--color-md-user-fence-bg"); @@ -124,6 +125,7 @@ function useMarkdownStyles(): MarkdownStyleSets { const markdownCodeBg = toMarkdownThemeColor(codeBg); const markdownCodeText = toMarkdownThemeColor(codeText); const markdownHrColor = toMarkdownThemeColor(hrColor); + const markdownUserBodyColor = toMarkdownThemeColor(userBodyColor); const markdownUserCodeBg = toMarkdownThemeColor(userCodeBg); const markdownUserCodeText = toMarkdownThemeColor(userCodeText); const markdownUserFenceBg = toMarkdownThemeColor(userFenceBg); @@ -181,9 +183,17 @@ function useMarkdownStyles(): MarkdownStyleSets { list: { marginTop: 4, marginBottom: 4 }, list_item: { marginTop: 0, marginBottom: 4 }, task_list_item: { marginTop: 0, marginBottom: 4 }, - bold: { fontWeight: "700", color: markdownStrongColor, fontFamily: "DMSans_700Bold" }, + text: { lineHeight: 22 }, + bold: { + fontWeight: "700", + color: markdownStrongColor, + fontFamily: "DMSans_700Bold", + }, italic: { fontStyle: "italic" }, - link: { color: markdownLinkColor, textDecorationLine: "underline" as const }, + link: { + color: markdownLinkColor, + textDecorationLine: "underline" as const, + }, blockquote: { borderLeftWidth: 3, borderLeftColor: markdownBlockquoteBorder, @@ -258,6 +268,9 @@ function useMarkdownStyles(): MarkdownStyleSets { ...baseTheme, colors: { ...baseTheme.colors, + text: markdownUserBodyColor, + heading: markdownUserBodyColor, + link: markdownUserBodyColor, code: markdownUserCodeText, codeBackground: markdownUserCodeBg, border: markdownUserFenceBg, @@ -266,6 +279,19 @@ function useMarkdownStyles(): MarkdownStyleSets { const userStyles: NodeStyleOverrides = { ...baseStyles, paragraph: { marginTop: 0, marginBottom: 0 }, + bold: { + fontWeight: "700", + color: markdownUserBodyColor, + fontFamily: "DMSans_700Bold", + }, + heading: { + ...baseStyles.heading, + color: markdownUserBodyColor, + }, + link: { + color: markdownUserBodyColor, + textDecorationLine: "underline" as const, + }, }; const assistantTheme: PartialMarkdownTheme = { @@ -312,6 +338,7 @@ function useMarkdownStyles(): MarkdownStyleSets { hrColor, linkColor, strongColor, + userBodyColor, userCodeBg, userCodeText, userFenceBg, @@ -328,11 +355,12 @@ function renderFeedEntry( readonly onToggleWorkGroup: (groupId: string) => void; readonly onPressImage: (uri: string, headers?: Record) => void; readonly iconSubtleColor: string | import("react-native").ColorValue; + readonly userBubbleColor: string | import("react-native").ColorValue; readonly markdownStyles: MarkdownStyleSets; }, ) { const entry = info.item; - const { markdownStyles, iconSubtleColor } = props; + const { markdownStyles, iconSubtleColor, userBubbleColor } = props; if (entry.type === "message") { const { message } = entry; @@ -344,7 +372,10 @@ function renderFeedEntry( if (isUser) { return ( - + {message.text.trim().length > 0 ? ( ); })} - + {timestampLabel} @@ -427,7 +458,7 @@ function renderFeedEntry( ); })} - + {timestampLabel} @@ -437,18 +468,21 @@ function renderFeedEntry( if (entry.type === "queued-message") { return ( - - + + {entry.queuedMessage.text} {entry.queuedMessage.attachments.length > 0 ? ( - + {entry.queuedMessage.attachments.length} image {entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached ) : null} - + {entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`} @@ -537,6 +571,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; const iconSubtleColor = useThemeColor("--color-icon-subtle"); + const userBubbleColor = useThemeColor("--color-user-bubble"); const markdownStyles = useMarkdownStyles(); useEffect(() => { @@ -599,12 +634,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onToggleWorkGroup, onPressImage, iconSubtleColor, + userBubbleColor, markdownStyles, }), [ copiedRowId, expandedWorkGroups, iconSubtleColor, + userBubbleColor, markdownStyles, onCopyWorkRow, onPressImage, @@ -652,7 +689,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { keyboardShouldPersistTaps="handled" estimatedItemSize={80} initialScrollAtEnd - maintainScrollAtEnd={{ on: { layout: true, itemLayout: true, dataChange: true } }} + maintainScrollAtEnd={{ + on: { layout: true, itemLayout: true, dataChange: true }, + }} maintainScrollAtEndThreshold={0.1} refreshing={props.refreshing ?? false} onRefresh={props.onRefresh} diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx index 29e78ebc9c..bddd5ef629 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx @@ -171,6 +171,7 @@ async function mountTerminalViewport(props: { threadRef: ReturnType; drawerBackgroundColor?: string; drawerTextColor?: string; + runtimeEnv?: Record; }) { const drawer = document.createElement("div"); drawer.className = "thread-terminal-drawer"; @@ -194,6 +195,7 @@ async function mountTerminalViewport(props: { terminalId="term-1" terminalLabel="Terminal" cwd="/repo/project" + {...(props.runtimeEnv ? { runtimeEnv: props.runtimeEnv } : {})} onSessionExited={() => undefined} onAddTerminalContext={() => undefined} focusRequestId={0} @@ -206,7 +208,10 @@ async function mountTerminalViewport(props: { ); return { - rerender: async (nextProps: { threadRef: ReturnType }) => { + rerender: async (nextProps: { + threadRef: ReturnType; + runtimeEnv?: Record; + }) => { await screen.rerender( undefined} onAddTerminalContext={() => undefined} focusRequestId={0} @@ -259,6 +265,47 @@ describe("TerminalViewport", () => { } }); + it("renders and attaches the terminal without the desktop local API", async () => { + const environment = createEnvironmentApi(); + environmentApiById.set("environment-a", environment); + readLocalApiMock.mockReturnValueOnce(undefined); + + const mounted = await mountTerminalViewport({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + }); + + try { + await vi.waitFor(() => { + expect(environment.terminal.attach).toHaveBeenCalledTimes(1); + }); + expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps the terminal mounted when xterm fit runs before dimensions are ready", async () => { + const environment = createEnvironmentApi(); + environmentApiById.set("environment-a", environment); + fitAddonFitSpy.mockImplementationOnce(() => { + throw new TypeError("Cannot read properties of undefined (reading 'dimensions')"); + }); + + const mounted = await mountTerminalViewport({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + }); + + try { + await vi.waitFor(() => { + expect(environment.terminal.attach).toHaveBeenCalledTimes(1); + }); + expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); + expect(fitAddonFitSpy).toHaveBeenCalled(); + } finally { + await mounted.cleanup(); + } + }); + it("reattaches the terminal when the scoped thread reference changes", async () => { const environmentA = createEnvironmentApi(); const environmentB = createEnvironmentApi(); @@ -313,6 +360,34 @@ describe("TerminalViewport", () => { } }); + it("does not reattach when runtime env contents are unchanged but object identity changes", async () => { + const environment = createEnvironmentApi(); + environmentApiById.set("environment-a", environment); + + const mounted = await mountTerminalViewport({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + runtimeEnv: { PATH: "/usr/bin", T3: "1" }, + }); + + try { + await vi.waitFor(() => { + expect(environment.terminal.attach).toHaveBeenCalledTimes(1); + }); + + await mounted.rerender({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + runtimeEnv: { T3: "1", PATH: "/usr/bin" }, + }); + + await vi.waitFor(() => { + expect(environment.terminal.attach).toHaveBeenCalledTimes(1); + }); + expect(terminalDisposeSpy).not.toHaveBeenCalled(); + } finally { + await mounted.cleanup(); + } + }); + it("uses the drawer surface colors for the terminal theme", async () => { const environment = createEnvironmentApi(); environmentApiById.set("environment-a", environment); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 7d0fd29723..48fb9f0281 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -75,6 +75,24 @@ function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnap } } +function fitTerminalSafely(fitAddon: FitAddon): boolean { + try { + fitAddon.fit(); + return true; + } catch { + return false; + } +} + +function runtimeEnvSignature(runtimeEnv: Record | undefined): string { + if (!runtimeEnv) return ""; + return JSON.stringify( + Object.entries(runtimeEnv) + .filter(([key, value]) => key.length > 0 && typeof value === "string") + .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)), + ); +} + function normalizeComputedColor(value: string | null | undefined, fallback: string): string { const normalizedValue = value?.trim().toLowerCase(); if ( @@ -283,6 +301,7 @@ export function TerminalViewport({ const selectionActionOpenRef = useRef(false); const selectionActionTimerRef = useRef(null); const keybindingsRef = useRef(keybindings); + const runtimeEnvKey = useMemo(() => runtimeEnvSignature(runtimeEnv), [runtimeEnv]); const handleSessionExited = useEffectEvent(() => { onSessionExited(); }); @@ -302,7 +321,7 @@ export function TerminalViewport({ let disposed = false; const api = readEnvironmentApi(environmentId); const localApi = readLocalApi(); - if (!api || !localApi) return; + if (!api) return; const fitAddon = new FitAddon(); const terminal = new Terminal({ @@ -315,7 +334,7 @@ export function TerminalViewport({ }); terminal.loadAddon(fitAddon); terminal.open(mount); - fitAddon.fit(); + fitTerminalSafely(fitAddon); terminalRef.current = terminal; fitAddonRef.current = fitAddon; @@ -369,6 +388,10 @@ export function TerminalViewport({ }; const showSelectionAction = async () => { + if (!localApi) { + clearSelectionAction(); + return; + } if (selectionActionOpenRef.current) { return; } @@ -479,6 +502,10 @@ export function TerminalViewport({ const latestTerminal = terminalRef.current; if (!latestTerminal) return; + if (!localApi) { + writeSystemMessage(latestTerminal, "Opening links is unavailable in this browser."); + return; + } if (match.kind === "url") { void localApi.shell.openExternal(match.text).catch((error: unknown) => { @@ -630,7 +657,7 @@ export function TerminalViewport({ const activeTerminal = terminalRef.current; const activeFitAddon = fitAddonRef.current; if (!activeTerminal || !activeFitAddon) return; - activeFitAddon.fit(); + fitTerminalSafely(activeFitAddon); unsubscribeAttach = attachTerminalSession({ environmentId, client: api, @@ -664,7 +691,7 @@ export function TerminalViewport({ if (!activeTerminal || !activeFitAddon) return; const wasAtBottom = activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY; - activeFitAddon.fit(); + fitTerminalSafely(activeFitAddon); if (wasAtBottom) { activeTerminal.scrollToBottom(); } @@ -700,7 +727,7 @@ export function TerminalViewport({ // autoFocus is intentionally omitted; // it is only read at mount time and must not trigger terminal teardown/recreation. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [cwd, environmentId, runtimeEnv, terminalId, threadId, worktreePath]); + }, [cwd, environmentId, runtimeEnvKey, terminalId, threadId, worktreePath]); useEffect(() => { if (!autoFocus) return; @@ -721,7 +748,7 @@ export function TerminalViewport({ if (!api || !terminal || !fitAddon) return; const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY; const frame = window.requestAnimationFrame(() => { - fitAddon.fit(); + fitTerminalSafely(fitAddon); if (wasAtBottom) { terminal.scrollToBottom(); } diff --git a/apps/web/src/lib/contextWindow.test.ts b/apps/web/src/lib/contextWindow.test.ts index 70479b3fa4..8cb6a7f582 100644 --- a/apps/web/src/lib/contextWindow.test.ts +++ b/apps/web/src/lib/contextWindow.test.ts @@ -44,6 +44,23 @@ describe("contextWindow", () => { expect(snapshot).toBeNull(); }); + it("keeps valid zero-usage snapshots", () => { + const snapshot = deriveLatestContextWindowSnapshot([ + makeActivity("activity-1", "context-window.updated", { + usedTokens: 0, + maxTokens: 100_000, + }), + ]); + + expect(snapshot).toMatchObject({ + usedTokens: 0, + maxTokens: 100_000, + remainingTokens: 100_000, + usedPercentage: 0, + remainingPercentage: 100, + }); + }); + it("formats compact token counts", () => { expect(formatContextWindowTokens(999)).toBe("999"); expect(formatContextWindowTokens(1400)).toBe("1.4k"); diff --git a/apps/web/src/lib/contextWindow.ts b/apps/web/src/lib/contextWindow.ts index f668135a13..02cf262191 100644 --- a/apps/web/src/lib/contextWindow.ts +++ b/apps/web/src/lib/contextWindow.ts @@ -36,7 +36,7 @@ export function deriveLatestContextWindowSnapshot( const payload = asRecord(activity.payload); const usedTokens = asFiniteNumber(payload?.usedTokens); - if (usedTokens === null || usedTokens <= 0) { + if (usedTokens === null || usedTokens < 0) { continue; } diff --git a/apps/web/src/lib/lruCache.test.ts b/apps/web/src/lib/lruCache.test.ts index 7f53db2607..2605081381 100644 --- a/apps/web/src/lib/lruCache.test.ts +++ b/apps/web/src/lib/lruCache.test.ts @@ -40,4 +40,13 @@ describe("LRUCache", () => { expect(cache.get("b")).toBe("B"); expect(cache.get("c")).toBe("C"); }); + + it("does not cache entries larger than the memory budget", () => { + const cache = new LRUCache(2, 25); + cache.set("a", "A", 10); + cache.set("oversized", "X", 30); + + expect(cache.get("a")).toBe("A"); + expect(cache.get("oversized")).toBeNull(); + }); }); diff --git a/apps/web/src/lib/lruCache.ts b/apps/web/src/lib/lruCache.ts index 141c796e73..8fadcacedd 100644 --- a/apps/web/src/lib/lruCache.ts +++ b/apps/web/src/lib/lruCache.ts @@ -29,6 +29,10 @@ export class LRUCache { this.cache.delete(key); } + if (approximateSize > this.maxMemoryBytes) { + return; + } + this.evictIfNeeded(approximateSize); this.cache.set(key, { value, approximateSize }); this.totalSize += approximateSize; diff --git a/apps/web/src/lib/threadSort.test.ts b/apps/web/src/lib/threadSort.test.ts index 2a69357c49..88e9617862 100644 --- a/apps/web/src/lib/threadSort.test.ts +++ b/apps/web/src/lib/threadSort.test.ts @@ -114,6 +114,31 @@ describe("sortThreads", () => { ]); }); + it("falls back to createdAt when updatedAt is invalid", () => { + const sorted = sortThreads( + [ + makeThread({ + id: ThreadId.make("thread-1"), + createdAt: "2026-03-09T10:00:00.000Z", + updatedAt: "invalid-date" as never, + messages: [], + }), + makeThread({ + id: ThreadId.make("thread-2"), + createdAt: "2026-03-09T09:00:00.000Z", + updatedAt: "2026-03-09T09:30:00.000Z", + messages: [], + }), + ], + "updated_at", + ); + + expect(sorted.map((thread) => thread.id)).toEqual([ + ThreadId.make("thread-1"), + ThreadId.make("thread-2"), + ]); + }); + it("falls back to id ordering when threads have no sortable timestamps", () => { const sorted = sortThreads( [ @@ -162,6 +187,29 @@ describe("sortThreads", () => { ]); }); + it("uses updatedAt as a fallback for created_at sorting when createdAt is invalid", () => { + const sorted = sortThreads( + [ + makeThread({ + id: ThreadId.make("thread-1"), + createdAt: "invalid-date" as never, + updatedAt: "2026-03-09T10:05:00.000Z", + }), + makeThread({ + id: ThreadId.make("thread-2"), + createdAt: "2026-03-09T10:00:00.000Z", + updatedAt: "2026-03-09T10:10:00.000Z", + }), + ], + "created_at", + ); + + expect(sorted.map((thread) => thread.id)).toEqual([ + ThreadId.make("thread-1"), + ThreadId.make("thread-2"), + ]); + }); + it("returns the latest active thread for a project", () => { const latestThread = getLatestThreadForProject( [ diff --git a/apps/web/src/lib/threadSort.ts b/apps/web/src/lib/threadSort.ts index 837a7788d3..de8b22e93c 100644 --- a/apps/web/src/lib/threadSort.ts +++ b/apps/web/src/lib/threadSort.ts @@ -13,6 +13,17 @@ export function toSortableTimestamp(iso: string | undefined): number | null { return Number.isFinite(ms) ? ms : null; } +function getFirstSortableTimestamp(...values: Array): 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; @@ -34,7 +45,7 @@ function getLatestUserMessageTimestamp(thread: ThreadSortInput): number { return latestUserMessageTimestamp; } - return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY; + return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY; } export function getThreadSortTimestamp( @@ -42,7 +53,9 @@ export function getThreadSortTimestamp( sortOrder: SidebarThreadSortOrder | Exclude, ): number { if (sortOrder === "created_at") { - return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY; + return ( + getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY + ); } return getLatestUserMessageTimestamp(thread); }