@devries-cameron20 / t3code Mirror · read-only / commits / f12e8206f5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 12:15 UTC

fix(web): load a too-large PR file's diff on demand (#37007)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Yash Singh committed Nov 14, 2026 at 22:59 UTC f12e8206f56c05133fe4ddb8916e9e1456190972
28 files changed +877 -80
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt
+47 -5
@@ -402,7 +402,7 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
402 @Suppress("LongParameterList")
403 fun drawCode(
404 canvas: Canvas,
405 - content: String,
405 + row: DiffRow,
406 tokens: List<DiffToken>?,
407 codeX: Float,
408 baseline: Float,
@@ -417,12 +417,16 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
417 canvas.restore()
418 return
419 }
420 - val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(content, null, 0)) else tokens
420 + val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(row.content, null, 0)) else tokens
421 var line = 0
422 var x = codeX
423 var column = 0
424 - runs.forEach { run ->
425 - configureCodePaint(run.color ?: theme.text, run.fontStyle, style)
424 + splitAtNote(runs, row.noteStart).forEach { (run, note) ->
425 + configureCodePaint(
426 + if (note) theme.warningText else run.color ?: theme.text,
427 + run.fontStyle,
428 + style,
429 + )
430 var start = 0
431 while (start < run.content.length) {
432 while (line + 1 < lines.starts.size && lines.starts[line + 1] <= column + start) {
@@ -434,8 +438,10 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
438 if (lineBaseline + textPaint.fontMetrics.descent >= canvas.clipBounds.top &&
439 lineBaseline + textPaint.fontMetrics.ascent <= canvas.clipBounds.bottom
440 ) {
441 + val segmentWidth = textPaint.measureText(run.content, start, end)
442 + fillNote(canvas, note, x, x + segmentWidth, lineBaseline)
443 canvas.drawText(run.content, start, end, x, lineBaseline, textPaint)
438 - x += textPaint.measureText(run.content, start, end)
444 + x += segmentWidth
445 }
446 start = end
447 }
@@ -443,6 +449,21 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
449 }
450 }
451
452 + fun noticeColor(row: DiffRow): Int =
453 + if (row.tone == "warning") theme.warningText else theme.mutedText
454 +
455 + fun noticeFill(row: DiffRow): Int =
456 + if (row.tone == "warning") theme.warningBackground else theme.background
457 +
458 + /** Fills behind a segment of a cut line's note; other segments are left alone. */
459 + private fun fillNote(canvas: Canvas, note: Boolean, left: Float, right: Float, baseline: Float) {
460 + if (!note) return
461 + backgroundPaint.color = theme.warningBackground
462 + val metrics = textPaint.fontMetrics
463 + val top = baseline + metrics.ascent
464 + canvas.drawRect(left, top, right, baseline + metrics.descent, backgroundPaint)
465 + }
466 +
467 fun drawFileHeaderPathScrollFades(
468 canvas: Canvas,
469 pathRect: RectF,
@@ -532,3 +553,24 @@ private object ReviewDiffTypefaces {
553 else -> regular
554 }
555 }
556 +
557 +/** Splits color runs where a cut line's note starts; the flag marks the note's runs. */
558 +private fun splitAtNote(runs: List<DiffToken>, noteStart: Int?): List<Pair<DiffToken, Boolean>> {
559 + if (noteStart == null) return runs.map { it to false }
560 + return buildList {
561 + var offset = 0
562 + for (run in runs) {
563 + val end = offset + run.content.length
564 + when {
565 + end <= noteStart -> add(run to false)
566 + offset >= noteStart -> add(run to true)
567 + else -> {
568 + val cut = noteStart - offset
569 + add(run.copy(content = run.content.substring(0, cut)) to false)
570 + add(run.copy(content = run.content.substring(cut)) to true)
571 + }
572 + }
573 + offset = end
574 + }
575 + }
576 +}
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt
+14
@@ -182,6 +182,20 @@ internal class CodeLayoutCache {
182 }
183 }
184 }
185 + row.noteStart?.takeIf { it in 0 until text.length }?.let { start ->
186 + text.setSpan(
187 + ForegroundColorSpan(theme.warningText),
188 + start,
189 + text.length,
190 + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
191 + )
192 + text.setSpan(
193 + BackgroundColorSpan(theme.warningBackground),
194 + start,
195 + text.length,
196 + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
197 + )
198 + }
199 return text
200 }
201 }
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt
+11 -8
@@ -4,6 +4,16 @@ import expo.modules.kotlin.Promise
4 import expo.modules.kotlin.modules.Module
5 import expo.modules.kotlin.modules.ModuleDefinition
6
7 +private val REVIEW_DIFF_EVENTS = arrayOf(
8 + "onDebug",
9 + "onVisibleFileChange",
10 + "onToggleFile",
11 + "onToggleViewedFile",
12 + "onPressLine",
13 + "onToggleComment",
14 + "onPressNotice",
15 +)
16 +
17 class T3ReviewDiffModule : Module() {
18 override fun definition() = ModuleDefinition {
19 Name("T3ReviewDiffSurface")
@@ -54,14 +64,7 @@ class T3ReviewDiffModule : Module() {
64 view.setInitialFileId(fileId)
65 }
66
57 - Events(
58 - "onDebug",
59 - "onVisibleFileChange",
60 - "onToggleFile",
61 - "onToggleViewedFile",
62 - "onPressLine",
63 - "onToggleComment",
64 - )
67 + Events(REVIEW_DIFF_EVENTS)
68
69 AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean ->
70 view.scrollToFile(fileId, animated)
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+27 -6
@@ -31,6 +31,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
31 private val onToggleViewedFile by EventDispatcher()
32 private val onPressLine by EventDispatcher()
33 private val onToggleComment by EventDispatcher()
34 + private val onPressNotice by EventDispatcher()
35 private var rows: List<DiffRow> = emptyList()
36 private var visibleRows: List<DiffRow> = emptyList()
37 private var visibleRowIndices = IntArray(0)
@@ -432,6 +433,9 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
433 }
434 }
435 "comment" -> onToggleComment(mapOf("commentId" to row.id))
436 + "notice" -> if (gesture == "tap" && row.actionable) {
437 + onPressNotice(mapOf("rowId" to row.id, "fileId" to row.resolvedFileId))
438 + }
439 "line" -> {
440 val payload = mutableMapOf<String, Any>(
441 "rowId" to row.id,
@@ -534,7 +538,13 @@ internal data class DiffRow(
538 val wordDiffRanges: List<DiffWordDiffRange>,
539 val commentText: String,
540 val commentRangeLabel: String,
537 - val commentSectionTitle: String
541 + val commentSectionTitle: String,
542 + /** A notice drawn in the warning colors. */
543 + val tone: String = "",
544 + /** A notice that reports taps through `onPressNotice`. */
545 + val actionable: Boolean = false,
546 + /** Where a cut line's note starts in `content`. */
547 + val noteStart: Int? = null
548 ) {
549 val resolvedFileId: String get() = fileId.ifEmpty { id }
550 val isPlainAscii: Boolean = content.all { it in ' '..'~' }
@@ -564,7 +574,9 @@ internal data class DiffTheme(
574 val addBar: Int,
575 val deleteBar: Int,
576 val addText: Int,
567 - val deleteText: Int
577 + val deleteText: Int,
578 + val warningText: Int,
579 + val warningBackground: Int
580 ) {
581 companion object {
582 fun fallback(scheme: String): DiffTheme = if (scheme == "dark") {
@@ -582,6 +594,8 @@ internal data class DiffTheme(
594 deleteBar = Color.rgb(255, 46, 63),
595 addText = Color.rgb(94, 204, 113),
596 deleteText = Color.rgb(255, 103, 98),
597 + warningText = Color.rgb(250, 204, 102),
598 + warningBackground = Color.rgb(51, 38, 13),
599 )
600 } else {
601 DiffTheme(
@@ -598,6 +612,8 @@ internal data class DiffTheme(
612 deleteBar = Color.rgb(213, 44, 54),
613 addText = Color.rgb(25, 130, 67),
614 deleteText = Color.rgb(190, 38, 48),
615 + warningText = Color.rgb(140, 92, 0),
616 + warningBackground = Color.rgb(255, 245, 214),
617 )
618 }
619
@@ -617,6 +633,8 @@ internal data class DiffTheme(
633 deleteBar = color(json, "deleteBar", fallback.deleteBar),
634 addText = color(json, "addText", fallback.addText),
635 deleteText = color(json, "deleteText", fallback.deleteText),
636 + warningText = color(json, "warningText", fallback.warningText),
637 + warningBackground = color(json, "warningBackground", fallback.warningBackground),
638 )
639 } catch (_: Exception) {
640 fallback
@@ -1189,7 +1207,7 @@ private class DiffCanvasView(context: Context) : View(context) {
1207 }
1208
1209 private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
1192 - fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
1210 + fill(canvas, drawing.noticeFill(row), 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
1211 val iconSize = 16f * density
1212 val iconRect = RectF(
1213 style.fileHeaderHorizontalPaddingPx + 2f * density,
@@ -1197,10 +1215,10 @@ private class DiffCanvasView(context: Context) : View(context) {
1215 style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize,
1216 (top + bottom + iconSize) / 2f,
1217 )
1200 - drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText)
1218 + drawing.drawNoticeIcon(canvas, iconRect, drawing.noticeColor(row))
1219 drawing.configureUiPaint(
1220 paint = textPaint,
1203 - color = theme.mutedText,
1221 + color = drawing.noticeColor(row),
1222 size = style.fileHeaderSubtextFontSizePx,
1223 weight = style.fileHeaderSubtextFontWeight,
1224 )
@@ -1313,7 +1331,7 @@ private class DiffCanvasView(context: Context) : View(context) {
1331 drawing.configureCodePaint(theme.text, 0, style)
1332 drawing.drawWordDiffRanges(canvas, row, codeX, top, firstLineBottom, lines)
1333 val baseline = lines.baseline(top, firstLineBottom, textPaint)
1316 - drawing.drawCode(canvas, row.content, tokensByRowId[row.id], codeX, baseline, style, lines)
1334 + drawing.drawCode(canvas, row, tokensByRowId[row.id], codeX, baseline, style, lines)
1335 }
1336
1337 drawLineNumber(canvas, row, top, firstLineBottom)
@@ -1488,6 +1506,9 @@ private fun parseRows(value: String, isCancelled: () -> Boolean): List<DiffRow>
1506 commentText = row.optString("commentText"),
1507 commentRangeLabel = row.optString("commentRangeLabel"),
1508 commentSectionTitle = row.optString("commentSectionTitle"),
1509 + tone = row.optString("tone"),
1510 + actionable = row.optBoolean("actionable"),
1511 + noteStart = row.optNullableInt("noteStart"),
1512 )
1513 }
1514 } catch (_: Exception) {
apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift
+22 -1
@@ -16,6 +16,13 @@ struct ReviewDiffCodeLineStarts: RandomAccessCollection {
16
17 /// ASCII uses fixed-pitch columns. TextKit handles shaping, tabs, and Unicode highlights.
18 /// Pass `unboundedWidth` to lay a row out on one line for horizontal scrolling.
19 +/** A cut line's note, drawn in its own colors. */
20 +struct ReviewDiffCodeNote {
21 + let range: NSRange
22 + let color: UIColor
23 + let background: UIColor
24 +}
25 +
26 final class ReviewDiffCodeLayout: NSObject {
27 static let unboundedWidth = CGFloat.greatestFiniteMagnitude
28
@@ -84,7 +91,14 @@ final class ReviewDiffCodeLayout: NSObject {
91 return layout
92 }
93
87 - func decorate(text: NSAttributedString, highlights: [NSRange], color: UIColor, version: Int) {
94 + // A cut line's note is not code, so it takes the warning colors over any token color.
95 + func decorate(
96 + text: NSAttributedString,
97 + highlights: [NSRange],
98 + color: UIColor,
99 + note: ReviewDiffCodeNote? = nil,
100 + version: Int
101 + ) {
102 guard usesNativeLayout else { return }
103 let layout = nativeLayout()
104 guard layout.decorationVersion != version else { return }
@@ -105,6 +119,13 @@ final class ReviewDiffCodeLayout: NSObject {
119 storage.addAttribute(.backgroundColor, value: color, range: intersection)
120 }
121 }
122 + if let note {
123 + let intersection = NSIntersectionRange(note.range, fullRange)
124 + if intersection.length > 0 {
125 + storage.addAttribute(.foregroundColor, value: note.color, range: intersection)
126 + storage.addAttribute(.backgroundColor, value: note.background, range: intersection)
127 + }
128 + }
129 storage.endEditing()
130 layout.decorationVersion = version
131 }
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
+1
@@ -88,6 +88,7 @@ public class T3ReviewDiffModule: Module {
88 "onToggleViewedFile",
89 "onPressLine",
90 "onToggleComment",
91 + "onPressNotice",
92 "onPullToRefresh"
93 )
94
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
+42 -6
@@ -19,6 +19,12 @@ private struct ReviewDiffNativeRow: Decodable, Sendable {
19 let commentText: String?
20 let commentRangeLabel: String?
21 let commentSectionTitle: String?
22 + /** A notice drawn in the warning colors. */
23 + let tone: String?
24 + /** A notice that reports taps through `onPressNotice`. */
25 + let actionable: Bool?
26 + /** Where a cut line's note starts in `content`, in UTF-16 units. */
27 + let noteStart: Int?
28 }
29
30 private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
@@ -52,6 +58,8 @@ private struct ReviewDiffNativeThemePayload: Decodable {
58 let deleteBar: String?
59 let addText: String?
60 let deleteText: String?
61 + let warningText: String?
62 + let warningBackground: String?
63 }
64
65 private struct ReviewDiffNativeTheme {
@@ -68,6 +76,8 @@ private struct ReviewDiffNativeTheme {
76 let deleteBar: UIColor
77 let addText: UIColor
78 let deleteText: UIColor
79 + let warningText: UIColor
80 + let warningBackground: UIColor
81
82 static func resolve(_ scheme: String) -> ReviewDiffNativeTheme {
83 resolve(scheme, payload: nil)
@@ -95,7 +105,10 @@ private struct ReviewDiffNativeTheme {
105 addBar: UIColor(reviewDiffHex: payload.addBar) ?? fallback.addBar,
106 deleteBar: UIColor(reviewDiffHex: payload.deleteBar) ?? fallback.deleteBar,
107 addText: UIColor(reviewDiffHex: payload.addText) ?? fallback.addText,
98 - deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText
108 + deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText,
109 + warningText: UIColor(reviewDiffHex: payload.warningText) ?? fallback.warningText,
110 + warningBackground: UIColor(reviewDiffHex: payload.warningBackground)
111 + ?? fallback.warningBackground
112 )
113 }
114
@@ -114,7 +127,9 @@ private struct ReviewDiffNativeTheme {
127 addBar: UIColor(red: 0.02, green: 0.82, blue: 0.54, alpha: 1),
128 deleteBar: UIColor(red: 1.00, green: 0.36, blue: 0.50, alpha: 1),
129 addText: UIColor(red: 0.10, green: 0.84, blue: 0.56, alpha: 1),
117 - deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1)
130 + deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1),
131 + warningText: UIColor(red: 0.98, green: 0.80, blue: 0.40, alpha: 1),
132 + warningBackground: UIColor(red: 0.20, green: 0.15, blue: 0.05, alpha: 1)
133 )
134 }
135
@@ -131,7 +146,9 @@ private struct ReviewDiffNativeTheme {
146 addBar: UIColor(red: 0.02, green: 0.80, blue: 0.52, alpha: 1),
147 deleteBar: UIColor(red: 1.00, green: 0.34, blue: 0.48, alpha: 1),
148 addText: UIColor(red: 0.00, green: 0.56, blue: 0.34, alpha: 1),
134 - deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1)
149 + deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1),
150 + warningText: UIColor(red: 0.55, green: 0.36, blue: 0.00, alpha: 1),
151 + warningBackground: UIColor(red: 1.00, green: 0.96, blue: 0.84, alpha: 1)
152 )
153 }
154 }
@@ -350,6 +367,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
367 let onToggleViewedFile = EventDispatcher()
368 let onPressLine = EventDispatcher()
369 let onToggleComment = EventDispatcher()
370 + let onPressNotice = EventDispatcher()
371 let onPullToRefresh = EventDispatcher()
372
373 private let pullRefreshControl = UIRefreshControl()
@@ -383,6 +401,9 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
401 contentView.onToggleComment = { [weak self] commentId in
402 self?.onToggleComment(["commentId": commentId])
403 }
404 + contentView.onPressNotice = { [weak self] payload in
405 + self?.onPressNotice(payload)
406 + }
407 contentView.onDrawMetrics = { [weak self] metrics in
408 self?.emitDebug("draw-metrics", metrics)
409 }
@@ -1214,6 +1235,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1235 var onToggleViewedFile: ((String) -> Void)?
1236 var onPressLine: (([String: Any]) -> Void)?
1237 var onToggleComment: ((String) -> Void)?
1238 + var onPressNotice: (([String: Any]) -> Void)?
1239 var onDrawMetrics: (([String: Any]) -> Void)?
1240
1241 private var stickyWidth: CGFloat {
@@ -1555,6 +1577,11 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1577 return
1578 }
1579
1580 + if row.kind == "notice", row.actionable == true {
1581 + onPressNotice?(["rowId": row.id, "fileId": resolvedFileId(for: row)])
1582 + return
1583 + }
1584 +
1585 if row.kind == "line" {
1586 onPressLine?(linePressPayload(for: row, gesture: "tap"))
1587 return
@@ -2200,7 +2227,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
2227 return
2228 }
2229
2203 - theme.background.setFill()
2230 + let warning = row.tone == "warning"
2231 + (warning ? theme.warningBackground : theme.background).setFill()
2232 context.fill(rect)
2233
2234 let hairline = 1 / traitCollection.displayScale
@@ -2214,7 +2242,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
2242 width: iconSize,
2243 height: iconSize
2244 )
2217 - drawNoticeIcon(rect: iconRect, color: theme.mutedText)
2245 + let noticeColor = warning ? theme.warningText : theme.mutedText
2246 + drawNoticeIcon(rect: iconRect, color: noticeColor)
2247
2248 drawSingleLineText(
2249 row.text ?? "",
@@ -2224,7 +2253,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
2253 width: max(24, viewportWidth - iconRect.maxX - 10 - style.fileHeaderHorizontalPadding),
2254 height: fileHeaderSubtextFont.lineHeight
2255 ),
2227 - color: theme.mutedText,
2256 + color: noticeColor,
2257 font: fileHeaderSubtextFont
2258 )
2259 }
@@ -2554,6 +2583,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
2583 NSRange(location: $0.start, length: $0.end - $0.start)
2584 },
2585 color: (change == "add" ? theme.addBar : theme.deleteBar).withAlphaComponent(0.28),
2586 + note: row.noteStart.map {
2587 + ReviewDiffCodeNote(
2588 + range: NSRange(location: $0, length: max(0, text.length - $0)),
2589 + color: theme.warningText,
2590 + background: theme.warningBackground
2591 + )
2592 + },
2593 version: codeDecorationVersion
2594 )
2595 layout.draw(
apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
+11
@@ -47,6 +47,12 @@ export interface NativeReviewDiffRow {
47 readonly commentText?: string;
48 readonly commentRangeLabel?: string;
49 readonly commentSectionTitle?: string;
50 + /** A notice drawn in the warning colors. */
51 + readonly tone?: "warning";
52 + /** A notice that reports taps through `onPressNotice`. */
53 + readonly actionable?: boolean;
54 + /** Where a cut line's note starts in `content`. */
55 + readonly noteStart?: number;
56 }
57
58 export interface NativeReviewDiffWordDiffRange {
@@ -74,6 +80,8 @@ export interface NativeReviewDiffTheme {
80 readonly deleteBar: string;
81 readonly addText: string;
82 readonly deleteText: string;
83 + readonly warningText: string;
84 + readonly warningBackground: string;
85 }
86
87 export interface NativeReviewDiffStyle {
@@ -151,6 +159,9 @@ export interface NativeReviewDiffViewProps extends ViewProps {
159 }>,
160 ) => void;
161 readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
162 + readonly onPressNotice?: (
163 + event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>,
164 + ) => void;
165 }
166
167 export interface NativeReviewDiffViewHandle {
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+5
@@ -1011,6 +1011,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
1011 !staleDiff &&
1012 !detail.isPending &&
1013 !result.isPending &&
1014 + !result.withheldRefetching &&
1015 !result.error;
1016 const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));
1017 const baseData = useMemo(() => getCachedNativeReviewDiffData({ parsedDiff: parsed }), [parsed]);
@@ -1338,6 +1339,10 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
1339 });
1340 else void viewed.toggle(file.path);
1341 }}
1342 + onPressNotice={(event) => {
1343 + const file = data.files.find((file) => file.id === event.nativeEvent.fileId);
1344 + if (file) result.loadWithheldFile(file.path);
1345 + }}
1346 onToggleComment={(event) => {
1347 const id = event.nativeEvent.commentId;
1348 if (id?.startsWith("discussion:"))
apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
+39
@@ -7,6 +7,8 @@ import {
7 combinePullRequestDiffPages,
8 getCachedPullRequestDiffPages,
9 retainPullRequestDiffPage,
10 + withWithheldFiles,
11 + type WithheldFileLoad,
12 } from "./pullRequestDiffPages";
13
14 const GITHUB = sourceControlClients.get("github").changeRequest;
@@ -156,4 +158,41 @@ describe("paged mobile pull request diffs", () => {
158 expect(refreshed).toHaveLength(1);
159 expect(refreshed[0]?.result.patch).toContain("changed.ts");
160 });
161 +
162 + it("swaps a loaded withheld file in under its id and says what a tap does for the rest", () => {
163 + const pages = [{ cursor: null, result: withheldDiff() }];
164 + const parsed = combinePullRequestDiffPages(pages, new WeakMap(), "pr", GITHUB);
165 + if (parsed.kind !== "files") throw new Error("Expected structured diff");
166 + const placeholder = parsed.files[0];
167 + let merged: ReviewParsedDiff = parsed;
168 + const fileWith = (load: WithheldFileLoad | undefined, canLoad = true) => {
169 + merged = withWithheldFiles(
170 + parsed,
171 + new Map(load === undefined ? [] : [["large.ts", load]]),
172 + canLoad,
173 + "pr",
174 + );
175 + return merged.kind === "files" ? merged.files[0] : undefined;
176 + };
177 + expect(fileWith(undefined)).toMatchObject({
178 + notice: "Diff too large to display. Tap to load it.",
179 + noticeTone: "warning",
180 + noticeActionable: true,
181 + });
182 + expect(fileWith(undefined, false)).toMatchObject({
183 + notice: "Diff too large to display here.",
184 + noticeActionable: false,
185 + });
186 + expect(fileWith({ status: "loading" })).toMatchObject({ noticeActionable: false });
187 + expect(fileWith({ status: "error" })).toMatchObject({
188 + notice: "Couldn't load this diff. Tap to try again.",
189 + noticeActionable: true,
190 + });
191 + const loaded = fileWith({ status: "loaded", result: diff("large.ts") });
192 + expect(loaded).toMatchObject({ id: placeholder?.id, path: "large.ts" });
193 + expect(loaded?.notice).toBeUndefined();
194 + expect(loaded?.rows.length).toBeGreaterThan(0);
195 + // The totals follow the loaded file, which may have changed since the page was read.
196 + expect(merged).toMatchObject({ additions: 1, deletions: 1 });
197 + });
198 });
apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
+73 -2
@@ -1,6 +1,10 @@
1 import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
2 import type { PullRequestDiffResult } from "@t3tools/contracts";
3 -import { buildReviewParsedDiff, type ReviewParsedDiff } from "../review/reviewModel";
3 +import {
4 + buildReviewParsedDiff,
5 + type ReviewParsedDiff,
6 + type ReviewRenderableFile,
7 +} from "../review/reviewModel";
8
9 export interface PullRequestDiffPage {
10 readonly cursor: string | null;
@@ -61,6 +65,7 @@ export function retainPullRequestDiffPage(
65 (previous?.patch === result.patch &&
66 previous.truncated === result.truncated &&
67 previous.nextCursor === result.nextCursor &&
68 + previous.withheldFilesReadable === result.withheldFilesReadable &&
69 JSON.stringify(previous.omittedFileStats ?? []) ===
70 JSON.stringify(result.omittedFileStats ?? []))
71 )
@@ -84,7 +89,13 @@ export function combinePullRequestDiffPages(
89 );
90 const files = value.files.map((file) => {
91 const stat = omittedFileStats.get(file.path);
87 - return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file;
92 + if (!stat) return file;
93 + return {
94 + ...file,
95 + additions: stat.additions,
96 + deletions: stat.deletions,
97 + ...(file.rows.length === 0 ? { withheld: true } : {}),
98 + };
99 });
100 value = {
101 ...value,
@@ -111,3 +122,63 @@ export function combinePullRequestDiffPages(
122 : null,
123 };
124 }
125 +
126 +export type WithheldFileLoad =
127 + | { readonly status: "loading" | "error" }
128 + | { readonly status: "loaded"; readonly result: PullRequestDiffResult };
129 +
130 +const withheldFileParses = new WeakMap<PullRequestDiffResult, ReviewRenderableFile | null>();
131 +
132 +function parseWithheldFile(result: PullRequestDiffResult, scope: string) {
133 + if (withheldFileParses.has(result)) return withheldFileParses.get(result) ?? null;
134 + const parsed = buildReviewParsedDiff(result.patch, scope);
135 + const file =
136 + parsed.kind === "files" ? (parsed.files.find((entry) => entry.rows.length > 0) ?? null) : null;
137 + withheldFileParses.set(result, file);
138 + return file;
139 +}
140 +
141 +function withheldFileNotice(load: WithheldFileLoad | undefined, canLoad: boolean): string {
142 + if (load === undefined) {
143 + return canLoad
144 + ? "Diff too large to display. Tap to load it."
145 + : "Diff too large to display here.";
146 + }
147 + if (load.status === "loading") return "Loading diff…";
148 + if (load.status === "error") return "Couldn't load this diff. Tap to try again.";
149 + return "No text diff for this file.";
150 +}
151 +
152 +/**
153 + * Puts each loaded withheld file in place of its empty one, under the same id so folds and
154 + * targets hold, and gives the rest a notice saying what a tap does.
155 + */
156 +export function withWithheldFiles(
157 + parsed: ReviewParsedDiff,
158 + loads: ReadonlyMap<string, WithheldFileLoad>,
159 + canLoad: boolean,
160 + scope: string,
161 +): ReviewParsedDiff {
162 + if (parsed.kind !== "files" || !parsed.files.some((file) => file.withheld)) return parsed;
163 + const files = parsed.files.map((file): ReviewRenderableFile => {
164 + if (!file.withheld) return file;
165 + const load = loads.get(file.path);
166 + const loaded =
167 + load?.status === "loaded"
168 + ? parseWithheldFile(load.result, `${scope}:withheld:${file.path}`)
169 + : null;
170 + if (loaded !== null) return { ...loaded, id: file.id };
171 + return {
172 + ...file,
173 + notice: withheldFileNotice(load, canLoad),
174 + noticeTone: "warning",
175 + noticeActionable: canLoad && (load === undefined || load.status === "error"),
176 + };
177 + });
178 + return {
179 + ...parsed,
180 + files,
181 + additions: files.reduce((total, file) => total + file.additions, 0),
182 + deletions: files.reduce((total, file) => total + file.deletions, 0),
183 + };
184 +}
apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
+66 -3
@@ -5,8 +5,9 @@ import {
5 type PullRequestListEntry,
6 type PullRequestSummary,
7 } from "@t3tools/contracts";
8 -import { useAtomRefresh } from "@effect/atom-react";
9 -import { useLayoutEffect, useMemo, useState } from "react";
8 +import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
9 +import { Atom } from "effect/reactivity";
10 +import { useContext, useLayoutEffect, useMemo, useState } from "react";
11
12 import { composerPullRequests } from "../../state/pull-requests";
13 import { useEnvironmentQuery } from "../../state/query";
@@ -14,7 +15,9 @@ import { usePullToRefresh } from "../../state/use-pull-to-refresh";
15 import {
16 getCachedPullRequestDiffPages,
17 retainPullRequestDiffPage,
18 + withWithheldFiles,
19 type PullRequestDiffPage,
20 + type WithheldFileLoad,
21 } from "./pullRequestDiffPages";
22
23 export type PullRequestParams = {
@@ -43,6 +46,26 @@ export function pullRequestTarget(params: PullRequestParams) {
46 }
47
48 const NO_PAGES: readonly PullRequestDiffPage[] = [];
49 +const NO_PATHS: readonly string[] = [];
50 +
51 +type PullRequestDiffTarget = Parameters<typeof composerPullRequests.diff>[0];
52 +
53 +// Keyed by the diff's serialized target, which the hook already holds as its scope.
54 +const withheldFileDiff = (targetKey: string, path: string) => {
55 + const target = JSON.parse(targetKey) as PullRequestDiffTarget;
56 + return composerPullRequests.diff({ ...target, input: { ...target.input, path } });
57 +};
58 +
59 +// One read per withheld file the reader asked for, so only that file's diff crosses the wire.
60 +const withheldFileDiffsAtom = Atom.family((key: string) => {
61 + const { targetKey, paths } = JSON.parse(key) as {
62 + readonly targetKey: string;
63 + readonly paths: readonly string[];
64 + };
65 + return Atom.make((get) => paths.map((path) => get(withheldFileDiff(targetKey, path)))).pipe(
66 + Atom.withLabel(`mobile:pull-request-withheld-file-diffs:${key}`),
67 + );
68 +});
69
70 export function usePullRequestDiffEntry(navigation: {
71 readonly addListener: (
@@ -116,10 +139,46 @@ export function usePullRequestDiff(
139 }, [cursor, key, query.data, state.key, state.pages]);
140 if (state.key !== key || state.pages !== pages) setState({ key, cursor, pages });
141
119 - const parsed = useMemo(
142 + const [withheldLoads, setWithheldLoads] = useState<{
143 + readonly key: string;
144 + readonly paths: readonly string[];
145 + }>({ key: "", paths: NO_PATHS });
146 + const withheldPaths = withheldLoads.key === key ? withheldLoads.paths : NO_PATHS;
147 + const withheldResults = useAtomValue(
148 + withheldFileDiffsAtom(JSON.stringify({ targetKey: key, paths: withheldPaths })),
149 + );
150 + const registry = useContext(RegistryContext);
151 + const refreshWithheldFiles = () => {
152 + for (const path of withheldPaths) registry.refresh(withheldFileDiff(key, path));
153 + };
154 + const loadWithheldFile = (path: string) => {
155 + // The read is keyed without the head, so even a first load must not reuse an older one.
156 + registry.refresh(withheldFileDiff(key, path));
157 + if (!withheldPaths.includes(path)) setWithheldLoads({ key, paths: [...withheldPaths, path] });
158 + };
159 + // A refetch keeps showing the last patch, whose lines may not exist at the new head.
160 + const withheldRefetching = withheldResults.some((result) => result.waiting);
161 + const loads = new Map<string, WithheldFileLoad>();
162 + withheldPaths.forEach((path, index) => {
163 + const result = withheldResults[index];
164 + if (result === undefined) return;
165 + // A failed refetch still carries the last patch; show the failure instead.
166 + loads.set(
167 + path,
168 + result._tag === "Failure"
169 + ? { status: "error" }
170 + : result._tag === "Success"
171 + ? { status: "loaded", result: result.value }
172 + : { status: "loading" },
173 + );
174 + });
175 + const pagesParsed = useMemo(
176 () => getCachedPullRequestDiffPages(pages, key, terminology),
177 [key, pages, terminology],
178 );
179 + // The server says whether a withheld file can be read alone; GitHub may refuse the whole diff.
180 + const withheldFilesReadable = pages[0]?.result.withheldFilesReadable === true;
181 + const parsed = withWithheldFiles(pagesParsed, loads, withheldFilesReadable, key);
182 const patch = useMemo(() => pages.map((page) => page.result.patch).join("\n"), [pages]);
183 const nextCursor = pages.at(-1)?.result.nextCursor ?? null;
184 const canLoadMore =
@@ -136,15 +195,19 @@ export function usePullRequestDiff(
195 }
196 setState({ key, cursor: null, pages: NO_PAGES });
197 refreshFirstPage();
198 + refreshWithheldFiles();
199 };
200 const onPullRefresh = () => {
201 setState({ key, cursor: null, pages: NO_PAGES });
202 onRefresh();
203 + refreshWithheldFiles();
204 };
205 return {
206 ...query,
207 refresh,
208 parsed,
209 + loadWithheldFile,
210 + withheldRefetching,
211 patch,
212 nextCursor,
213 canLoadMore,
apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
+16 -1
@@ -1,3 +1,4 @@
1 +import { cutLineNoteStart } from "@t3tools/shared/diffCutLines";
2 import type { NativeReviewDiffRow, NativeReviewDiffTheme } from "../diffs/nativeReviewDiffSurface";
3 import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
4 import * as Arr from "effect/Array";
@@ -226,6 +227,8 @@ export function createNativeReviewDiffTheme(
227 deleteBar: terminalRed ?? "#ff2e3f",
228 addText: "#5ECC71",
229 deleteText: "#FF6762",
230 + warningText: nativeColor(appTheme["--color-warning-foreground"]),
231 + warningBackground: nativeColor(appTheme["--color-warning"]),
232 };
233 }
234
@@ -243,6 +246,8 @@ export function createNativeReviewDiffTheme(
246 deleteBar: terminalRed ?? "#ff2e3f",
247 addText: "#199F43",
248 deleteText: "#D52C36",
249 + warningText: nativeColor(appTheme["--color-warning-foreground"]),
250 + warningBackground: nativeColor(appTheme["--color-warning"]),
251 };
252 }
253
@@ -270,7 +275,15 @@ function createNoticeRow(fileId: string, suffix: string, text: string): NativeRe
275 }
276
277 function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
273 - if (file.notice) return [createNoticeRow(file.id, "loading", file.notice)];
278 + if (file.notice) {
279 + return [
280 + {
281 + ...createNoticeRow(file.id, "loading", file.notice),
282 + ...(file.noticeTone === undefined ? {} : { tone: file.noticeTone }),
283 + ...(file.noticeActionable ? { actionable: true } : {}),
284 + },
285 + ];
286 + }
287 if (file.rows.length > 0) {
288 return [];
289 }
@@ -388,6 +401,7 @@ function mapLineRow(
401 row: ReviewRenderableLineRow,
402 rowIndex: number,
403 ): NativeReviewDiffRow {
404 + const noteStart = cutLineNoteStart(row.content);
405 return {
406 kind: "line",
407 id: `${file.id}:line:${rowIndex}:${row.id}`,
@@ -396,6 +410,7 @@ function mapLineRow(
410 change: row.change,
411 oldLineNumber: row.oldLineNumber,
412 newLineNumber: row.newLineNumber,
413 + ...(noteStart === null ? {} : { noteStart }),
414 };
415 }
416
apps/mobile/src/features/review/reviewModel.ts
+5
@@ -56,6 +56,11 @@ export interface ReviewRenderableFile {
56 readonly id: string;
57 readonly cacheKey: string;
58 readonly notice?: string;
59 + readonly noticeTone?: "warning";
60 + /** The notice row reports taps, as for loading a withheld file's diff. */
61 + readonly noticeActionable?: boolean;
62 + /** The host left out this file's hunks as too large; it can be loaded on its own. */
63 + readonly withheld?: boolean;
64 readonly path: string;
65 readonly previousPath: string | null;
66 readonly changeType: ChangeTypes;
apps/server/src/pullRequest/PullRequestService.test.ts
+34
@@ -3249,6 +3249,40 @@ it.effect("reads the fresh diff when detail or summary discovers a changed revis
3249 }),
3250 );
3251
3252 +it.effect("keeps a withheld file's read out of the page's cached diff", () =>
3253 + Effect.gen(function* () {
3254 + const provider = fakePullRequestProvider(SourceControlProviderKind.make("github"), {
3255 + getDiff: (input) =>
3256 + Effect.succeed({
3257 + patch: input.path === undefined ? "page" : `file ${input.path}`,
3258 + truncated: input.path === undefined,
3259 + nextCursor: null,
3260 + }),
3261 + });
3262 + const service = yield* makeService({
3263 + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
3264 + providers: [provider],
3265 + });
3266 + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 10 };
3267 + assert.strictEqual((yield* service.diff(ref)).patch, "page");
3268 + assert.strictEqual(
3269 + (yield* service.diff({ ...ref, path: "sdk.patch" })).patch,
3270 + "file sdk.patch",
3271 + );
3272 + assert.strictEqual((yield* service.diff(ref)).patch, "page");
3273 +
3274 + // A host that would answer with its whole diff must not be cached as one file's.
3275 + const wholeDiffOnly = yield* makeService({
3276 + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
3277 + providers: [
3278 + { ...provider, capabilities: { ...provider.capabilities, withheldFileDiff: false } },
3279 + ],
3280 + });
3281 + const error = yield* Effect.flip(wholeDiffOnly.diff({ ...ref, path: "sdk.patch" }));
3282 + assert.strictEqual(error._tag, "PullRequestOperationError");
3283 + }),
3284 +);
3285 +
3286 it.effect("keeps routed reads separate when the GitHub account changes", () =>
3287 Effect.gen(function* () {
3288 for (const operation of ["summary", "detail", "checks", "diff", "filesViewed"] as const) {
apps/server/src/pullRequest/PullRequestService.ts
+35 -16
@@ -2036,23 +2036,31 @@ export const make = Effect.gen(function* () {
2036 const diffUncached: PullRequestService["Service"]["diff"] = (input) =>
2037 requireProject(input).pipe(
2038 Effect.flatMap((project) =>
2039 - project.api.capabilities.diff
2040 - ? project.api
2041 - .getDiff({
2042 - cwd: project.project.workspaceRoot,
2043 - repository: project.repository,
2044 - host: project.host,
2045 - number: input.number,
2046 - ...(input.cursor === undefined ? {} : { cursor: input.cursor }),
2047 - ...(input.commit === undefined ? {} : { commit: input.commit }),
2048 - })
2049 - .pipe(Effect.mapError(toPullRequestError("diff")))
2050 - : Effect.fail(
2039 + input.path !== undefined && project.api.capabilities.withheldFileDiff !== true
2040 + ? Effect.fail(
2041 new PullRequestOperationError({
2042 operation: "diff",
2053 - detail: "This host cannot provide a diff for a change request.",
2043 + detail: "This host cannot read one file of a change request's diff.",
2044 }),
2055 - ),
2045 + )
2046 + : project.api.capabilities.diff
2047 + ? project.api
2048 + .getDiff({
2049 + cwd: project.project.workspaceRoot,
2050 + repository: project.repository,
2051 + host: project.host,
2052 + number: input.number,
2053 + ...(input.path === undefined ? {} : { path: input.path }),
2054 + ...(input.cursor === undefined ? {} : { cursor: input.cursor }),
2055 + ...(input.commit === undefined ? {} : { commit: input.commit }),
2056 + })
2057 + .pipe(Effect.mapError(toPullRequestError("diff")))
2058 + : Effect.fail(
2059 + new PullRequestOperationError({
2060 + operation: "diff",
2061 + detail: "This host cannot provide a diff for a change request.",
2062 + }),
2063 + ),
2064 ),
2065 );
2066
@@ -3503,16 +3511,26 @@ export const make = Effect.gen(function* () {
3511
3512 const diffCache = yield* Cache.makeWith(
3513 (key: string) => {
3506 - const [reference, cursor, commit] = JSON.parse(key) as [string, string | null, string | null];
3514 + const [reference, cursor, commit, , path] = JSON.parse(key) as [
3515 + string,
3516 + string | null,
3517 + string | null,
3518 + string | null,
3519 + string | null,
3520 + ];
3521 return diffUncached({
3522 ...refOfCacheKey(reference),
3523 + ...(path === null ? {} : { path }),
3524 ...(cursor === null ? {} : { cursor }),
3525 ...(commit === null ? {} : { commit }),
3526 } as PullRequestDiffInput).pipe(
3527 observeRead,
3528 Effect.tap(({ value, observedAt }) => {
3529 // Keep the loader's epoch and read time if a refresh occurs during the provider read.
3515 - diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt);
3530 + // One withheld file is not the page's file list.
3531 + if (path === null) {
3532 + diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt);
3533 + }
3534 return Effect.void;
3535 }),
3536 );
@@ -3559,6 +3577,7 @@ export const make = Effect.gen(function* () {
3577 input.commit === undefined
3578 ? (lastGoodSummary.peek(refCacheKey(input))?.updatedAt ?? null)
3579 : null,
3580 + input.path ?? null,
3581 ]);
3582 const evictDiffs = Cache.entries(diffCache).pipe(
3583 Effect.flatMap((entries) =>
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+192 -9
@@ -43,11 +43,13 @@ import {
43 ChevronsDownUpIcon,
44 ChevronsUpDownIcon,
45 } from "lucide-react";
46 -import { useAtomRefresh } from "@effect/atom-react";
46 +import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
47 +import { AsyncResult, Atom } from "effect/reactivity";
48 import * as Schema from "effect/Schema";
49 import {
50 createContext,
51 use,
52 + useContext,
53 useEffect,
54 useEffectEvent,
55 useRef,
@@ -141,6 +143,8 @@ import {
143 import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation";
144 import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState";
145 import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
146 +import { hasCutLines } from "@t3tools/shared/diffCutLines";
147 +import { CUT_LINES_CSS, markCutLineNotes } from "./cutLineNotes";
148 import {
149 nextPendingReviewCommentId,
150 pullRequestReviewKey,
@@ -154,8 +158,29 @@ interface ReviewAnnotationGroup {
158 readonly pending: ReadonlyArray<PendingReviewComment>;
159 readonly draft: boolean;
160 readonly image?: { readonly url: string; readonly path: string };
161 + readonly withheld?: { readonly path: string; readonly status: WithheldFileStatus };
162 }
163
164 +type WithheldFileStatus = "idle" | "loading" | "error" | "empty";
165 +
166 +type PullRequestDiffTarget = Parameters<typeof pullRequestEnvironment.diff>[0];
167 +
168 +// One read per withheld file the reader asked for, so only that file's diff crosses the wire.
169 +const withheldFileDiffsAtom = Atom.family((key: string) => {
170 + const { environmentId, input, paths } = JSON.parse(key) as {
171 + readonly environmentId: PullRequestDiffTarget["environmentId"];
172 + readonly input: PullRequestDiffTarget["input"];
173 + readonly paths: ReadonlyArray<string>;
174 + };
175 + return Atom.make((get) =>
176 + paths.map((path) =>
177 + get(pullRequestEnvironment.diff({ environmentId, input: { ...input, path } })),
178 + ),
179 + ).pipe(Atom.withLabel(`pull-request-withheld-file-diffs:${key}`));
180 +});
181 +
182 +const NO_PATHS: ReadonlyArray<string> = [];
183 +
184 type ReviewAnnotation = DiffLineAnnotation<ReviewAnnotationGroup>;
185
186 const COMMIT_PAGE_SIZE = 10;
@@ -508,6 +533,7 @@ function PullRequestCodeTab({
533 existing.patch === next.patch &&
534 existing.truncated === next.truncated &&
535 existing.nextCursor === next.nextCursor &&
536 + existing.source.withheldFilesReadable === next.source.withheldFilesReadable &&
537 existing.omittedFileStats.length === next.omittedFileStats.length &&
538 existing.omittedFileStats.every((file, index) => {
539 const refreshed = next.omittedFileStats[index];
@@ -562,6 +588,20 @@ function PullRequestCodeTab({
588 isViewed: isFileViewed,
589 isStale: isFileViewedStale,
590 } = filesViewed;
591 + const [withheldLoads, setWithheldLoads] = useState<{
592 + readonly scope: string;
593 + readonly paths: ReadonlyArray<string>;
594 + /** The render key each loaded file was last shown under; a changed patch gets a new one. */
595 + readonly shownKeys: ReadonlyMap<string, string>;
596 + }>({ scope: "", paths: NO_PATHS, shownKeys: new Map() });
597 + const withheldPaths = withheldLoads.scope === scopeKey ? withheldLoads.paths : NO_PATHS;
598 + const withheldInput = { ...reference, ...(commit === null ? {} : { commit }) };
599 + const atomRegistry = useContext(RegistryContext);
600 + const withheldFileDiff = (path: string) =>
601 + pullRequestEnvironment.diff({ environmentId, input: { ...withheldInput, path } });
602 + const refreshWithheldFiles = useEffectEvent(() => {
603 + for (const path of withheldPaths) atomRegistry.refresh(withheldFileDiff(path));
604 + });
605 const appliedRefreshToken = useRef(refreshToken);
606 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new refresh token clears loaded slices and refetches the first diff page and viewed files
607 useEffect(() => {
@@ -572,6 +612,7 @@ function PullRequestCodeTab({
612 // applied page is forgotten too.
613 setAppliedPage(null);
614 refreshFirstDiffPage();
615 + refreshWithheldFiles();
616 refreshFilesViewed();
617 }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
618 const appliedBackgroundRefreshToken = useRef(backgroundRefreshToken);
@@ -582,6 +623,7 @@ function PullRequestCodeTab({
623 // Keeping slices mounted preserves scroll; the page merge invalidates changed pages.
624 setSliceState((previous) => ({ ...previous, cursor: null }));
625 refreshFirstDiffPage();
626 + refreshWithheldFiles();
627 refreshFilesViewed();
628 }, [backgroundRefreshToken, refreshFirstDiffPage, refreshFilesViewed]);
629
@@ -606,11 +648,89 @@ function PullRequestCodeTab({
648 // Agent context is local, so it does not require host comment permission.
649 const canSelectLines =
650 commit === null && (review.inlineComment || onAddToAgentSelection !== undefined);
609 - const { parsedSlices, loadedFiles, sourceFileStats } = diffModel(
651 + const {
652 + parsedSlices,
653 + loadedFiles: pagedFiles,
654 + sourceFileStats,
655 + } = diffModel(
656 loadedSlices,
657 `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}`,
658 ignoreWhitespace,
659 );
660 + const withheldResults = useAtomValue(
661 + withheldFileDiffsAtom(
662 + JSON.stringify({ environmentId, input: withheldInput, paths: withheldPaths }),
663 + ),
664 + );
665 + // A refetch keeps showing the last patch, whose lines may not exist at the new head.
666 + const withheldRefetching = withheldResults.some((result) => result.waiting);
667 + const withheldStatuses = new Map<string, WithheldFileStatus>();
668 + const withheldFiles = new Map<string, (typeof pagedFiles)[number]>();
669 + const cutFiles = new Set<unknown>();
670 + withheldPaths.forEach((path, index) => {
671 + const result = withheldResults[index];
672 + if (result === undefined) return;
673 + // A failed refresh still carries the earlier patch; show the failure instead of stale code.
674 + const data = result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null);
675 + if (data === null) {
676 + withheldStatuses.set(path, result._tag === "Failure" ? "error" : "loading");
677 + return;
678 + }
679 + const parsed = parseSlice(
680 + {
681 + source: data,
682 + cursor: null,
683 + patch: data.patch,
684 + truncated: false,
685 + nextCursor: null,
686 + omittedFileStats: [],
687 + },
688 + `pull-request:${scopeKey}:${resolvedTheme}:withheld:${path}`,
689 + // Cut lines can match up to the cut and differ after it; hiding them would drop changes.
690 + false,
691 + );
692 + const file = parsed?.kind === "files" ? parsed.files[0] : undefined;
693 + if (file !== undefined && file.hunks.length > 0) {
694 + withheldFiles.set(path, file);
695 + if (hasCutLines(data.patch)) cutFiles.add(file);
696 + } else withheldStatuses.set(path, "empty");
697 + });
698 + // Fold choices follow render keys, so a loaded or refetched patch would otherwise fold again
699 + // when marked Viewed: it opens on first load and keeps its earlier key's choice after.
700 + const rekeyed = [...withheldFiles].flatMap(([path, file]) => {
701 + const key = buildFileDiffRenderKey(file);
702 + return withheldLoads.shownKeys.get(path) === key ? [] : [[path, key] as const];
703 + });
704 + if (withheldLoads.scope === scopeKey && rekeyed.length > 0) {
705 + setWithheldLoads({
706 + ...withheldLoads,
707 + shownKeys: new Map([...withheldLoads.shownKeys, ...rekeyed]),
708 + });
709 + setFoldChoices((current) =>
710 + rekeyed.reduce((next, [path, key]) => {
711 + const shown = withheldLoads.shownKeys.get(path);
712 + const collapsed = shown === undefined ? false : current.get(shown);
713 + return collapsed === undefined ? next : withFileDiffFold(next, key, collapsed);
714 + }, current),
715 + );
716 + }
717 + const loadedFiles =
718 + withheldFiles.size === 0
719 + ? pagedFiles
720 + : // A refreshed page may carry the file's patch itself now.
721 + pagedFiles.map((file) =>
722 + file.hunks.length === 0 ? (withheldFiles.get(resolveFileDiffPath(file)) ?? file) : file,
723 + );
724 + const loadWithheldFile = (path: string) => {
725 + // The read is keyed without the head, so even a first load must not reuse an older one.
726 + atomRegistry.refresh(withheldFileDiff(path));
727 + if (withheldPaths.includes(path)) return;
728 + setWithheldLoads({
729 + scope: scopeKey,
730 + paths: [...withheldPaths, path],
731 + shownKeys: withheldLoads.scope === scopeKey ? withheldLoads.shownKeys : new Map(),
732 + });
733 + };
734 const linkAnchor = parsePullRequestAnchor(revealUrl);
735 const linkFile =
736 linkAnchor?.kind === "diff"
@@ -732,6 +852,17 @@ function PullRequestCodeTab({
852 lineNumber: 0,
853 metadata: { threads: [], pending: [], draft: false, image: { url: imageUrl, path } },
854 });
855 + } else if (fileDiff.hunks.length === 0 && omittedFileStats.has(path)) {
856 + annotations.push({
857 + side: "additions",
858 + lineNumber: 0,
859 + metadata: {
860 + threads: [],
861 + pending: [],
862 + draft: false,
863 + withheld: { path, status: withheldStatuses.get(path) ?? "idle" },
864 + },
865 + });
866 }
867 return {
868 fileKey,
@@ -743,7 +874,7 @@ function PullRequestCodeTab({
874 annotations
875 .map(
876 ({ side, lineNumber, metadata }) =>
746 - `${side}:${lineNumber}:${metadata.image?.url ?? ""}:${metadata.draft ? "d" : ""}:${metadata.pending
877 + `${side}:${lineNumber}:${metadata.image?.url ?? ""}:${metadata.withheld?.status ?? ""}:${metadata.draft ? "d" : ""}:${metadata.pending
878 .map((comment) => `${comment.id}:${comment.body}`)
879 .join(",")}:${metadata.threads
880 .map(
@@ -769,6 +900,7 @@ function PullRequestCodeTab({
900 });
901
902 const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;
903 + const withheldFilesReadable = loadedSlices[0]?.source.withheldFilesReadable === true;
904 const withheldContent =
905 loadedSlices.some((slice) => slice.truncated) ||
906 parsedSlices.some((parsed) => parsed?.kind === "raw");
@@ -908,7 +1040,7 @@ function PullRequestCodeTab({
1040 range: SelectedLineRange | null,
1041 context: { item: CodeViewItem<ReviewAnnotationGroup> },
1042 ) => {
911 - if (!range || !canSelectLines) return;
1043 + if (!range || !canSelectLines || withheldRefetching) return;
1044 const item = context.item;
1045 if (item.type !== "diff") return;
1046 const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id);
@@ -1030,12 +1162,24 @@ function PullRequestCodeTab({
1162 preferredHighlighter: PREFERRED_HIGHLIGHTER,
1163 themeType: resolvedTheme,
1164 stickyHeaders: true,
1033 - loadDiffFiles,
1034 - enableGutterUtility: canSelectLines && draft === null,
1035 - enableLineSelection: canSelectLines && draft === null,
1165 + // Full contents would not match the cut lines, and would bring back the lines just cut.
1166 + loadDiffFiles: (fileDiff: FileDiffMetadata) =>
1167 + cutFiles.has(fileDiff)
1168 + ? Promise.reject(new Error("Unchanged lines are unavailable in a file with cut lines."))
1169 + : loadDiffFiles(fileDiff),
1170 + enableGutterUtility: canSelectLines && draft === null && !withheldRefetching,
1171 + enableLineSelection: canSelectLines && draft === null && !withheldRefetching,
1172 onGutterUtilityClick: beginComment,
1173 onLineSelectionEnd: beginComment,
1038 - onPostRender: codeViewReveal.flush,
1174 + onPostRender: (fileContainer: HTMLElement, instance: object) => {
1175 + codeViewReveal.flush();
1176 + // Containers are reused across files, so the flag is set or cleared on every render.
1177 + fileContainer.toggleAttribute(
1178 + "data-cut-lines",
1179 + "fileDiff" in instance && cutFiles.has(instance.fileDiff),
1180 + );
1181 + if (withheldFiles.size > 0) markCutLineNotes(fileContainer);
1182 + },
1183 onItemCollapsedChange: (
1184 _item: CodeViewItem<ReviewAnnotationGroup>,
1185 nextItem: CodeViewItem<ReviewAnnotationGroup>,
@@ -1147,6 +1291,12 @@ function PullRequestCodeTab({
1291 />
1292 </div>
1293 ) : null}
1294 + {annotation.metadata.withheld ? (
1295 + <WithheldFileNotice
1296 + {...annotation.metadata.withheld}
1297 + onLoad={withheldFilesReadable ? loadWithheldFile : undefined}
1298 + />
1299 + ) : null}
1300 <InlineReviewThreads threads={annotation.metadata.threads} renderThread={renderThreadCard} />
1301 {annotation.metadata.pending.map((comment) => (
1302 <PendingReviewCommentCard
@@ -1740,7 +1890,7 @@ function PullRequestCodeTab({
1890 renderHeaderPrefix={renderHeaderPrefix}
1891 renderHeaderMetadata={renderHeaderMetadata}
1892 renderAnnotation={renderAnnotation}
1743 - unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
1893 + unsafeCSSExtra={`${REPLACE_FILE_COUNTS_CSS}\n${CUT_LINES_CSS}`}
1894 />
1895 </FileViewedToggleContext>
1896 </div>
@@ -1786,4 +1936,37 @@ function PullRequestCodeTab({
1936 );
1937 }
1938
1939 +function WithheldFileNotice({
1940 + path,
1941 + status,
1942 + onLoad,
1943 +}: {
1944 + readonly path: string;
1945 + readonly status: WithheldFileStatus;
1946 + readonly onLoad: ((path: string) => void) | undefined;
1947 +}) {
1948 + return (
1949 + <div className="flex items-center gap-2 bg-warning/8 px-3 py-2 text-xs text-warning-foreground">
1950 + <TriangleAlertIcon aria-hidden className="size-3.5 shrink-0 text-warning" />
1951 + <span>
1952 + {status === "error"
1953 + ? "Couldn't load this diff."
1954 + : status === "empty"
1955 + ? "No text diff for this file."
1956 + : "Diff too large to display."}
1957 + </span>
1958 + {onLoad === undefined || status === "empty" ? null : (
1959 + <Button
1960 + size="micro"
1961 + variant="warning-outline"
1962 + disabled={status === "loading"}
1963 + onClick={() => onLoad(path)}
1964 + >
1965 + {status === "loading" ? "Loading..." : status === "error" ? "Retry" : "Load diff"}
1966 + </Button>
1967 + )}
1968 + </div>
1969 + );
1970 +}
1971 +
1972 export default PullRequestCodeTab;
apps/web/src/components/pullRequest/cutLineNotes.ts new
+49
@@ -0,0 +1,49 @@
1 +import { cutLineNoteStart } from "@t3tools/shared/diffCutLines";
2 +
3 +const HIGHLIGHT_NAME = "t3-cut-line-note";
4 +
5 +/**
6 + * Goes in the diff's shadow root, where the highlighted text lives. A file with cut lines cannot
7 + * load the unchanged lines around them, so it drops the controls that would.
8 + */
9 +export const CUT_LINES_CSS = `
10 +::highlight(${HIGHLIGHT_NAME}) {
11 + color: var(--color-warning-foreground);
12 + background-color: color-mix(in srgb, var(--color-warning) 18%, transparent);
13 +}
14 +:host([data-cut-lines]) :is([data-expand-button], [data-expand-all-button]) {
15 + display: none;
16 +}`;
17 +
18 +let highlight: Highlight | null = null;
19 +
20 +/**
21 + * Styles cut-line notes so they do not read as code. Lines this long render untokenized, one
22 + * text node each, so a range highlight is the only way to reach the note without the code.
23 + */
24 +export function markCutLineNotes(fileContainer: HTMLElement): void {
25 + const root = fileContainer.shadowRoot;
26 + if (root === null || typeof Highlight === "undefined" || !CSS.highlights) return;
27 + if (highlight === null) {
28 + highlight = new Highlight();
29 + CSS.highlights.set(HIGHLIGHT_NAME, highlight);
30 + }
31 + const marked = new Set<Node>();
32 + // A range over a removed row collapses onto the row's parent rather than disconnecting.
33 + for (const range of highlight) {
34 + if (range.collapsed || !range.startContainer.isConnected) highlight.delete(range);
35 + else marked.add(range.startContainer);
36 + }
37 + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
38 + for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) {
39 + if (marked.has(text)) continue;
40 + const value = text.nodeValue ?? "";
41 + const noteStart = cutLineNoteStart(value);
42 + if (noteStart === null) continue;
43 + const range = new Range();
44 + range.setStart(text, noteStart);
45 + range.setEnd(text, value.length);
46 + highlight.add(range);
47 + marked.add(text);
48 + }
49 +}
packages/contracts/src/pullRequest.ts
+6
@@ -319,6 +319,8 @@ export const PullRequestCapabilities = Schema.Struct({
319 * reported rather than that the repository runs none. Absent means an empty list says nothing.
320 */
321 checksAlwaysReport: Schema.optional(Schema.Boolean),
322 + /** The diff can read one file the paged diff withheld as too large (`PullRequestDiffInput.path`). */
323 + withheldFileDiff: Schema.optional(Schema.Boolean),
324 });
325 export type PullRequestCapabilities = typeof PullRequestCapabilities.Type;
326
@@ -725,6 +727,8 @@ export const PullRequestDiffInput = Schema.Struct({
727 ...PullRequestRef.fields,
728 cursor: Schema.optional(TrimmedNonEmptyString),
729 commit: Schema.optional(TrimmedNonEmptyString),
730 + /** Reads one file the paged diff withheld as too large; ignores `cursor`. */
731 + path: Schema.optional(TrimmedNonEmptyString),
732 });
733 export type PullRequestDiffInput = typeof PullRequestDiffInput.Type;
734
@@ -741,6 +745,8 @@ export const PullRequestDiffResult = Schema.Struct({
745 truncated: Schema.Boolean,
746 nextCursor: Schema.NullOr(TrimmedNonEmptyString),
747 omittedFileStats: Schema.optional(Schema.Array(PullRequestOmittedFileStat)),
748 + /** On the first page: files this diff withholds can be read one at a time with `path`. */
749 + withheldFilesReadable: Schema.optional(Schema.Boolean),
750 });
751 export type PullRequestDiffResult = typeof PullRequestDiffResult.Type;
752
packages/shared/package.json
+4
@@ -463,6 +463,10 @@
463 "types": "./src/cliRelease.ts",
464 "import": "./src/cliRelease.ts"
465 },
466 + "./diffCutLines": {
467 + "types": "./src/diffCutLines.ts",
468 + "import": "./src/diffCutLines.ts"
469 + },
470 "./gitPatchPath": {
471 "types": "./src/gitPatchPath.ts",
472 "import": "./src/gitPatchPath.ts"
packages/shared/src/diffCutLines.ts new
+17
@@ -0,0 +1,17 @@
1 +// A withheld file's diff line the server cut short ends in this note, which clients style apart.
2 +const CUT_LINE_NOTE = / …\[[\d,]+ more characters\]$/;
3 +
4 +export function cutLineNote(omittedCharacters: number): string {
5 + return ` …[${omittedCharacters.toLocaleString("en-US")} more characters]`;
6 +}
7 +
8 +/** Where a cut line's note starts, past its leading space, or null for a whole line. */
9 +export function cutLineNoteStart(line: string): number | null {
10 + if (!line.endsWith("more characters]")) return null;
11 + const note = CUT_LINE_NOTE.exec(line);
12 + return note === null ? null : note.index + 1;
13 +}
14 +
15 +export function hasCutLines(patch: string): boolean {
16 + return new RegExp(CUT_LINE_NOTE.source, "m").test(patch);
17 +}
packages/source-control-core/src/server/PullRequestProvider.ts
+2
@@ -249,6 +249,7 @@ export interface ProviderDiffSlice {
249 readonly truncated: boolean;
250 readonly nextCursor: string | null;
251 readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
252 + readonly withheldFilesReadable?: boolean;
253 }
254
255 export interface ProviderDiffFileContents {
@@ -455,6 +456,7 @@ export interface PullRequestProviderApi {
456 readonly number: number;
457 readonly cursor?: string | undefined;
458 readonly commit?: string | undefined;
459 + readonly path?: string | undefined;
460 },
461 ) => Effect.Effect<ProviderDiffSlice, PullRequestProviderError>;
462
packages/source-control-core/src/server/diffFileRevisions.test.ts
+21 -1
@@ -1,6 +1,10 @@
1 import { assert, describe, it } from "@effect/vitest";
2
3 -import { parseDiffFilePaths, parseDiffFileRevisions } from "./diffFileRevisions.ts";
3 +import {
4 + diffFileSection,
5 + parseDiffFilePaths,
6 + parseDiffFileRevisions,
7 +} from "./diffFileRevisions.ts";
8
9 function patchOf(...lines: ReadonlyArray<string>): string {
10 return `${lines.join("\n")}\n`;
@@ -257,3 +261,19 @@ describe("parseDiffFilePaths", () => {
261 ]);
262 });
263 });
264 +
265 +describe("diffFileSection", () => {
266 + it("picks a file by where it ends up, so a swapped rename is not read as its partner", () => {
267 + const aToB = patchOf("diff --git a/a.ts b/b.ts", "rename from a.ts", "rename to b.ts");
268 + const bToA = patchOf("diff --git a/b.ts b/a.ts", "rename from b.ts", "rename to a.ts");
269 + const gone = patchOf(
270 + "diff --git a/gone.ts b/gone.ts",
271 + "deleted file mode 100644",
272 + "--- a/gone.ts",
273 + "+++ /dev/null",
274 + );
275 + const patch = `${aToB}${bToA}${gone}`;
276 + assert.strictEqual(diffFileSection(patch, "a.ts"), bToA);
277 + assert.strictEqual(diffFileSection(patch, "gone.ts"), gone);
278 + });
279 +});
packages/source-control-core/src/server/diffFileRevisions.ts
+35
@@ -1,3 +1,4 @@
1 +import { cutLineNote } from "@t3tools/shared/diffCutLines";
2 import { unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
3
4 const ENTRY = "diff --git ";
@@ -128,3 +129,37 @@ export function parseDiffFilePaths(
129 (oldPath ?? newPath) === null ? [] : [{ oldPath, newPath }],
130 );
131 }
132 +
133 +function nextEntry(patch: string, from: number): number {
134 + const at = patch.indexOf(`\n${ENTRY}`, from);
135 + return at === -1 ? -1 : at + 1;
136 +}
137 +
138 +/** The one file's section of a multi-file patch, or null when no section names `path`. */
139 +export function diffFileSection(patch: string, path: string): string | null {
140 + let start = patch.startsWith(ENTRY) ? 0 : nextEntry(patch, 0);
141 + while (start !== -1) {
142 + const end = nextEntry(patch, start);
143 + const section = end === -1 ? patch.slice(start) : patch.slice(start, end);
144 + // Only the header names the file; hunks can be megabytes.
145 + const hunk = section.indexOf("\n@@");
146 + const [entry] = parseEntries(hunk === -1 ? section : section.slice(0, hunk));
147 + if (entry !== undefined && (entry.newPath ?? entry.oldPath) === path) return section;
148 + start = end;
149 + }
150 + return null;
151 +}
152 +
153 +/** Cuts hunk lines past `maxLength` and says how much was cut; headers stay whole. */
154 +export function truncateLongDiffLines(patch: string, maxLength: number): string {
155 + let inBody = false;
156 + return patch
157 + .split("\n")
158 + .map((line) => {
159 + if (line.startsWith(ENTRY)) inBody = false;
160 + else if (line.startsWith("@@")) inBody = true;
161 + if (!inBody || line.length <= maxLength + 1) return line;
162 + return `${line.slice(0, maxLength + 1)}${cutLineNote(line.length - 1 - maxLength)}`;
163 + })
164 + .join("\n");
165 +}
packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+30
@@ -3099,6 +3099,8 @@ layer("GitHubPullRequestApi.layer", (it) => {
3099
3100 assert.isFalse(diff.truncated);
3101 assert.isNull(diff.nextCursor);
3102 + // The refusal covers one file's read too.
3103 + assert.isUndefined(diff.withheldFilesReadable);
3104 expect(diff.patch).toContain("diff --git a/src/file1.ts b/src/file1.ts");
3105 expect(diff.patch).toContain("diff --git a/src/file2.ts b/src/file2.ts");
3106 assert.strictEqual(callAt(1).host, "github.acme.dev");
@@ -3106,6 +3108,33 @@ layer("GitHubPullRequestApi.layer", (it) => {
3108 }),
3109 );
3110
3111 + it.effect("cuts one withheld file out of GitHub's whole diff", () =>
3112 + Effect.gen(function* () {
3113 + const sdk = "diff --git a/patches/sdk.patch b/patches/sdk.patch\n@@ -1 +1 @@\n-old\n+new\n";
3114 + const patch = `diff --git a/a.ts b/a.ts\n@@ -1 +1 @@\n-a\n+b\n${sdk}diff --git a/z.ts b/z.ts\n@@ -1 +1 @@\n-y\n+z\n`;
3115 + mockedExecute.mockReturnValueOnce(Effect.succeed(output(patch)));
3116 + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3117 + const ref = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 };
3118 + const file = yield* cli.getPullRequestDiff({ ...ref, path: "patches/sdk.patch" });
3119 + expect(file).toEqual({ patch: sdk, truncated: false, nextCursor: null });
3120 + expect(pathAt(0)).toBe("repos/acme/web/pulls/7");
3121 + expect(callAt(0)).toMatchObject({ kind: "rest", accept: "application/vnd.github.diff" });
3122 +
3123 + const minified = `diff --git a/b.js b/b.js\n@@ -10,2 +10,2 @@\n ${"c".repeat(1200)}\n-${"a".repeat(3000)}\n+${"b".repeat(1500)}\n`;
3124 + mockedExecute.mockReturnValueOnce(Effect.succeed(output(minified)));
3125 + const shortened = yield* cli.getPullRequestDiff({ ...ref, path: "b.js" });
3126 + expect(shortened.patch).toBe(
3127 + `diff --git a/b.js b/b.js\n@@ -10,2 +10,2 @@\n ${"c".repeat(1000)} …[200 more characters]\n-${"a".repeat(1000)} …[2,000 more characters]\n+${"b".repeat(1000)} …[500 more characters]\n`,
3128 + );
3129 +
3130 + mockedExecute.mockReturnValueOnce(Effect.succeed(output(patch, true)));
3131 + const error = yield* Effect.flip(
3132 + cli.getPullRequestDiff({ ...ref, path: "patches/sdk.patch" }),
3133 + );
3134 + expect(error._tag).toBe("GitHubPullRequestReadError");
3135 + }),
3136 + );
3137 +
3138 it.effect("hands back a cursor for the next page rather than walking on by itself", () =>
3139 Effect.gen(function* () {
3140 mockedExecute.mockReturnValueOnce(Effect.fail(diffRefused));
@@ -3992,6 +4021,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
4021 assert.strictEqual(pathAt(1), "repos/acme/web/pulls/7/files?per_page=100&page=1");
4022 expect(slice.patch).toContain("src/file1.ts");
4023 expect(slice.patch).not.toContain("diff --git a/a b/a");
4024 + assert.isTrue(slice.withheldFilesReadable);
4025 assert.strictEqual(mockedExecute.mock.calls.length, 2);
4026 }),
4027 );
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+71 -22
@@ -1,4 +1,8 @@
1 import { isCommitSha, normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
2 +import {
3 + diffFileSection,
4 + truncateLongDiffLines,
5 +} from "@t3tools/source-control-core/server/diffFileRevisions";
6 import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
7 import { KnownWorkflowRuns, makeChecksRevalidator } from "./gitHubConditionalChecks.ts";
8 import { runGitHubStackAction, type GitHubStackActionError } from "./githubStackActions.ts";
@@ -378,6 +382,9 @@ const decodePullRequestActionState = Schema.decodeUnknownEffect(PullRequestActio
382
383 /** A large pull request can produce a multi-megabyte patch; past this it is truncated. */
384 const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
385 +const WITHHELD_FILE_DIFF_MAX_OUTPUT_BYTES = 32 * 1024 * 1024;
386 +// Withheld files are mostly minified bundles; megabyte lines would freeze the client's layout.
387 +const WITHHELD_FILE_MAX_LINE_LENGTH = 1_000;
388 const DIFF_TIMEOUT = Duration.seconds(60);
389 const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
390
@@ -470,6 +477,7 @@ export interface GitHubPullRequestDiffSlice {
477 readonly truncated: boolean;
478 readonly nextCursor: string | null;
479 readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
480 + readonly withheldFilesReadable?: boolean;
481 }
482
483 export interface GitHubPullRequestFilesViewed {
@@ -615,6 +623,7 @@ export class GitHubPullRequestApi extends Context.Service<
623 readonly number: number;
624 readonly cursor?: string | undefined;
625 readonly commit?: string | undefined;
626 + readonly path?: string | undefined;
627 }) => Effect.Effect<GitHubPullRequestDiffSlice, GitHubPullRequestApiError>;
628
629 readonly getPullRequestDiffFileContents: (input: {
@@ -2244,36 +2253,76 @@ export const make = Effect.gen(function* () {
2253 if (input.commit !== undefined && !isCommitSha(input.commit)) {
2254 return Effect.fail(new GitHubDiffCommitError({ cwd: input.cwd }));
2255 }
2256 + const { owner, name } = parseRepositorySelector(input.repository);
2257 + const fullDiff = (maxResponseBytes: number) =>
2258 + api.rest({
2259 + host: input.host,
2260 + operation: "getPullRequestDiff",
2261 + path:
2262 + input.commit === undefined
2263 + ? `repos/${owner}/${name}/pulls/${input.number}`
2264 + : `repos/${owner}/${name}/commits/${input.commit}`,
2265 + accept: "application/vnd.github.diff",
2266 + maxResponseBytes,
2267 + timeout: DIFF_TIMEOUT,
2268 + });
2269 + // GitHub has no per-file diff, so a withheld file is cut from the whole patch here and
2270 + // only its section reaches the client.
2271 + if (input.path !== undefined) {
2272 + const path = input.path;
2273 + return fullDiff(WITHHELD_FILE_DIFF_MAX_OUTPUT_BYTES).pipe(
2274 + Effect.flatMap((response) => {
2275 + const section = response.truncated ? null : diffFileSection(response.body, path);
2276 + if (section === null) {
2277 + return Effect.fail(
2278 + readError(
2279 + input.cwd,
2280 + "getPullRequestDiff",
2281 + new Error(
2282 + response.truncated
2283 + ? `The diff for ${path} is too large to load.`
2284 + : `GitHub's diff does not include ${path}.`,
2285 + ),
2286 + ),
2287 + );
2288 + }
2289 + return Effect.succeed({
2290 + patch: truncateLongDiffLines(section, WITHHELD_FILE_MAX_LINE_LENGTH),
2291 + truncated: false,
2292 + nextCursor: null,
2293 + });
2294 + }),
2295 + );
2296 + }
2297 if (input.cursor !== undefined) {
2298 const page = diffCursorPage(input.cursor);
2299 return page === null
2300 ? Effect.fail(new GitHubDiffCursorError({ cwd: input.cwd }))
2301 : filesPage(page);
2302 }
2303 + // A withheld file is read from the whole diff, so it is readable unless GitHub refused that.
2304 + const readableFirstPage = () =>
2305 + filesPage(1).pipe(
2306 + Effect.map((slice): GitHubPullRequestDiffSlice => ({
2307 + ...slice,
2308 + withheldFilesReadable: true,
2309 + })),
2310 + );
2311 if (input.commit !== undefined) {
2254 - return filesPage(1);
2312 + return readableFirstPage();
2313 }
2256 - const { owner, name } = parseRepositorySelector(input.repository);
2257 - return api
2258 - .rest({
2259 - host: input.host,
2260 - operation: "getPullRequestDiff",
2261 - path: `repos/${owner}/${name}/pulls/${input.number}`,
2262 - accept: "application/vnd.github.diff",
2263 - maxResponseBytes: DIFF_MAX_OUTPUT_BYTES,
2264 - timeout: DIFF_TIMEOUT,
2265 - })
2266 - .pipe(
2267 - Effect.flatMap((response) =>
2268 - response.truncated
2269 - ? filesPage(1)
2270 - : Effect.succeed({ patch: response.body, truncated: false, nextCursor: null }),
2271 - ),
2272 - // Above 300 changed files, GitHub returns 406; use the paged files API.
2273 - Effect.catchTags({
2274 - GitHubApiResponseError: (error) => filesPage(1).pipe(Effect.mapError(() => error)),
2275 - }),
2276 - );
2314 + return fullDiff(DIFF_MAX_OUTPUT_BYTES).pipe(
2315 + Effect.flatMap((response) =>
2316 + response.truncated
2317 + ? readableFirstPage()
2318 + : Effect.succeed({ patch: response.body, truncated: false, nextCursor: null }),
2319 + ),
2320 + // Above 300 changed files (or about 20,000 lines), GitHub returns 406; use the paged
2321 + // files API. That refusal also covers a single file's read, so none is offered.
2322 + Effect.catchTags({
2323 + GitHubApiResponseError: (error) => filesPage(1).pipe(Effect.mapError(() => error)),
2324 + }),
2325 + );
2326 }),
2327
2328 getPullRequestDiffFileContents,
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+1
@@ -59,6 +59,7 @@ const CAPABILITIES: PullRequestCapabilities = {
59 // Statuses and check runs land on the head commit itself and are read whole, so an empty list
60 // after a push is CI that never started rather than a read that saw nothing.
61 checksAlwaysReport: true,
62 + withheldFileDiff: true,
63 };
64
65 const UNAVAILABLE_REQUIREMENT = {
packages/source-control-testing/src/fakeSourceControlDriver.ts
+1
@@ -43,6 +43,7 @@ export function fakePullRequestProvider(
43 review: FULL_REVIEW,
44 reviewers: FULL_REVIEWERS,
45 edit: { changeRequest: true, comment: true },
46 + withheldFileDiff: true,
47 },
48 getViewer: () => Effect.succeed("bilal"),
49 getViewerPermissions: () =>