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
This commit is contained in:
1 parent
5225844b96
commit
7d20cb9e79
18 files changed
+1070
-58
No files matched your search
+20
-10
@@ -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);
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> {
|
||||
guard let data = json.data(using: .utf8) else {
|
||||
return []
|
||||
@@ -718,6 +738,17 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
|
||||
setNeedsDisplayForVisibleBounds()
|
||||
}
|
||||
}
|
||||
var selectedRowIds: Set<String> = [] {
|
||||
didSet {
|
||||
setNeedsDisplayForVisibleBounds()
|
||||
}
|
||||
}
|
||||
var collapsedCommentIds: Set<String> = [] {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<NativeReviewDiffWordDiffRange>;
|
||||
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<Record<string, unknown>>) => 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<NativeReviewDiffViewProps> | undefined;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import Stack from "expo-router/stack";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
type NativeSyntheticEvent,
|
||||
Text as NativeText,
|
||||
@@ -36,7 +38,16 @@ import {
|
||||
type ReviewParsedDiff,
|
||||
type ReviewRenderableFile,
|
||||
} from "./reviewModel";
|
||||
import { countReviewCommentContexts } from "./reviewCommentSelection";
|
||||
import {
|
||||
buildReviewCommentTarget,
|
||||
clearReviewCommentTarget,
|
||||
countReviewCommentContexts,
|
||||
formatReviewSelectedRangeLabel,
|
||||
getSelectedReviewCommentLines,
|
||||
parseReviewInlineComments,
|
||||
setReviewCommentTarget,
|
||||
useReviewCommentTarget,
|
||||
} from "./reviewCommentSelection";
|
||||
import { markReviewEvent, measureReviewWork } from "./reviewPerf";
|
||||
import {
|
||||
highlightNativeReviewDiffVisibleRows,
|
||||
@@ -49,11 +60,18 @@ import {
|
||||
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
|
||||
NATIVE_REVIEW_DIFF_ROW_HEIGHT,
|
||||
NATIVE_REVIEW_DIFF_STYLE,
|
||||
type NativeReviewDiffCommentTarget,
|
||||
} from "./nativeReviewDiffAdapter";
|
||||
|
||||
const IOS_NAV_BAR_HEIGHT = 44;
|
||||
const REVIEW_HEADER_SPACING = 0;
|
||||
|
||||
interface PendingNativeCommentSelection extends NativeReviewDiffCommentTarget {
|
||||
readonly sectionId: string;
|
||||
readonly sectionTitle: string;
|
||||
readonly rowId: string;
|
||||
}
|
||||
|
||||
function isReviewDiffDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
@@ -116,6 +134,20 @@ function getValidReviewExpandedFileIds(
|
||||
return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));
|
||||
}
|
||||
|
||||
function areStringArraysEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {
|
||||
if (left.length !== right.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
if (left[index] !== right[index]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
|
||||
return (
|
||||
<View className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40">
|
||||
@@ -129,7 +161,66 @@ const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string
|
||||
);
|
||||
});
|
||||
|
||||
function ReviewSelectionActionBar(props: {
|
||||
readonly bottomInset: number;
|
||||
readonly title: string | null;
|
||||
readonly onOpenComment: (() => void) | null;
|
||||
readonly onClear: () => void;
|
||||
}) {
|
||||
if (!props.title) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<SymbolView
|
||||
name={props.onOpenComment ? "text.bubble" : "line.3.horizontal.decrease.circle"}
|
||||
size={16}
|
||||
tintColor="#ffffff"
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="text-[15px] font-t3-bold text-white">{props.title}</Text>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: 18,
|
||||
right: 18,
|
||||
bottom: Math.max(props.bottomInset, 10) + 18,
|
||||
flexDirection: "row",
|
||||
justifyContent: "center",
|
||||
gap: 10,
|
||||
}}
|
||||
>
|
||||
{props.onOpenComment ? (
|
||||
<Pressable
|
||||
className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5"
|
||||
onPress={props.onOpenComment}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
) : (
|
||||
<View className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5">
|
||||
{content}
|
||||
</View>
|
||||
)}
|
||||
|
||||
<Pressable
|
||||
className="h-12 w-12 items-center justify-center rounded-full bg-blue-600"
|
||||
onPress={props.onClear}
|
||||
>
|
||||
<SymbolView name="xmark" size={16} tintColor="#ffffff" type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReviewSheet() {
|
||||
const { push } = useRouter();
|
||||
const insets = useSafeAreaInsets();
|
||||
const colorScheme = useColorScheme();
|
||||
const headerForeground = String(useThemeColor("--color-foreground"));
|
||||
@@ -151,7 +242,12 @@ export function ReviewSheet() {
|
||||
const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<
|
||||
Record<string, ReadonlyArray<string>>
|
||||
>({});
|
||||
const [nativeTokensPatchJson, setNativeTokensPatchJson] = useState(
|
||||
const [pendingNativeCommentSelection, setPendingNativeCommentSelection] =
|
||||
useState<PendingNativeCommentSelection | null>(null);
|
||||
const [collapsedCommentIds, setCollapsedCommentIds] = useState<ReadonlySet<string>>(
|
||||
() => new Set(),
|
||||
);
|
||||
const [nativeTokensPatchJson, setNativeTokensPatchJson] = useState(() =>
|
||||
JSON.stringify({ resetKey: "", tokensByRowId: {} }),
|
||||
);
|
||||
const selectedTheme = colorScheme === "dark" ? "dark" : "light";
|
||||
@@ -159,6 +255,7 @@ export function ReviewSheet() {
|
||||
const nativeVisibleRangeRef = useRef({ firstRowIndex: 0, lastRowIndex: 80 });
|
||||
const nativeVisibleChunkIndexRef = useRef(0);
|
||||
const [nativeVisibleHighlightRequest, setNativeVisibleHighlightRequest] = useState(0);
|
||||
const activeCommentTarget = useReviewCommentTarget();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
|
||||
const cwd = selectedThreadCwd;
|
||||
@@ -205,9 +302,26 @@ export function ReviewSheet() {
|
||||
);
|
||||
const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);
|
||||
const NativeReviewDiffView = resolveNativeReviewDiffView()!;
|
||||
const inlineReviewComments = useMemo(
|
||||
() => parseReviewInlineComments(draftMessage),
|
||||
[draftMessage],
|
||||
);
|
||||
const selectedSectionInlineComments = useMemo(
|
||||
() =>
|
||||
selectedSection
|
||||
? inlineReviewComments.filter((comment) => comment.sectionId === selectedSection.id)
|
||||
: [],
|
||||
[inlineReviewComments, selectedSection],
|
||||
);
|
||||
const nativeReviewDiffData = useMemo(
|
||||
() => measureReviewWork("build-native-diff-data", () => buildNativeReviewDiffData(parsedDiff)),
|
||||
[parsedDiff],
|
||||
() =>
|
||||
measureReviewWork("build-native-diff-data", () =>
|
||||
buildNativeReviewDiffData({
|
||||
parsedDiff,
|
||||
comments: selectedSectionInlineComments,
|
||||
}),
|
||||
),
|
||||
[parsedDiff, selectedSectionInlineComments],
|
||||
);
|
||||
const nativeReviewDiffTheme = useMemo(
|
||||
() => createNativeReviewDiffTheme(selectedTheme),
|
||||
@@ -217,6 +331,10 @@ export function ReviewSheet() {
|
||||
() => JSON.stringify(nativeReviewDiffData.rows),
|
||||
[nativeReviewDiffData.rows],
|
||||
);
|
||||
const collapsedCommentIdsJson = useMemo(
|
||||
() => JSON.stringify(Array.from(collapsedCommentIds)),
|
||||
[collapsedCommentIds],
|
||||
);
|
||||
const nativeThemeJson = useMemo(
|
||||
() => JSON.stringify(nativeReviewDiffTheme),
|
||||
[nativeReviewDiffTheme],
|
||||
@@ -301,15 +419,80 @@ export function ReviewSheet() {
|
||||
}
|
||||
|
||||
const expandedFileIdSet = new Set(expandedFileIds);
|
||||
return parsedDiff.files
|
||||
.filter((file) => !expandedFileIdSet.has(file.id))
|
||||
.map((file) => file.id);
|
||||
return parsedDiff.files.reduce<string[]>((fileIds, file) => {
|
||||
if (!expandedFileIdSet.has(file.id)) {
|
||||
fileIds.push(file.id);
|
||||
}
|
||||
return fileIds;
|
||||
}, []);
|
||||
}, [expandedFileIds, parsedDiff]);
|
||||
const nativeCollapsedFileIdsJson = useMemo(
|
||||
() => JSON.stringify(nativeCollapsedFileIds),
|
||||
[nativeCollapsedFileIds],
|
||||
);
|
||||
const nativeViewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
|
||||
const openReviewCommentSheet = useCallback(() => {
|
||||
if (!environmentId || !threadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
push({
|
||||
pathname: "/threads/[environmentId]/[threadId]/review-comment",
|
||||
params: { environmentId, threadId },
|
||||
});
|
||||
}, [environmentId, push, threadId]);
|
||||
const selectedNativeRowIds = useMemo(() => {
|
||||
if (
|
||||
activeCommentTarget &&
|
||||
activeCommentTarget.sectionTitle === selectedSection?.title &&
|
||||
activeCommentTarget.startIndex !== activeCommentTarget.endIndex
|
||||
) {
|
||||
return getSelectedReviewCommentLines(activeCommentTarget).flatMap((line) => {
|
||||
const rowId = nativeReviewDiffData.rowIdByCommentLineId.get(line.id);
|
||||
return rowId ? [rowId] : [];
|
||||
});
|
||||
}
|
||||
|
||||
return pendingNativeCommentSelection ? [pendingNativeCommentSelection.rowId] : [];
|
||||
}, [
|
||||
activeCommentTarget,
|
||||
nativeReviewDiffData.rowIdByCommentLineId,
|
||||
pendingNativeCommentSelection,
|
||||
selectedSection?.title,
|
||||
]);
|
||||
const selectedNativeRowIdsJson = useMemo(
|
||||
() => JSON.stringify(selectedNativeRowIds),
|
||||
[selectedNativeRowIds],
|
||||
);
|
||||
const selectionAction = useMemo(() => {
|
||||
if (
|
||||
activeCommentTarget &&
|
||||
activeCommentTarget.sectionTitle === selectedSection?.title &&
|
||||
activeCommentTarget.startIndex !== activeCommentTarget.endIndex
|
||||
) {
|
||||
return {
|
||||
title: `Comment on ${formatReviewSelectedRangeLabel(activeCommentTarget)}`,
|
||||
onOpenComment: openReviewCommentSheet,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
pendingNativeCommentSelection &&
|
||||
pendingNativeCommentSelection.sectionTitle === selectedSection?.title
|
||||
) {
|
||||
return {
|
||||
title: "Select range end",
|
||||
onOpenComment: null,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [
|
||||
activeCommentTarget,
|
||||
openReviewCommentSheet,
|
||||
pendingNativeCommentSelection,
|
||||
selectedSection?.title,
|
||||
]);
|
||||
const loadGitDiffs = useCallback(async () => {
|
||||
if (!cwd) {
|
||||
return;
|
||||
@@ -431,11 +614,7 @@ export function ReviewSheet() {
|
||||
|
||||
updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {
|
||||
const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
|
||||
if (
|
||||
existing !== undefined &&
|
||||
validIds.length === existing.length &&
|
||||
validIds.every((id, index) => id === existing[index])
|
||||
) {
|
||||
if (existing !== undefined && areStringArraysEqual(validIds, existing)) {
|
||||
return existing;
|
||||
}
|
||||
return validIds;
|
||||
@@ -452,6 +631,17 @@ export function ReviewSheet() {
|
||||
}
|
||||
}, [nativeReviewDiffData.rows.length, nativeTokensResetKey]);
|
||||
|
||||
useEffect(() => {
|
||||
clearReviewCommentTarget();
|
||||
setPendingNativeCommentSelection(null);
|
||||
}, [selectedSection?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeCommentTarget === null) {
|
||||
setPendingNativeCommentSelection(null);
|
||||
}
|
||||
}, [activeCommentTarget]);
|
||||
|
||||
useEffect(() => {
|
||||
if (parsedDiff.kind !== "files" || nativeReviewDiffData.rows.length === 0) {
|
||||
return;
|
||||
@@ -676,6 +866,97 @@ export function ReviewSheet() {
|
||||
[handleToggleViewedFile],
|
||||
);
|
||||
|
||||
const handleNativePressLine = useCallback(
|
||||
(
|
||||
event: NativeSyntheticEvent<{
|
||||
readonly rowId?: string;
|
||||
readonly gesture?: "tap" | "longPress";
|
||||
}>,
|
||||
) => {
|
||||
if (!selectedSection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { rowId, gesture } = event.nativeEvent;
|
||||
if (!rowId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = nativeReviewDiffData.commentTargetsByRowId.get(rowId);
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (gesture === "longPress") {
|
||||
clearReviewCommentTarget();
|
||||
setPendingNativeCommentSelection({
|
||||
...target,
|
||||
sectionId: selectedSection.id,
|
||||
sectionTitle: selectedSection.title,
|
||||
rowId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
pendingNativeCommentSelection &&
|
||||
pendingNativeCommentSelection.sectionTitle === selectedSection.title &&
|
||||
pendingNativeCommentSelection.filePath === target.filePath
|
||||
) {
|
||||
setReviewCommentTarget(
|
||||
buildReviewCommentTarget(
|
||||
{
|
||||
sectionTitle: pendingNativeCommentSelection.sectionTitle,
|
||||
sectionId: pendingNativeCommentSelection.sectionId,
|
||||
filePath: pendingNativeCommentSelection.filePath,
|
||||
lines: pendingNativeCommentSelection.lines,
|
||||
},
|
||||
pendingNativeCommentSelection.lineIndex,
|
||||
target.lineIndex,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setPendingNativeCommentSelection(null);
|
||||
setReviewCommentTarget({
|
||||
sectionTitle: selectedSection.title,
|
||||
sectionId: selectedSection.id,
|
||||
filePath: target.filePath,
|
||||
lines: target.lines,
|
||||
startIndex: target.lineIndex,
|
||||
endIndex: target.lineIndex,
|
||||
});
|
||||
openReviewCommentSheet();
|
||||
},
|
||||
[
|
||||
nativeReviewDiffData.commentTargetsByRowId,
|
||||
openReviewCommentSheet,
|
||||
pendingNativeCommentSelection,
|
||||
selectedSection,
|
||||
],
|
||||
);
|
||||
|
||||
const handleNativeToggleComment = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly commentId?: string }>) => {
|
||||
const { commentId } = event.nativeEvent;
|
||||
if (!commentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCollapsedCommentIds((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(commentId)) {
|
||||
next.delete(commentId);
|
||||
} else {
|
||||
next.add(commentId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const parsedDiffNotice =
|
||||
parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
|
||||
|
||||
@@ -851,15 +1132,19 @@ export function ReviewSheet() {
|
||||
style={StyleSheet.absoluteFillObject}
|
||||
appearanceScheme={selectedTheme}
|
||||
collapsedFileIdsJson={nativeCollapsedFileIdsJson}
|
||||
collapsedCommentIdsJson={collapsedCommentIdsJson}
|
||||
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
|
||||
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
|
||||
rowsJson={nativeRowsJson}
|
||||
selectedRowIdsJson={selectedNativeRowIdsJson}
|
||||
styleJson={nativeStyleJson}
|
||||
themeJson={nativeThemeJson}
|
||||
tokensPatchJson={nativeTokensPatchJson}
|
||||
tokensResetKey={nativeTokensResetKey}
|
||||
viewedFileIdsJson={nativeViewedFileIdsJson}
|
||||
onDebug={handleNativeDebug}
|
||||
onPressLine={handleNativePressLine}
|
||||
onToggleComment={handleNativeToggleComment}
|
||||
onToggleFile={handleNativeToggleFile}
|
||||
onToggleViewedFile={handleNativeToggleViewedFile}
|
||||
/>
|
||||
@@ -868,14 +1153,16 @@ export function ReviewSheet() {
|
||||
) : (
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
contentInset={{ top: topContentInset }}
|
||||
contentInset={{ top: topContentInset, bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentOffset={{ x: 0, y: -topContentInset }}
|
||||
scrollIndicatorInsets={{ top: topContentInset }}
|
||||
scrollIndicatorInsets={{
|
||||
top: topContentInset,
|
||||
bottom: Math.max(insets.bottom, 18) + 18,
|
||||
}}
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{
|
||||
paddingTop: REVIEW_HEADER_SPACING,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
}}
|
||||
>
|
||||
{listHeader}
|
||||
@@ -912,6 +1199,15 @@ export function ReviewSheet() {
|
||||
) : null}
|
||||
</ScrollView>
|
||||
)}
|
||||
<ReviewSelectionActionBar
|
||||
bottomInset={insets.bottom}
|
||||
title={selectionAction?.title ?? null}
|
||||
onOpenComment={selectionAction?.onOpenComment ?? null}
|
||||
onClear={() => {
|
||||
clearReviewCommentTarget();
|
||||
setPendingNativeCommentSelection(null);
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -27,7 +27,21 @@ describe("buildNativeReviewDiffData", () => {
|
||||
"native-adapter-test",
|
||||
);
|
||||
|
||||
const data = buildNativeReviewDiffData(parsed);
|
||||
const data = buildNativeReviewDiffData({
|
||||
parsedDiff: parsed,
|
||||
comments: [
|
||||
{
|
||||
id: "comment-1",
|
||||
sectionId: "dirty",
|
||||
sectionTitle: "Working tree",
|
||||
filePath: "apps/demo/src/main.ts",
|
||||
startIndex: 1,
|
||||
endIndex: 1,
|
||||
rangeLabel: "+2",
|
||||
text: "Please keep this configurable.",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(data.additions).toBe(1);
|
||||
expect(data.deletions).toBe(1);
|
||||
@@ -70,6 +84,13 @@ describe("buildNativeReviewDiffData", () => {
|
||||
content: "const retryLimit = 4;",
|
||||
wordDiffRanges: [{ start: 19, end: 20 }],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "comment",
|
||||
id: "comment-1",
|
||||
filePath: "apps/demo/src/main.ts",
|
||||
commentText: "Please keep this configurable.",
|
||||
commentRangeLabel: "+2",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "file",
|
||||
filePath: "apps/demo/src/new.ts",
|
||||
@@ -86,5 +107,22 @@ describe("buildNativeReviewDiffData", () => {
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const changedLine = data.rows.find(
|
||||
(row) =>
|
||||
row.kind === "line" && row.change === "add" && row.content === "const retryLimit = 4;",
|
||||
);
|
||||
expect(changedLine?.id).toBeTruthy();
|
||||
const changedTarget = data.commentTargetsByRowId.get(changedLine?.id ?? "");
|
||||
expect(changedTarget).toMatchObject({
|
||||
filePath: "apps/demo/src/main.ts",
|
||||
lineIndex: 1,
|
||||
lines: expect.arrayContaining([
|
||||
expect.objectContaining({ content: "const retryLimit = 2;" }),
|
||||
expect.objectContaining({ content: "const retryLimit = 4;" }),
|
||||
]),
|
||||
});
|
||||
const changedCommentLine = changedTarget?.lines[changedTarget.lineIndex];
|
||||
expect(data.rowIdByCommentLineId.get(changedCommentLine?.id ?? "")).toBe(changedLine?.id);
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
type ReviewRenderableFile,
|
||||
type ReviewRenderableLineRow,
|
||||
} from "./reviewModel";
|
||||
import type { ReviewInlineComment } from "./reviewCommentSelection";
|
||||
|
||||
const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
|
||||
const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
|
||||
@@ -57,10 +58,23 @@ export const NATIVE_REVIEW_DIFF_STYLE = {
|
||||
export interface NativeReviewDiffData {
|
||||
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
|
||||
readonly files: ReadonlyArray<NativeReviewDiffFile>;
|
||||
readonly commentTargetsByRowId: ReadonlyMap<string, NativeReviewDiffCommentTarget>;
|
||||
readonly rowIdByCommentLineId: ReadonlyMap<string, string>;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffCommentTarget {
|
||||
readonly filePath: string;
|
||||
readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
|
||||
readonly lineIndex: number;
|
||||
}
|
||||
|
||||
export interface BuildNativeReviewDiffDataInput {
|
||||
readonly parsedDiff: ReviewParsedDiff;
|
||||
readonly comments?: ReadonlyArray<ReviewInlineComment>;
|
||||
}
|
||||
|
||||
export function createNativeReviewDiffTheme(
|
||||
scheme: TerminalAppearanceScheme,
|
||||
): NativeReviewDiffTheme {
|
||||
@@ -294,7 +308,12 @@ function mapLineRow(
|
||||
};
|
||||
}
|
||||
|
||||
function mapFileRows(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
|
||||
function mapFileRows(
|
||||
file: ReviewRenderableFile,
|
||||
comments: ReadonlyArray<ReviewInlineComment>,
|
||||
commentTargetsByRowId: Map<string, NativeReviewDiffCommentTarget>,
|
||||
rowIdByCommentLineId: Map<string, string>,
|
||||
): ReadonlyArray<NativeReviewDiffRow> {
|
||||
const rows: NativeReviewDiffRow[] = [
|
||||
{
|
||||
kind: "file",
|
||||
@@ -308,6 +327,24 @@ function mapFileRows(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiff
|
||||
},
|
||||
];
|
||||
|
||||
const lineRows = file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line");
|
||||
const commentsByEndIndex = new Map<number, ReviewInlineComment[]>();
|
||||
comments.forEach((comment) => {
|
||||
if (comment.filePath !== file.path) {
|
||||
return;
|
||||
}
|
||||
const endIndex = Math.min(comment.endIndex, lineRows.length - 1);
|
||||
if (endIndex < 0) {
|
||||
return;
|
||||
}
|
||||
const existing = commentsByEndIndex.get(endIndex);
|
||||
if (existing) {
|
||||
existing.push(comment);
|
||||
return;
|
||||
}
|
||||
commentsByEndIndex.set(endIndex, [comment]);
|
||||
});
|
||||
let lineIndex = 0;
|
||||
file.rows.forEach((row, rowIndex) => {
|
||||
if (row.kind === "hunk") {
|
||||
rows.push({
|
||||
@@ -319,18 +356,48 @@ function mapFileRows(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiff
|
||||
return;
|
||||
}
|
||||
|
||||
rows.push(mapLineRow(file, row, rowIndex));
|
||||
const nativeRow = mapLineRow(file, row, rowIndex);
|
||||
rows.push(nativeRow);
|
||||
rowIdByCommentLineId.set(row.id, nativeRow.id);
|
||||
commentTargetsByRowId.set(nativeRow.id, {
|
||||
filePath: file.path,
|
||||
lines: lineRows,
|
||||
lineIndex,
|
||||
});
|
||||
const commentsForLine = commentsByEndIndex.get(lineIndex) ?? [];
|
||||
for (const comment of commentsForLine) {
|
||||
rows.push({
|
||||
kind: "comment",
|
||||
id: comment.id,
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
commentText: comment.text,
|
||||
commentRangeLabel: comment.rangeLabel,
|
||||
commentSectionTitle: comment.sectionTitle,
|
||||
});
|
||||
}
|
||||
lineIndex += 1;
|
||||
});
|
||||
|
||||
rows.push(...noticeRowsForFile(file));
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData {
|
||||
export function buildNativeReviewDiffData(
|
||||
input: BuildNativeReviewDiffDataInput,
|
||||
): NativeReviewDiffData;
|
||||
export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData;
|
||||
export function buildNativeReviewDiffData(
|
||||
input: ReviewParsedDiff | BuildNativeReviewDiffDataInput,
|
||||
): NativeReviewDiffData {
|
||||
const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input;
|
||||
const comments = "parsedDiff" in input ? (input.comments ?? []) : [];
|
||||
if (parsedDiff.kind !== "files") {
|
||||
return {
|
||||
rows: [],
|
||||
files: [],
|
||||
commentTargetsByRowId: new Map(),
|
||||
rowIdByCommentLineId: new Map(),
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
};
|
||||
@@ -343,11 +410,19 @@ export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeR
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
}));
|
||||
const rows = addNativeWordDiffRanges(parsedDiff.files.flatMap(mapFileRows));
|
||||
const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
|
||||
const rowIdByCommentLineId = new Map<string, string>();
|
||||
const rows = addNativeWordDiffRanges(
|
||||
parsedDiff.files.flatMap((file) =>
|
||||
mapFileRows(file, comments, commentTargetsByRowId, rowIdByCommentLineId),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
rows,
|
||||
files,
|
||||
commentTargetsByRowId,
|
||||
rowIdByCommentLineId,
|
||||
additions: parsedDiff.additions,
|
||||
deletions: parsedDiff.deletions,
|
||||
};
|
||||
|
||||
@@ -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.",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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<ReviewRenderableLineRow>;
|
||||
@@ -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 = /<review_comment\b([^>]*)>\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<ReviewCommentTarget, "sectionTitle" | "filePath" | "lines">,
|
||||
target: Pick<ReviewCommentTarget, "sectionId" | "sectionTitle" | "filePath" | "lines">,
|
||||
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(/</g, "<");
|
||||
}
|
||||
|
||||
function unescapeReviewCommentAttribute(value: string): string {
|
||||
return value
|
||||
.replace(/</g, "<")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/&/g, "&");
|
||||
}
|
||||
|
||||
function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
|
||||
const attributes: Record<string, string> = {};
|
||||
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 [
|
||||
"<review_comment>",
|
||||
[
|
||||
"<review_comment",
|
||||
` sectionId="${escapeReviewCommentAttribute(target.sectionId)}"`,
|
||||
` sectionTitle="${escapeReviewCommentAttribute(target.sectionTitle)}"`,
|
||||
` filePath="${escapeReviewCommentAttribute(target.filePath)}"`,
|
||||
` startIndex="${target.startIndex}"`,
|
||||
` endIndex="${target.endIndex}"`,
|
||||
` rangeLabel="${escapeReviewCommentAttribute(rangeLabel)}"`,
|
||||
">",
|
||||
].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(/<review_comment>/g)).length;
|
||||
return Array.from(value.matchAll(/<review_comment\b/g)).length;
|
||||
}
|
||||
|
||||
export function parseReviewInlineComments(value: string): ReadonlyArray<ReviewInlineComment> {
|
||||
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;
|
||||
}
|
||||
@@ -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<string, string>) => 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 (
|
||||
<View className="mb-3.5 items-end gap-1.5">
|
||||
<View className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[10px] border border-blue-300/50 bg-blue-50/80 px-4 py-4 dark:border-blue-400/20 dark:bg-blue-500/12">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
>
|
||||
{message.text.trim().length > 0 ? (
|
||||
<Markdown
|
||||
options={{ gfm: true }}
|
||||
@@ -372,14 +403,14 @@ function renderFeedEntry(
|
||||
>
|
||||
<Image
|
||||
source={{ uri, ...(headers ? { headers } : {}) }}
|
||||
className="aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
|
||||
className="aspect-[1.3] w-full rounded-[14px] bg-white/15"
|
||||
resizeMode="cover"
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
<Text className="px-1 text-right font-t3-medium text-xs text-neutral-500 dark:text-neutral-500">
|
||||
<Text className="px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{timestampLabel}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -427,7 +458,7 @@ function renderFeedEntry(
|
||||
</TouchableOpacity>
|
||||
);
|
||||
})}
|
||||
<Text className="font-t3-medium text-xs text-neutral-500 dark:text-neutral-500">
|
||||
<Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{timestampLabel}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -437,18 +468,21 @@ function renderFeedEntry(
|
||||
if (entry.type === "queued-message") {
|
||||
return (
|
||||
<View className="mb-3.5 gap-1.5 items-end">
|
||||
<View className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[10px] border border-sky-300/60 bg-sky-100/75 px-4 py-4 dark:border-sky-300/20 dark:bg-sky-400/10">
|
||||
<Text className="font-sans text-[15px] leading-[22px] text-neutral-950 dark:text-neutral-50">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
>
|
||||
<Text className="font-sans text-[15px] leading-[22px] text-white">
|
||||
{entry.queuedMessage.text}
|
||||
</Text>
|
||||
{entry.queuedMessage.attachments.length > 0 ? (
|
||||
<Text className="font-t3-medium text-xs text-neutral-500 dark:text-neutral-500">
|
||||
<Text className="font-t3-medium text-xs text-white/75">
|
||||
{entry.queuedMessage.attachments.length} image
|
||||
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="px-1 text-right font-t3-medium text-xs text-neutral-500 dark:text-neutral-500">
|
||||
<Text className="px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -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}
|
||||
|
||||
@@ -171,6 +171,7 @@ async function mountTerminalViewport(props: {
|
||||
threadRef: ReturnType<typeof scopeThreadRef>;
|
||||
drawerBackgroundColor?: string;
|
||||
drawerTextColor?: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
}) {
|
||||
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<typeof scopeThreadRef> }) => {
|
||||
rerender: async (nextProps: {
|
||||
threadRef: ReturnType<typeof scopeThreadRef>;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
}) => {
|
||||
await screen.rerender(
|
||||
<TerminalViewport
|
||||
threadRef={nextProps.threadRef}
|
||||
@@ -214,6 +219,7 @@ async function mountTerminalViewport(props: {
|
||||
terminalId="term-1"
|
||||
terminalLabel="Terminal"
|
||||
cwd="/repo/project"
|
||||
{...(nextProps.runtimeEnv ? { runtimeEnv: nextProps.runtimeEnv } : {})}
|
||||
onSessionExited={() => 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);
|
||||
|
||||
@@ -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<string, string> | 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<number | null>(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();
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string>(2, 25);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("oversized", "X", 30);
|
||||
|
||||
expect(cache.get("a")).toBe("A");
|
||||
expect(cache.get("oversized")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,10 @@ export class LRUCache<T> {
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
if (approximateSize > this.maxMemoryBytes) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.evictIfNeeded(approximateSize);
|
||||
this.cache.set(key, { value, approximateSize });
|
||||
this.totalSize += approximateSize;
|
||||
|
||||
@@ -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(
|
||||
[
|
||||
|
||||
@@ -13,6 +13,17 @@ export function toSortableTimestamp(iso: string | undefined): number | null {
|
||||
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;
|
||||
@@ -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<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (sortOrder === "created_at") {
|
||||
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
return (
|
||||
getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY
|
||||
);
|
||||
}
|
||||
return getLatestUserMessageTimestamp(thread);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user