Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ diffui/
- Branch-scoped state: reviewed status, comments and session live in `~/.config/diffui/{repo}/{branch}/`, where `{repo}` and `{branch}` are `_safe_name()` of the repo path and branch. `get_repo_root()` and `_cached_current_branch()` are `lru_cache`'d. `_save_json` writes a temp file and renames it. `_load_json` moves an unparseable file aside to `.corrupt`, so the next save cannot overwrite it.
- Worktrees: `get_git_dir()` resolves the real git dir for regular repos and linked worktrees.
- Comments: `author_type` is `user` or `agent`. `category` is bug, suggestion, nit or question. `status` is open or resolved. The web UI locks a user's comment for editing once an agent replies (`canEdit` in `CommentDisplay.js`). The server does not enforce that. `agentColor()` hashes the author name, so each agent gets its own color.
- Word-level diff: `pair_diff_lines` pairs consecutive removes and adds, and `word_diff_ranges` uses `difflib.SequenceMatcher` for the changed word spans. Each word keeps its real character offsets (`_word_spans`), so indentation and runs of spaces do not shift the marks.
- Word-level diff: `pair_diff_lines` pairs consecutive removes and adds, and `word_diff_ranges` uses `difflib.SequenceMatcher` for the changed word spans. Each word keeps its real character offsets (`_word_spans`), so indentation and runs of spaces do not shift the marks. They render as `<mark class="word-hl">`, styled by the `word-hl-background`, `word-hl-underline` or `word-hl-off` class `useAppearance` puts on `<html>` from the `word_highlight` setting.
- Diff line `index`: `parse_diff_to_json` numbers every line of the diff text, and saved comments anchor on that number. `split_into_hunks` returns the lines before the first `@@` as a pseudo hunk. `parse_diff_to_json` emits neither that hunk nor the `@@` lines, but both still advance `index`. Skipping the count shifts every anchor. `file_note` (from `file_change_note`) is set when the header holds a rename, mode change, new or deleted file, or binary marker.
- `html=0` on `/api/diff` and `/api/file` skips Pygments HTML and word highlights. The TUI sends it and highlights `text` itself.
- Settings: `SettingsUpdate` in `models.py` limits `editor` to code, cursor, vim or nvim and `agent_cli` to claude, codex, opencode or cursor. A new agent CLI also needs an entry in `_AGENT_CMDS` (`routes_review.py`) and `_INTERACTIVE_CMDS` (`routes_agent_terminal.py`).
Expand Down Expand Up @@ -172,7 +172,7 @@ All in `~/.config/diffui/`:

| File | Scope | Format |
| --- | --- | --- |
| `settings.json` | Global | `{theme, editor, user_name, agent_cli, font_size, word_wrap, keybindings}` |
| `settings.json` | Global | `{theme, editor, user_name, agent_cli, font_size, word_wrap, word_highlight, keybindings}` |
| `{repo}/{branch}/reviewed.json` | Per branch | `{"path": mtime}` |
| `{repo}/{branch}/comments.json` | Per branch | `{"path": [{...}]}` |
| `{repo}/{branch}/session.json` | Per branch | `{activeFile, diffMode, showFileTree, showReviewed, scrollPositions}` |
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ The header shows the current scope. The browser has the same choices in its view
- The blame gutter shows the author and age of each line.
- `.md` files get a rendered preview and images show inline. Markdown is sanitized before rendering, and diagram blocks go to kroki.io.
- Font size and line wrap are in Settings and the command palette.
- Changed words inside a modified line are highlighted with a background, an underline, or not at all. Pick the style under "Changed words" in Settings, or cycle it from the command palette.
- `w` or the Whitespace button toggles ignore whitespace.
- `ctrl+click` (`cmd+click` on macOS) a line to open it in VS Code, Cursor, Vim or Neovim. Pick the editor in Settings.

Expand Down
2 changes: 1 addition & 1 deletion diffui/server/highlight.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def _apply_word_highlights(code_html: str, ranges: list[tuple[int, int]], code_p
end = code_html.index(";", i) + 1 if code_html[i] == "&" else i + 1
should_mark = plain_idx in marked_chars
if should_mark != in_highlight:
result.append("<mark>" if should_mark else "</mark>")
result.append('<mark class="word-hl">' if should_mark else "</mark>")
in_highlight = should_mark
result.append(code_html[i:end])
plain_idx += 1
Expand Down
1 change: 1 addition & 0 deletions diffui/server/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class SettingsUpdate(BaseModel):
agent_cli: str | None = Field(default=None, pattern="^(claude|codex|opencode|cursor)$")
font_size: int | None = Field(default=None, ge=8, le=32)
word_wrap: bool | None = None
word_highlight: str | None = Field(default=None, pattern="^(background|underline|off)$")
keybindings: dict[str, str] | None = None


Expand Down
2 changes: 2 additions & 0 deletions diffui/server/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def __init__(self) -> None:
self.agent_cli: str = saved.get("agent_cli", "claude")
self.font_size: int = saved.get("font_size", 13)
self.word_wrap: bool = saved.get("word_wrap", False)
self.word_highlight: str = saved.get("word_highlight", "background")
self.keybindings: dict[str, str] = saved.get("keybindings", {})
self.ignore_patterns: list[str] = []
self.theme_index: int = theme_index
Expand Down Expand Up @@ -133,6 +134,7 @@ def settings(self) -> dict:
"agent_cli": self.agent_cli,
"font_size": self.font_size,
"word_wrap": self.word_wrap,
"word_highlight": self.word_highlight,
"keybindings": self.keybindings,
}

Expand Down
8 changes: 6 additions & 2 deletions diffui/static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ function App() {
const [collapseAll, setCollapseAll] = useState(null);
const [fontSize, setFontSize] = useState(13);
const [wordWrap, setWordWrap] = useState(false);
const [wordHighlight, setWordHighlight] = useState('background');
const [keybindings, setKeybindings] = useState({});
const [commentsPulse, setCommentsPulse] = useState(false);
const diffRef = useRef(null);
Expand Down Expand Up @@ -189,12 +190,13 @@ function App() {
}
if (settings.font_size) setFontSize(settings.font_size);
if (settings.word_wrap !== undefined) setWordWrap(settings.word_wrap);
if (settings.word_highlight) setWordHighlight(settings.word_highlight);
if (settings.keybindings) setKeybindings(settings.keybindings);
if (session.activeFile) fetchDiff(session.activeFile);
});
}, []);

useAppearance({ themeCss, fontSize, wordWrap });
useAppearance({ themeCss, fontSize, wordWrap, wordHighlight });

const commentsPulseTimer = useRef(null);
const handleLiveEvents = useCallback((events) => {
Expand Down Expand Up @@ -300,6 +302,7 @@ function App() {
const handleSettingsChange = useCallback(async (settings) => {
if (settings.font_size !== undefined) setFontSize(settings.font_size);
if (settings.word_wrap !== undefined) setWordWrap(settings.word_wrap);
if (settings.word_highlight !== undefined) setWordHighlight(settings.word_highlight);
if (settings.keybindings !== undefined) setKeybindings(settings.keybindings);
const res = await sendJson('/api/settings', 'PUT', settings);
const data = await res.json();
Expand Down Expand Up @@ -437,7 +440,7 @@ function App() {
}, [reviewedCount, files.length]);

const { paletteCommands, handleCommand } = useKeyboard({
keybindings, fontSize, wordWrap,
keybindings, fontSize, wordWrap, wordHighlight,
showCompletionRef, dialogOpenRef, visibleFilesRef, activeFileRef,
handleFileSelect, handleToggleReview, handleCopyPath, handleSortByRisk, handleExportSummary,
handleCopyGitLabLink, handleNextUnreviewed, navigateComment, scrollToHunk, handleToggleWhitespace,
Expand Down Expand Up @@ -586,6 +589,7 @@ function App() {
onClose=${() => setShowSettings(false)}
fontSize=${fontSize}
wordWrap=${wordWrap}
wordHighlight=${wordHighlight}
keybindings=${keybindings}
/>
`}
Expand Down
13 changes: 12 additions & 1 deletion diffui/static/components/SettingsPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { kb } from '../lib/keys.js';

const html = htm.bind(h);

const WORD_HIGHLIGHT_OPTIONS = [['background', 'Background'], ['underline', 'Underline'], ['off', 'Off']];

const EDITORS = [
{ value: 'code', label: 'VS Code' },
{ value: 'cursor', label: 'Cursor' },
Expand All @@ -31,7 +33,7 @@ const REBINDABLE_KEYS = [
{ id: 'next-unreviewed', label: 'Next unreviewed' },
];

export function SettingsPanel({ onChange, onClose, fontSize, wordWrap, keybindings }) {
export function SettingsPanel({ onChange, onClose, fontSize, wordWrap, wordHighlight, keybindings }) {
const [settings, setSettings] = useState(null);
const [themes, setThemes] = useState([]);
const [showKeybindings, setShowKeybindings] = useState(false);
Expand Down Expand Up @@ -160,6 +162,15 @@ export function SettingsPanel({ onChange, onClose, fontSize, wordWrap, keybindin
</button>
</div>

<label class="settings-label">Changed words</label>
<div class="settings-row">
<div class="segmented segmented-sm">
${WORD_HIGHLIGHT_OPTIONS.map(([value, label]) => html`
<button class=${'segmented-btn' + (wordHighlight === value ? ' active' : '')} onClick=${() => update({ word_highlight: value })}>${label}</button>
`)}
</div>
</div>

<div class="settings-divider"></div>

<button class="settings-keybind-toggle" onClick=${() => setShowKeybindings(v => !v)}>
Expand Down
9 changes: 8 additions & 1 deletion diffui/static/lib/useAppearance.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useEffect } from 'preact/hooks';

export function useAppearance({ themeCss, fontSize, wordWrap }) {
export const WORD_HIGHLIGHT_STYLES = ['background', 'underline', 'off'];

export function useAppearance({ themeCss, fontSize, wordWrap, wordHighlight }) {
useEffect(() => {
if (themeCss) {
let style = document.getElementById('theme-vars');
Expand All @@ -20,4 +22,9 @@ export function useAppearance({ themeCss, fontSize, wordWrap }) {
useEffect(() => {
document.documentElement.classList.toggle('word-wrap-enabled', wordWrap);
}, [wordWrap]);

useEffect(() => {
const root = document.documentElement.classList;
for (const style of WORD_HIGHLIGHT_STYLES) root.toggle(`word-hl-${style}`, style === wordHighlight);
}, [wordHighlight]);
}
11 changes: 9 additions & 2 deletions diffui/static/lib/useKeyboard.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useEffect, useMemo, useCallback } from 'preact/hooks';
import { mod, clampFont } from './utils.js';
import { kb } from './keys.js';
import { WORD_HIGHLIGHT_STYLES } from './useAppearance.js';

// Global keydown handler plus the command palette's command list and dispatcher.
export function useKeyboard({
keybindings, fontSize, wordWrap,
keybindings, fontSize, wordWrap, wordHighlight,
showCompletionRef, dialogOpenRef, visibleFilesRef, activeFileRef,
handleFileSelect, handleToggleReview, handleCopyPath, handleSortByRisk, handleExportSummary,
handleCopyGitLabLink, handleNextUnreviewed, navigateComment, scrollToHunk, handleToggleWhitespace,
Expand Down Expand Up @@ -126,6 +127,7 @@ export function useKeyboard({
{ id: 'collapse-all-hunks', label: 'Collapse all hunks', category: 'Actions' },
{ id: 'toggle-whitespace', label: 'Toggle ignore whitespace', keys: 'w', category: 'Actions' },
{ id: 'toggle-word-wrap', label: 'Toggle word wrap', category: 'Settings' },
{ id: 'cycle-word-highlight', label: 'Cycle changed-word highlight', category: 'Settings' },
{ id: 'font-size-up', label: 'Increase font size', category: 'Settings' },
{ id: 'font-size-down', label: 'Decrease font size', category: 'Settings' },
{ id: 'export-summary', label: 'Copy review summary', keys: kb(keybindings, 'export-summary'), category: 'Actions' },
Expand Down Expand Up @@ -162,6 +164,11 @@ export function useKeyboard({
case 'collapse-all-hunks': handleCollapseAll('collapse'); break;
case 'toggle-whitespace': handleToggleWhitespace(); break;
case 'toggle-word-wrap': handleSettingsChange({ word_wrap: !wordWrap }); break;
case 'cycle-word-highlight': {
const i = WORD_HIGHLIGHT_STYLES.indexOf(wordHighlight);
handleSettingsChange({ word_highlight: WORD_HIGHLIGHT_STYLES[(i + 1) % WORD_HIGHLIGHT_STYLES.length] });
break;
}
case 'font-size-up': handleSettingsChange({ font_size: clampFont(fontSize + 1) }); break;
case 'font-size-down': handleSettingsChange({ font_size: clampFont(fontSize - 1) }); break;
case 'go-to-line': setShowGoToLine(v => !v); break;
Expand All @@ -174,7 +181,7 @@ export function useKeyboard({
case 'prev-hunk': scrollToHunk('prev'); break;
case 'next-hunk': scrollToHunk('next'); break;
}
}, [handleToggleReview, handleFileSelect, handleCopyPath, handleCopyGitLabLink, handleExpandContext, handleCollapseAll, handleToggleWhitespace, handleExportSummary, handleSortByRisk, handleBulkResolve, handleSendToAgent, handleExplain, scrollToHunk, handleSettingsChange, wordWrap, fontSize]);
}, [handleToggleReview, handleFileSelect, handleCopyPath, handleCopyGitLabLink, handleExpandContext, handleCollapseAll, handleToggleWhitespace, handleExportSummary, handleSortByRisk, handleBulkResolve, handleSendToAgent, handleExplain, scrollToHunk, handleSettingsChange, wordWrap, wordHighlight, fontSize]);

return { paletteCommands, handleCommand };
}
17 changes: 17 additions & 0 deletions diffui/static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,23 @@ mark {
padding: 0 1px;
}

/* Changed words inside a paired remove/add line. No padding, so the marked
text keeps the same columns as the line on the other side. */
mark.word-hl {
padding: 0;
}

html.word-hl-underline mark.word-hl {
background: transparent;
border-radius: 0;
text-decoration: underline 2px currentColor;
text-underline-offset: 3px;
}

html.word-hl-off mark.word-hl {
background: transparent;
}

/* --- Empty state --- */

.empty-state {
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "diffui"
version = "0.11.3"
version = "0.12.0"
description = "UI for reviewing AI agent diffs"
requires-python = ">=3.10"
dependencies = [
Expand Down
20 changes: 16 additions & 4 deletions tests/test_highlight.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,30 @@ def test_empty_line(self):
pytest.param(
'<span style="color:red">hello</span>', [], "hello", '<span style="color:red">hello</span>', id="no-ranges"
),
pytest.param("hello world", [(0, 5)], "hello world", "<mark>hello</mark> world", id="plain-text"),
pytest.param(
"hello world", [(0, 5)], "hello world", '<mark class="word-hl">hello</mark> world', id="plain-text"
),
pytest.param(
'<span style="color:red">abc</span>',
[(0, 3)],
"abc",
'<span style="color:red"><mark>abc</mark></span>',
'<span style="color:red"><mark class="word-hl">abc</mark></span>',
id="inside-span",
),
pytest.param(
"&lt;div&gt;", [(0, 5)], "<div>", "<mark>&lt;div&gt;</mark>", id="entities-count-as-one-character"
"&lt;div&gt;",
[(0, 5)],
"<div>",
'<mark class="word-hl">&lt;div&gt;</mark>',
id="entities-count-as-one-character",
),
pytest.param(
"&lt;div&gt;",
[(0, 1)],
"<div>",
'<mark class="word-hl">&lt;</mark>div&gt;',
id="range-ends-inside-entities",
),
pytest.param("&lt;div&gt;", [(0, 1)], "<div>", "<mark>&lt;</mark>div&gt;", id="range-ends-inside-entities"),
],
)
def test_apply_word_highlights(code_html, ranges, plain, marked):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ def test_settings_switches_theme(self, _server_app, requested, expected):
("agent_cli", "codex"),
("font_size", 16),
("word_wrap", True),
("word_highlight", "underline"),
("word_highlight", "off"),
("keybindings", {"toggle-review": "R", "sort-risk": "x"}),
],
)
Expand Down
Loading