t3code icon indicating copy to clipboard operation
t3code copied to clipboard

Python docstring bodies highlight as code in the diff panel because partial patches are tokenized without grammar context

Open KelvinChung2000 opened this issue 2 months ago • 8 comments

What happened

The diff view syntax highlighting is not correct. A python file, mainly in comment, lines following become green. Block comment did not render green.

Screenshot of the affected diff is attached at the end of this issue.

In a Python file shown in the desktop app's diff panel, the body of a triple-quoted docstring is highlighted as Python source. Prose words inside it (and, in, is, not, If True, escape, are) get keyword colours and bool gets a type colour, and the colouring shifts again after the closing """. A single-line # comment in the same view highlights correctly.

Diagnosis

The diff panel feeds Shiki a synthetic file assembled from the patch's own lines, with no grammar state carried in, so any construct opened above the patch's first line is invisible to the tokenizer.

The chain, at v0.0.40:

  1. apps/web/src/lib/diffRendering.ts:119 parses a unified patch with parsePatchFiles. That yields FileDiffMetadata with isPartial: true, which per @pierre/diffs types.d.ts:263-292 means deletionLines/additionLines hold only the context and changed lines present in the patch, not the whole file. compactPartialHunkOffsets (diffRendering.ts:84) keeps collapsedBefore so the gaps render as "N unmodified lines" separators, but those lines are absent from the data.
  2. @pierre/[email protected], dist/utils/renderDiffWithHighlighter.js, groups those lines into buckets and calls renderTwoFiles, which concatenates a bucket's lines into a contents string and passes it to highlighter.codeToHast. Neither Shiki's grammarState nor grammarContextCode is supplied, so every call starts from the initial state.
  3. shouldGroupAll = !forcePlainText && !diff.isPartial is false for a partial patch, so getBucketForHunk keys buckets by hunkIndex. This is not where a fix lives: grouping all hunks into one bucket would still concatenate the lines either side of an omitted gap, so the docstring opener would still be missing. Fixing it means supplying the missing context, either full file contents or grammarContextCode.

A Python docstring opened before the patch's first line therefore tokenizes as code. The same applies to any multi-line construct: block strings, template literals, heredocs, embedded languages.

There is one path out of the partial state. components/FileDiff.js:390 expandHunk calls loadFilesIfNecessary, which runs loadDiffFiles and then hydratePartialDiff, setting isPartial = false so the next render tokenizes whole file contents. Both renderers/DiffHunksRenderer.js:1091 and components/VirtualizedFileDiff.js:1020 gate that on hasFileLoader, and apps/web/src/components/DiffPanel.tsx:315-334 returns undefined for the loader unless the view is the active thread's git branch or working-tree diff with selectedTurnId === null. The user reports the wrong colours in every diff view they use, and in none of them were the "N unmodified lines" bands expandable, so no hydration ran anywhere and the colours stayed wrong throughout.

A library upgrade does not fix it. @pierre/diffs 1.4.2, the current latest, carries the same renderDiffWithHighlighter logic; the only changes since beta.10 are an appendItems helper and a default-theme tweak. No grammar-state threading was added.

Steps to reproduce

  1. In a Python file, write a function whose docstring body runs longer than the diff's context window, say 15 lines between the opening """ and the closing """.
  2. Change one line inside the docstring body, at least four lines below the opening """.
  3. Open the diff panel on that change.
  4. Expected: the whole docstring body renders in the string colour.
  5. Actual: words inside the docstring body are coloured as Python keywords and types, and the colouring changes again at the closing """.
  6. The reporter sees this in every diff view, with no expandable "N unmodified lines" bands in any of them, so no hydration ever runs. Where DiffPanel.tsx:315 does supply loadDiffFiles, expanding a band should hydrate to full contents and correct the colours; that bands were never expandable here suggests the loader is absent more widely than selectedTurnId !== null alone accounts for, which is worth checking alongside the tokenizer fix.

Version

0.0.40

Environment

Linux x64 (7.1.1-76070101-generic), Node v24.10.0. Server CLI launched via bunx t3; the UI is the desktop app against a local server on 127.0.0.1:3773.

Evidence

# @pierre/[email protected] dist/utils/renderDiffWithHighlighter.js
const shouldGroupAll = !forcePlainText && !diff.isPartial;
...
function getBucketForHunk(hunkIndex) {
  const index = shouldGroupAll ? 0 : hunkIndex;
  ...
}

# ... and in renderTwoFiles, in the same file
return getLineNodes(highlighter.codeToHast(cleanLastNewline(additionFile.contents), hastConfig));

# @pierre/[email protected] dist/types.d.ts, on FileDiffMetadata.isPartial
# "When true, `deletionLines`/`additionLines` contain only the lines present
#  in the patch and hunk expansion is unavailable."

# apps/web/src/lib/diffRendering.ts:119
const parsedPatches = parsePatchFiles(
  normalizedPatch,
  buildPatchCacheKey(normalizedPatch, cacheScope),
);

No server log or trace entries relate to this; the fault is entirely in the renderer.

Related issues

Not a duplicate of #11196 (incremental highlighting), which changes ChatMarkdown only, merged to the legend-perf/incremental-markdown branch after v0.0.40, and states it does not touch the diff viewers. #10830 is theme import, #10822 is progressive diff loading; neither covers grammar state. No existing issue matches.

Fix applied or workaround

Nothing was changed on the machine, and no workaround was available in the view where this was hit. Where a diff view does supply loadDiffFiles, expanding a collapsed context band hydrates the diff to full file contents and restores correct highlighting.

Filed by

claude (opus-5) via t3 triage

KelvinChung2000 avatar Sep 14 '26 13:09 KelvinChung2000

Image

KelvinChung2000 avatar Sep 14 '26 13:09 KelvinChung2000

Triage

Confirmed as a real highlighting bug in the desktop/web diff panel. Not a duplicate of #11196, #10830, or #10822.

What we verified

The report matches current main.

  1. getRenderablePatch in apps/web/src/lib/diffRendering.ts parses unified patches with parsePatchFiles, which marks files isPartial: true (hunk + context only).
  2. @pierre/diffs (1.3.0-beta.10 in catalog; same logic still in 1.4.2) concatenates those lines and calls Shiki codeToHast with no grammarState / grammarContextCode. shouldGroupAll is false for partial patches; grouping would not restore an omitted """ anyway.
  3. DiffPanel.tsx only passes loadDiffFiles for live git branch / working-tree when selectedTurnId === null. Turn/checkpoint diffs and chat FileDiffs never hydrate. That matches “no expandable bands” after an agent turn.
  4. The existing @pierre/diffs workspace patch is virtualizer/layout only. Chat already resumes Shiki from completed-line grammar state (incrementalHighlighting.ts / #11196); diffs do not.

Same class of miss is possible on mobile review highlighting (visible hunk rows tokenized without prefix context).

Next step

Accept. Preferred fix is two-sided:

  • App: supply loadDiffFiles for turn/checkpoint diffs (helpers already exist in diffFileContents.ts) and consider auto-hydrate so first paint is correct.
  • Tokenizer: thread grammar context through @pierre/diffs (local patch or upstream). Do not treat a library bump as the fix.

Repro: Python function whose docstring body is longer than hunk context; change a line ≥4 lines below the opening """; open the diff panel (especially a turn diff).

juliusmarminge avatar Sep 14 '26 13:09 juliusmarminge

Hey, I'd like to take this one. Plan: return the checkpoint refs with turn diffs and add a revision-range file loader so turn diffs get loadDiffFiles like the working-tree view, leaving the pierre patch and diffRendering.ts alone, so it shouldn't collide with #14772 (Svelte-only grammarContextCode). @juliusmarminge is the V2 freeze still on for the checkpoint code, or is this OK to go?

anzal1 avatar Oct 17 '26 04:10 anzal1

Reproduced on current main 89fe509232, Linux x64, real web dev server and Chromium, with an isolated Python repository. Changed a line inside a 20-line docstring, beyond the three-line patch context.

Both Changes and a real Codex turn's Latest turn diff colour prose as Python keywords/types. Expanding omitted context corrects the live Changes view; Latest turn has no expansion controls and keeps the wrong colours.

Latest turn: Python docstring prose incorrectly coloured as code

juliusmarminge avatar Oct 22 '26 01:10 juliusmarminge

Got a fix on a branch: turn diffs now get loadDiffFiles (refs returned with the checkpoint diff + a revision-range file loader), so Latest turn gets expand bands and expanding fixes the colours, same as Changes. First paint is still wrong though. Auto-hydrating would mean a git show per file, and the cleaner fix is grammar context in the pierre patch #14772 is touching. Good to open this as step one, or would you rather wait for #14772?

anzal1 avatar Oct 24 '26 11:10 anzal1

Hi, what is the current progress on this?

KelvinChung2000 avatar Nov 09 '26 16:11 KelvinChung2000

FYI: Vue SFCs run into the same bug. If a hunk's context doesn't include the <script setup lang="ts"> opening tag, the Vue grammar starts the hunk in template/HTML mode.

That means the whole script block then shows as plain text, and only tag-like bits such as defineProps<Props>() and </script> get colors, makign the code harder to review.

Svelte (#14772, now closed) and probably other multi-language SFC formats (Astro, etc.) have the same problem, so a full-file-context approach like #23347 would cover all of them, not just Python docstrings.

TheAlexLichter avatar Nov 13 '26 14:11 TheAlexLichter

Same bug with Elixir @doc """ heredocs, and here it flips the whole rest of the hunk, not just the docstring.

The hunk starts at line 27, inside a @doc """ whose opening is in the 26 collapsed lines above. The tokenizer starts outside the string, so every later """ toggles the state the wrong way:

  • line 28 """ (actually the closing delimiter) opens a string, so the code on lines 29-31 renders as a string
  • line 31 @doc """ closes it, so the doc prose on lines 32-34 renders as code (for, in, and and is get keyword colours)
  • line 35 """ opens again, so the real code on lines 36-52 (def, with, cond) renders as one plain string colour
  • and it keeps alternating until the end of the file

So code and docs end up swapped for the entire hunk. Any language with multi-line strings or block comments will be hit the same way (Elixir heredocs and ~S""" sigils, Python, JS template literals, /* */), which is another reason to fix it with grammar context or full-file context (#23347) rather than per-language.

screenshot-2026-11-27_15-30-31-t3code

maxguzenski avatar Nov 27 '26 18:11 maxguzenski