@devries-cameron20 / t3code Mirror · read-only / commits / 081afe08dc
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, 07:15 UTC

fix(mobile): PR diffs show syntax colors before the full file arrives (#38444)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 18, 2026 at 11:33 UTC 081afe08dcd15d745920d2d6be76c5e29d63c091
3 files changed +103 -66
apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
+10 -4
@@ -287,6 +287,12 @@ describe("highlightNativeReviewDiffVisibleRows", () => {
287 (token: { color: string | null }) => token.color !== null,
288 ),
289 ).toBe(true);
290 + // The blocked neighbor is colored from its patch while its source loads.
291 + await vi.waitFor(() => expect(chunks).toHaveBeenCalledTimes(2));
292 + const provisional = chunks.mock.calls[1]![0];
293 + const neighborIds = Array.from({ length: 5 }, (_, index) => `neighbor-${index}`);
294 + expect(Object.keys(provisional.tokensByRowId)).toEqual(neighborIds);
295 + expect(provisional.retryableRowIds).toEqual(neighborIds);
296 } finally {
297 neighborResponse.resolve({ oldContents: "", newContents: source });
298 await highlighting;
@@ -606,8 +612,10 @@ describe("source context", () => {
612 expect(result.tokensByRowId["new-tail"]).toEqual(newTokens[2]);
613 });
614
609 - it("leaves mismatched and unavailable source revisions plain", async () => {
615 + it("uses patch grammar for mismatched and unavailable source revisions", async () => {
616 const rows = [sourceRow("add", 3)];
617 + const patchTokens = (await highlight(rows)).tokensByRowId[rows[0]!.id];
618 + expect(patchTokens!.some((token) => token.color !== null)).toBe(true);
619 for (const source of [null, { oldContents: "", newContents: "different revision" }]) {
620 const result = await highlightNativeReviewDiffVisibleRows({
621 rows,
@@ -617,9 +625,7 @@ describe("source context", () => {
625 lastRowIndex: 0,
626 overscanRows: 0,
627 });
620 - expect(result.tokensByRowId[rows[0]!.id]).toEqual([
621 - { content: NEW_SOURCE[2], color: null, fontStyle: null },
622 - ]);
628 + expect(result.tokensByRowId[rows[0]!.id]).toEqual(patchTokens);
629 }
630 });
631 });
apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
+88 -61
@@ -239,6 +239,16 @@ function makePlainTokenFallback(
239 return [{ content: row.content || " ", color: null, fontStyle: null }];
240 }
241
242 +function settlesWithinTask(promise: Promise<unknown>): Promise<boolean> {
243 + return Promise.race([
244 + promise.then(
245 + () => true,
246 + () => true,
247 + ),
248 + new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 0)),
249 + ]);
250 +}
251 +
252 export async function highlightNativeReviewDiffVisibleRows(
253 input: HighlightNativeReviewDiffVisibleRowsInput,
254 ): Promise<{
@@ -317,6 +327,46 @@ export async function highlightNativeReviewDiffVisibleRows(
327 return cached;
328 };
329
330 + // Patch-only grammar: each run of consecutive lines is tokenized on its own.
331 + const highlightSegmentRows = (
332 + rowIds: ReadonlySet<string>,
333 + out: Record<string, ReadonlyArray<NativeReviewDiffToken>>,
334 + ) => {
335 + const sourceSegments = getSourceSegments(input.rows);
336 + const selectedSegments = new Map<
337 + SourceSegment,
338 + { firstSelected: number; lastSelected: number }
339 + >();
340 + for (const row of selectedRows) {
341 + if (!rowIds.has(row.id)) continue;
342 + const source = sourceSegments.get(row.id);
343 + if (!source) continue;
344 + const selection = selectedSegments.get(source.segment);
345 + if (selection) selection.lastSelected = source.index;
346 + else
347 + selectedSegments.set(source.segment, {
348 + firstSelected: source.index,
349 + lastSelected: source.index,
350 + });
351 + }
352 + for (const [segment, { firstSelected, lastSelected }] of selectedSegments) {
353 + if (input.signal?.aborted) return;
354 + const file = fileMap.get(segment.fileId);
355 + if (!file) continue;
356 + const tokens = tokenize(
357 + segment,
358 + () => segment.rows.map((row) => row.content).join("\n"),
359 + file.language,
360 + );
361 + for (let index = firstSelected; index <= lastSelected; index += 1) {
362 + const row = segment.rows[index]!;
363 + if (rowIds.has(row.id) && displaySide(row) === segment.side) {
364 + out[row.id] = tokens.highlightLine(index, input.scheme) ?? makePlainTokenFallback(row);
365 + }
366 + }
367 + }
368 + };
369 +
370 const sourceFiles = new Map<string, NativeReviewDiffLineRow[]>();
371 for (const row of selectedRows) {
372 if (!fileMap.get(row.fileId)?.loadContents) continue;
@@ -324,37 +374,54 @@ export async function highlightNativeReviewDiffVisibleRows(
374 if (fileRows) fileRows.push(row);
375 else sourceFiles.set(row.fileId, [row]);
376 }
327 - const emitFileChunk = (fileRows: ReadonlyArray<NativeReviewDiffLineRow>) => {
328 - if (!input.onChunk || input.signal?.aborted) return;
329 - const rowIds = new Set(fileRows.map((row) => row.id));
377 + const emitChunk = (
378 + chunkTokens: Record<string, ReadonlyArray<NativeReviewDiffToken>>,
379 + chunkRetryableRowIds: ReadonlyArray<string>,
380 + ) => {
381 + const rowCount = Object.keys(chunkTokens).length;
382 + if (!input.onChunk || input.signal?.aborted || rowCount === 0) return;
383 input.onChunk({
331 - tokensByRowId: Object.fromEntries(fileRows.map((row) => [row.id, tokensByRowId[row.id]!])),
332 - retryableRowIds: retryableRowIds.filter((id) => rowIds.has(id)),
333 - rowCount: fileRows.length,
384 + tokensByRowId: chunkTokens,
385 + retryableRowIds: chunkRetryableRowIds,
386 + rowCount,
387 durationMs: Math.round(performance.now() - startedAt),
388 });
389 };
390 + // Full sources arrive over the network. Until they do, show patch-only colors
391 + // as retryable rows, which the full-source tokens then replace.
392 + const emitProvisionalChunk = (rows: ReadonlyArray<NativeReviewDiffLineRow>) => {
393 + if (!input.onChunk) return;
394 + const provisional: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
395 + highlightSegmentRows(new Set(rows.map((row) => row.id)), provisional);
396 + traceDiffHighlight("highlight-provisional", { request, rows: rows.length });
397 + emitChunk(provisional, Object.keys(provisional));
398 + };
399 // The file filling the viewport should not wait for a sliver of its neighbor.
338 - for (const [fileId, fileRows] of [...sourceFiles].sort((a, b) => b[1].length - a[1].length)) {
400 + const sourceEntries = [...sourceFiles].sort((a, b) => b[1].length - a[1].length);
401 + let provisionalFrom = sourceEntries.length;
402 + for (const [entryIndex, [fileId, fileRows]] of sourceEntries.entries()) {
403 if (input.signal?.aborted) break;
404 const file = fileMap.get(fileId)!;
405 const fileTraceId = diffHighlightTraceId(fileId);
406 traceDiffHighlight("highlight-source", { request, file: fileTraceId, rows: fileRows.length });
407 + const loading = file.loadContents!(input.signal);
408 + if (entryIndex < provisionalFrom && !(await settlesWithinTask(loading))) {
409 + if (input.signal?.aborted) break;
410 + provisionalFrom = entryIndex;
411 + emitProvisionalChunk(sourceEntries.slice(entryIndex).flatMap(([, rows]) => rows));
412 + }
413 let source: NativeReviewDiffSource | null;
414 try {
345 - source = await file.loadContents!(input.signal);
415 + source = await loading;
416 } catch {
417 traceDiffHighlight("highlight-source-error", { request, file: fileTraceId });
348 - for (const row of fileRows) {
349 - selectedRowIds.delete(row.id);
350 - tokensByRowId[row.id] = makePlainTokenFallback(row);
351 - retryableRowIds.push(row.id);
352 - }
353 - emitFileChunk(fileRows);
418 + // Patch-only colors below, retried with the source on a later viewport.
419 + for (const row of fileRows) retryableRowIds.push(row.id);
420 continue;
421 }
422 if (input.signal?.aborted) break;
423 const contexts = source ? getFullSourceContexts(source) : null;
424 + const fileTokens: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
425 for (const side of ["old", "new"] as const) {
426 if (input.signal?.aborted) break;
427 const candidate = contexts?.[side];
@@ -371,75 +438,35 @@ export async function highlightNativeReviewDiffVisibleRows(
438 matches: !!context,
439 knownLines: context?.comparisonLines.length,
440 });
441 + if (!context) continue;
442 + // Rows the source cannot vouch for keep patch-only grammar below.
443 const matchingRows: { row: NativeReviewDiffLineRow; lineIndex: number }[] = [];
444 for (const row of fileRows) {
445 if (displaySide(row) !== side) continue;
377 - selectedRowIds.delete(row.id);
446 const lineNumber = side === "old" ? row.oldLineNumber : row.newLineNumber;
447 const lineIndex = typeof lineNumber === "number" ? lineNumber - 1 : -1;
448 if (
381 - context &&
449 lineIndex >= 0 &&
450 lineIndex < context.comparisonLines.length &&
451 context.comparisonLines[lineIndex] === row.content
452 ) {
453 matchingRows.push({ row, lineIndex });
387 - } else {
388 - // A changed revision or missing source cannot
389 - // supply trustworthy grammar. Do not cache guessed syntax colors.
390 - tokensByRowId[row.id] = makePlainTokenFallback(row);
454 }
455 }
393 - if (!context || matchingRows.length === 0) continue;
456 + if (matchingRows.length === 0) continue;
457 const tokens = tokenize(context, context.contents, file.language);
458 for (const { row, lineIndex } of matchingRows) {
396 - tokensByRowId[row.id] =
459 + selectedRowIds.delete(row.id);
460 + fileTokens[row.id] = tokensByRowId[row.id] =
461 tokens.highlightLine(lineIndex, input.scheme) ?? makePlainTokenFallback(row);
462 }
463 }
400 - emitFileChunk(fileRows);
464 + emitChunk(fileTokens, []);
465 await new Promise<void>((resolve) => setTimeout(resolve, 0));
466 }
467
404 - const selectedSegments = new Map<
405 - SourceSegment,
406 - { firstSelected: number; lastSelected: number }
407 - >();
468 if (selectedRowIds.size > 0 && !input.signal?.aborted) {
409 - const sourceSegments = getSourceSegments(input.rows);
410 - for (const row of selectedRows) {
411 - if (!selectedRowIds.has(row.id)) continue;
412 - const source = sourceSegments.get(row.id);
413 - if (!source) continue;
414 - const selection = selectedSegments.get(source.segment);
415 - if (selection) {
416 - selection.lastSelected = source.index;
417 - } else {
418 - selectedSegments.set(source.segment, {
419 - firstSelected: source.index,
420 - lastSelected: source.index,
421 - });
422 - }
423 - }
424 - }
425 -
426 - for (const [segment, { firstSelected, lastSelected }] of selectedSegments) {
427 - if (input.signal?.aborted) break;
428 - const file = fileMap.get(segment.fileId);
429 - if (!file) continue;
430 -
431 - const tokens = tokenize(
432 - segment,
433 - () => segment.rows.map((row) => row.content).join("\n"),
434 - file.language,
435 - );
436 - for (let index = firstSelected; index <= lastSelected; index += 1) {
437 - const row = segment.rows[index]!;
438 - if (selectedRowIds.has(row.id) && displaySide(row) === segment.side) {
439 - tokensByRowId[row.id] =
440 - tokens.highlightLine(index, input.scheme) ?? makePlainTokenFallback(row);
441 - }
442 - }
469 + highlightSegmentRows(selectedRowIds, tokensByRowId);
470 }
471
472 if (input.signal?.aborted) {
apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
+5 -1
@@ -137,7 +137,11 @@ export function useNativeReviewDiffHighlighting(input: {
137 : highlightedRowIdsRef.current,
138 signal: abortController.signal,
139 onChunk: (chunk) => {
140 - for (const rowId of Object.keys(chunk.tokensByRowId)) deliveredRowIds.add(rowId);
140 + // Provisional rows still need the final result's tokens.
141 + const retryable = new Set(chunk.retryableRowIds);
142 + for (const rowId of Object.keys(chunk.tokensByRowId)) {
143 + if (!retryable.has(rowId)) deliveredRowIds.add(rowId);
144 + }
145 enqueueChunk(chunk);
146 },
147 }),