Skip to content

feat: add markdown diff view and previous commit history tabs - #599

Merged
unhappychoice merged 10 commits into
mainfrom
feat/diff-view
Mar 17, 2026
Merged

unhappychoice merged 10 commits into
mainfrom
feat/diff-view

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Mar 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Add Diff and History tabs to the markdown content view (alongside existing Preview, Frontmatter, Raw tabs)
  • Diff tab shows uncommitted working tree changes via git diff
  • History tab shows the previous commit's changes via git diff HEAD~1 HEAD
  • Color-coded diff rendering: green for additions, red for removals, blue for hunk headers

Changes

Backend

  • New /api/diff/:path endpoint: returns git diff for current working tree changes
  • New /api/diff-prev/:path endpoint: returns diff between HEAD~1 and HEAD for a file
  • Both endpoints are registered in server.ts

Frontend

  • New DiffView component for rendering color-coded unified diff output
  • New diffSlice Redux slice for managing diff/diff-prev state
  • Updated useViewMode hook to support diff and diff-prev tab values
  • Updated MarkdownContentTabs to include Diff and History tabs
  • Updated MarkdownContentView to render diff views when selected
  • Updated MarkdownContent to fetch diff data on tab selection

Tests

  • Backend: diff route tests (diff and diff-prev routers)
  • Frontend: DiffView component tests, updated existing tests for new diff state

Closes #108

Summary by CodeRabbit

  • New Features

    • Added "Diff" and "Previous" view modes with tabs to inspect uncommitted and prior-file changes.
    • Loading indicators and clear empty-state messages for diff views.
    • UI now shows git-related tabs only when a repository is detected.
  • Backend / API

    • New endpoints to fetch current and previous file diffs.
  • Tests

    • Added unit and e2e tests covering diff functionality and API routes.

Add Diff and History tabs alongside existing Preview, Frontmatter, and Raw tabs.
The Diff tab shows uncommitted changes (git diff) and the History tab shows
the previous commit's changes (git diff HEAD~1 HEAD).

Closes #108
@netlify

netlify Bot commented Mar 17, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for mdts-unhappychoice ready!

Name Link
🔨 Latest commit 1284a95
🔍 Latest deploy log https://app.netlify.com/projects/mdts-unhappychoice/deploys/69b9dad15620cd0008d93c34
😎 Deploy Preview https://deploy-preview-599--mdts-unhappychoice.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Mar 17, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds markdown diff viewing: new backend routes (/api/diff, /api/diff-prev), Redux diff slice with async thunks, UI tabs and view modes for diff and diff-prev, fileTree Git-repo flag, and corresponding tests and mocks.

Changes

Cohort / File(s) Summary
Backend routes & server
src/server/routes/diff.ts, src/server/server.ts
New diffRouter and diffPrevRouter exposing /api/diff and /api/diff-prev; compute current and previous diffs using simple-git with repo validation and error handling; routes mounted in server.
Redux: diff state & store
packages/frontend/src/store/slices/diffSlice.ts, packages/frontend/src/store/store.ts
New diffSlice with async thunks fetchDiff and fetchDiffPrev; added diff reducer to store and RootState.
File tree Git flag
packages/frontend/src/store/slices/fileTreeSlice.ts, src/server/routes/filetree.ts
Added isGitRepository field to fileTree state and API response; fetchFileTree now expects/returns isGitRepository.
Frontend components & hook
packages/frontend/src/hooks/useViewMode.ts, packages/frontend/src/components/Content/MarkdownContent/...
MarkdownContent.tsx, MarkdownContentTabs.tsx, MarkdownContentView.tsx
Extended ViewMode to include diff/diff-prev; components read isGitRepository and diff state, dispatch fetchDiff/fetchDiffPrev on view changes, added tabs and rendering cases with loading/empty states.
Tests & test utilities
test/unit/server/routes/diff.test.ts, test/unit/server/routes/filetree.test.ts, test/e2e/server.test.ts, packages/frontend/test/.../*, packages/frontend/test/utils.ts
Added unit tests for diff routes (success/error/edge cases); updated filetree tests and e2e expectations to include isGitRepository; updated frontend unit tests and mocks to include diff state and thunk mocks; test utilities updated to include diff and isGitRepository.

Sequence Diagram(s)

sequenceDiagram
    participant User as User
    participant UI as MarkdownContent Component
    participant Store as Redux Store
    participant API as Frontend API Client
    participant Server as Server
    participant Git as Git Repo

    User->>UI: Select "diff" or "diff-prev" tab
    UI->>Store: dispatch(fetchDiff(path)) or dispatch(fetchDiffPrev(path))
    Store->>API: HTTP GET /api/diff/:path or /api/diff-prev/:path
    API->>Server: Request diff for path
    Server->>Git: validate repo & run git commands
    Git-->>Server: diff output (text)
    Server-->>API: 200 OK (diff text)
    API->>Store: resolve thunk with diff payload
    Store->>UI: updated diff state (loading false, diff text)
    UI->>User: render diff or show empty/loading state
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hopped through code to fetch the change,
Sniffed the commits across the range.
Tabs now show what's new and old,
Diff tales in lines of green and bold.
Hooray — the editor's story's told!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately summarizes the main change: adding diff view and previous commit history tabs to the markdown content view.
Linked Issues check ✅ Passed The PR fully implements the requirements from issue #108: adds diff tabs, enables viewing uncommitted changes via git diff, and provides history view for previous commit changes.
Out of Scope Changes check ✅ Passed All changes are directly related to adding diff/history tab functionality. The fileTreeSlice changes (adding isGitRepository) and filetree route updates are necessary supporting changes for conditional tab rendering.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/diff-view
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Mar 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.17355% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 89.93%. Comparing base (f39ab00) to head (1284a95).
⚠️ Report is 11 commits behind head on main.

Files with missing lines Patch % Lines
...onents/Content/MarkdownContent/MarkdownContent.tsx 85.71% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #599      +/-   ##
==========================================
+ Coverage   89.14%   89.93%   +0.78%     
==========================================
  Files          66       68       +2     
  Lines        1327     1441     +114     
  Branches      294      314      +20     
==========================================
+ Hits         1183     1296     +113     
- Misses        144      145       +1     
Flag Coverage Δ
frontend 91.27% <98.57%> (+0.49%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (3)
packages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsx (1)

37-44: Stale diff data may flash when switching files or view modes.

When switching from one file's diff view to another, the previous diff content remains in Redux state until the new fetch completes. Since diffSlice doesn't expose a reset action, users may briefly see stale diff data before loading completes.

This is partially mitigated by loading spinners, but there's a race window between viewMode changing and diffLoading becoming true.

♻️ Consider adding a reset action to diffSlice

In diffSlice.ts:

 const diffSlice = createSlice({
   name: 'diff',
   initialState,
-  reducers: {},
+  reducers: {
+    resetDiff: (state) => {
+      state.diff = '';
+      state.diffPrev = '';
+    },
+  },
   extraReducers: (builder) => {

Then dispatch reset before fetch:

   useEffect(() => {
     if (viewMode === 'diff') {
+      dispatch(resetDiff());
       dispatch(fetchDiff(currentPath));
     }
     if (viewMode === 'diff-prev') {
+      dispatch(resetDiff());
       dispatch(fetchDiffPrev(currentPath));
     }
   }, [dispatch, currentPath, viewMode]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsx`
around lines 37 - 44, The stale diff issue happens because previous diff state
persists while new fetches are in flight; add a reset/clear action to diffSlice
(e.g., resetDiff or clearDiff) that clears diff data and loading flags, then
update the useEffect in MarkdownContent.tsx to dispatch that reset action
immediately when viewMode changes (before calling fetchDiff(currentPath) or
fetchDiffPrev(currentPath)) so the UI shows cleared/loading state instead of
stale diff; reference symbols: diffSlice (add resetDiff/clearDiff),
MarkdownContent useEffect, fetchDiff, and fetchDiffPrev.
packages/frontend/src/hooks/useViewMode.ts (1)

8-8: Unsafe type cast allows arbitrary strings as ViewMode.

The cast as ViewMode doesn't validate the URL parameter. If a user navigates with an invalid tab value (e.g., ?tab=invalid), it passes through as a ViewMode, potentially causing unexpected behavior in downstream components.

♻️ Suggested validation
+const VALID_VIEW_MODES: ViewMode[] = ['preview', 'frontmatter', 'raw', 'diff', 'diff-prev'];
+
 export const useViewMode = (): ViewMode => {
   const [searchParams] = useSearchParams();
-  return (searchParams.get('tab') as ViewMode) || 'preview';
+  const tab = searchParams.get('tab');
+  return (tab && VALID_VIEW_MODES.includes(tab as ViewMode)) ? (tab as ViewMode) : 'preview';
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/frontend/src/hooks/useViewMode.ts` at line 8, The code returns
(searchParams.get('tab') as ViewMode) which unsafely casts arbitrary strings to
ViewMode; change useViewMode to validate the value returned by
searchParams.get('tab') against the allowed ViewMode values (e.g., an array or
enum of permitted modes) and only return it if it matches, otherwise return the
default 'preview'. Update the logic inside useViewMode (the usage of
searchParams.get('tab')) to perform a runtime check (includes/has) against the
ViewMode set and avoid the cast so downstream consumers receive a guaranteed
valid ViewMode.
src/server/routes/diff.ts (1)

47-47: HEAD~1 will fail on repos with only one commit.

When a repository has only a single commit, HEAD~1 doesn't exist, causing git.diff(['HEAD~1', 'HEAD', '--', filePath]) to fail with a 500 error. This may confuse users.

Consider handling this edge case gracefully by returning an empty diff or a more descriptive error message. Alternatively, document this expected behavior.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/server/routes/diff.ts` at line 47, The current call git.diff(['HEAD~1',
'HEAD', '--', filePath]) will throw on repos with only one commit; before
calling git.diff, check for at least two commits (e.g., use git.log({ n: 2 }) or
git.revparse/--verify for HEAD~1) and if fewer than two commits return an empty
diff or a clear descriptive response instead of letting the exception bubble;
update the route handler around the git.diff call to perform this pre-check and
only call git.diff when HEAD~1 exists, otherwise set diff = '' (or a descriptive
message) and return that for filePath.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@packages/frontend/src/components/Content/MarkdownContent/MarkdownContentView.tsx`:
- Line 22: The component MarkdownContentView currently selects diff state but
ignores diffError and diffPrevError, so failed fetches look like empty diffs;
update the selector usage and render logic in MarkdownContentView to also read
diffError and diffPrevError from the diff slice and, where
diffLoading/diffPrevLoading and diff/diffPrev are handled (the block around the
useSelector and the render branches handling diff modes), display explicit error
UI/messages when diffError or diffPrevError is non-null (e.g., a clear error
banner or placeholder), ensuring you keep existing loading and empty-state
behavior intact while surfacing fetch failures to the user.

In `@packages/frontend/src/store/slices/diffSlice.ts`:
- Around line 24-27: The code constructs diff URLs by directly interpolating the
path into `/api/diff/${path}`, which breaks for filenames with reserved URL
characters; update both occurrences (the async loader around lines showing the
fetchData call and the similar block at 33-36) to encode the path with
encodeURIComponent(path) before building the URL so
fetchData<string>(`/api/diff/${encodedPath}`, 'text') is used, preserving the
existing null-checks and returning '' when path is null or the fetch returns
falsy.
- Around line 54-57: The fetchDiff.rejected case currently sets
state.diffLoading and state.diffError but leaves the previous diff payload in
state.diff; update the fetchDiff.rejected reducer to also clear the stale
payload (e.g., set state.diff = '' or null) so a failed fetch doesn't show an
outdated diff, and make the same change in the other rejected handler referenced
around lines 66-69 so both failure paths clear state.diff alongside
state.diffLoading and state.diffError.

In `@src/server/routes/diff.ts`:
- Around line 50-51: The catch block in the diff route currently declares
`error` but doesn't use it, causing lint failures; update the catch in the
handler (the catch surrounding the "Failed to get previous diff" response in
src/server/routes/diff.ts / the diffRouter route) to either log the error (e.g.,
use console.error or the app logger to record the caught `error`) or rename the
parameter to `_error` if you intentionally want to ignore it; ensure the chosen
approach removes the unused-variable lint warning and preserves the existing
res.status(500).json response.
- Around line 26-27: The catch block in the diff route handler currently
declares an unused variable named error which triggers ESLint no-unused-vars;
update the catch clause to either rename the parameter to _error or log the
error before sending the response (e.g., use console.error or the existing
logger) and then keep res.status(500).json({ error: 'Failed to get diff' }); —
locate the catch around the diff route handler (the try/catch that ends with
res.status(500).json({ error: 'Failed to get diff' })) and apply one of these
fixes so the caught exception is either intentionally discarded (_error) or
consumed by logging.

In `@test/unit/server/routes/diff.test.ts`:
- Around line 34-35: The working-tree call to git.diff passes filePath directly
(git.diff(..., filePath)) which can misinterpret filenames starting with `-`;
update the route handler so the args include the `--` separator (e.g., pass
['--', filePath] or include '--' in the args array) to match the diff-prev call
pattern, and update the unit test expectation (mockDiff) to expect the separator
(e.g., ['--', 'test.md']) instead of just ['test.md'] so the test reflects the
safer invocation.

---

Nitpick comments:
In
`@packages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsx`:
- Around line 37-44: The stale diff issue happens because previous diff state
persists while new fetches are in flight; add a reset/clear action to diffSlice
(e.g., resetDiff or clearDiff) that clears diff data and loading flags, then
update the useEffect in MarkdownContent.tsx to dispatch that reset action
immediately when viewMode changes (before calling fetchDiff(currentPath) or
fetchDiffPrev(currentPath)) so the UI shows cleared/loading state instead of
stale diff; reference symbols: diffSlice (add resetDiff/clearDiff),
MarkdownContent useEffect, fetchDiff, and fetchDiffPrev.

In `@packages/frontend/src/hooks/useViewMode.ts`:
- Line 8: The code returns (searchParams.get('tab') as ViewMode) which unsafely
casts arbitrary strings to ViewMode; change useViewMode to validate the value
returned by searchParams.get('tab') against the allowed ViewMode values (e.g.,
an array or enum of permitted modes) and only return it if it matches, otherwise
return the default 'preview'. Update the logic inside useViewMode (the usage of
searchParams.get('tab')) to perform a runtime check (includes/has) against the
ViewMode set and avoid the cast so downstream consumers receive a guaranteed
valid ViewMode.

In `@src/server/routes/diff.ts`:
- Line 47: The current call git.diff(['HEAD~1', 'HEAD', '--', filePath]) will
throw on repos with only one commit; before calling git.diff, check for at least
two commits (e.g., use git.log({ n: 2 }) or git.revparse/--verify for HEAD~1)
and if fewer than two commits return an empty diff or a clear descriptive
response instead of letting the exception bubble; update the route handler
around the git.diff call to perform this pre-check and only call git.diff when
HEAD~1 exists, otherwise set diff = '' (or a descriptive message) and return
that for filePath.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f066149a-1fd5-44f0-a292-b940dc795ce4

📥 Commits

Reviewing files that changed from the base of the PR and between f39ab00 and 84e91d3.

⛔ Files ignored due to path filters (4)
  • packages/frontend/test/unit/__snapshots__/Layout.test.tsx.snap is excluded by !**/*.snap
  • packages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/DiffView.test.tsx.snap is excluded by !**/*.snap
  • packages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContent.test.tsx.snap is excluded by !**/*.snap
  • packages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContentTabs.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (14)
  • packages/frontend/src/components/Content/MarkdownContent/DiffView.tsx
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsx
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsx
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownContentView.tsx
  • packages/frontend/src/hooks/useViewMode.ts
  • packages/frontend/src/store/slices/diffSlice.ts
  • packages/frontend/src/store/store.ts
  • packages/frontend/test/unit/components/Content/MarkdownContent/DiffView.test.tsx
  • packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContent.test.tsx
  • packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContentView.test.tsx
  • packages/frontend/test/utils.ts
  • src/server/routes/diff.ts
  • src/server/server.ts
  • test/unit/server/routes/diff.test.ts

Comment thread src/server/routes/diff.ts Resolved
Comment thread src/server/routes/diff.ts Resolved
Comment thread test/unit/server/routes/diff.test.ts Resolved
…EAD~1

The previous implementation used a fixed HEAD~1..HEAD diff, which returned
empty results for files not changed in the most recent commit. Now uses
git log to find the last commit that modified the specific file and shows
that commit's diff. Also renamed History tab to Prev Diff for clarity.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsx (1)

37-38: Diff tabs unconditionally rendered - consider edge case handling.

The implementation is correct. Unlike the Frontmatter tab which is conditionally rendered based on hasFrontmatter, these tabs are always visible. This works well if the DiffView component gracefully handles edge cases:

  • "Diff" with no uncommitted changes → empty state
  • "Prev Diff" on a never-committed file → error/empty state

If the backend or DiffView doesn't handle these gracefully, you might consider adding props like hasDiff / hasPrevDiff for conditional rendering. However, always-visible tabs with proper empty states is also a valid UX pattern.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsx`
around lines 37 - 38, The Diff and Prev Diff tabs in MarkdownContentTabs (Tab
value="diff" and value="diff-prev") are always rendered; update
MarkdownContentTabs to either (A) accept/compute hasDiff and hasPrevDiff props
and only render <Tab value="diff" .../> and <Tab value="diff-prev" .../> when
those flags are true, or (B) leave the tabs visible but ensure the DiffView
component receives clear props (e.g., diffData / prevDiffData or a isEmpty
indicator) and implements graceful empty/error states for "no uncommitted
changes" and "never-committed file" cases; modify the parent component that
mounts DiffView to supply these flags/data and add conditional rendering or
empty-state handling accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/server/routes/diff.ts`:
- Around line 52-53: The git.diff call using log.latest.hash (variable hash)
fails for root commits because `${hash}~1` may not exist; wrap the
git.diff([`${hash}~1`, hash, '--', filePath]) call in error handling and when
the error indicates an unknown revision (root commit), fall back to retrieving
the initial commit change via git.show([hash, '--', filePath]) (or another
root-aware git invocation) so the route returns the initial commit's diff
instead of a 500; update the logic around the git.diff invocation in the diff
route to detect this case and use git.show for hash with no parent.

---

Nitpick comments:
In
`@packages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsx`:
- Around line 37-38: The Diff and Prev Diff tabs in MarkdownContentTabs (Tab
value="diff" and value="diff-prev") are always rendered; update
MarkdownContentTabs to either (A) accept/compute hasDiff and hasPrevDiff props
and only render <Tab value="diff" .../> and <Tab value="diff-prev" .../> when
those flags are true, or (B) leave the tabs visible but ensure the DiffView
component receives clear props (e.g., diffData / prevDiffData or a isEmpty
indicator) and implements graceful empty/error states for "no uncommitted
changes" and "never-committed file" cases; modify the parent component that
mounts DiffView to supply these flags/data and add conditional rendering or
empty-state handling accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 65477879-a613-4f46-873a-653e708053e2

📥 Commits

Reviewing files that changed from the base of the PR and between 80eb556 and 87ad951.

⛔ Files ignored due to path filters (3)
  • packages/frontend/test/unit/__snapshots__/Layout.test.tsx.snap is excluded by !**/*.snap
  • packages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContent.test.tsx.snap is excluded by !**/*.snap
  • packages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContentTabs.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsx
  • src/server/routes/diff.ts
  • test/unit/server/routes/diff.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/unit/server/routes/diff.test.ts

Comment thread src/server/routes/diff.ts Resolved
Replace custom DiffView component with MarkdownRenderer using diff code
blocks, matching the same rendering approach as the Raw tab.
Add isGitRepository flag to filetree API response and conditionally
render Diff and Last Commit tabs only when the mounted directory is
inside a git repository.
Fetch diff on file selection instead of on tab click, and conditionally
render the Diff tab only when the diff result is non-empty.
Fall back to diffing against the empty tree when the commit has no
parent (initial commit). Also revert the accidental change to
example_documents/features/frontmatter.md.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/server/routes/diff.ts (1)

23-23: ⚠️ Potential issue | 🟠 Major

Use -- before filePath in working-tree diff call.

Line 23 passes filePath directly to git diff. Filenames beginning with - can be parsed as options. Use the pathspec separator.

🔧 Proposed fix
-      const diff = await git.diff([filePath]);
+      const diff = await git.diff(['--', filePath]);

Downstream impact: update the expectation in test/unit/server/routes/diff.test.ts (Line 34) to match ['--', 'test.md'].

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/server/routes/diff.ts` at line 23, The git.diff call passes filePath
directly which can be interpreted as an option for filenames starting with '-',
so change the invocation to include the pathspec separator by calling
git.diff(['--', filePath]) (update the call site where git.diff is used in
src/server/routes/diff.ts) and also update the unit test expectation in
test/unit/server/routes/diff.test.ts to expect ['--', 'test.md'] instead of
['test.md'] so tests reflect the new argument order.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/server/routes/diff.ts`:
- Around line 54-60: The catch currently swallows all errors when calling
git.diff and always falls back to the empty-tree diff; change it to catch the
error into a variable (e) and only perform the empty-tree fallback when the
error clearly indicates a missing parent/root-commit revision (e.g., message
contains "bad revision", "unknown revision", "ambiguous argument", or similar
git "no parent" wording); for any other error (invalid filePath, permissions,
repo corruption) rethrow or propagate the error instead of falling back. Locate
the git.diff call and the catch block around it and implement the conditional
check on the caught error message before assigning diff using the emptyTree
constant.

---

Duplicate comments:
In `@src/server/routes/diff.ts`:
- Line 23: The git.diff call passes filePath directly which can be interpreted
as an option for filenames starting with '-', so change the invocation to
include the pathspec separator by calling git.diff(['--', filePath]) (update the
call site where git.diff is used in src/server/routes/diff.ts) and also update
the unit test expectation in test/unit/server/routes/diff.test.ts to expect
['--', 'test.md'] instead of ['test.md'] so tests reflect the new argument
order.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a5c09828-b16e-40e0-a004-a5a659e3e420

📥 Commits

Reviewing files that changed from the base of the PR and between 9b199fe and 16c4ca2.

⛔ Files ignored due to path filters (3)
  • packages/frontend/test/unit/__snapshots__/Layout.test.tsx.snap is excluded by !**/*.snap
  • packages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContent.test.tsx.snap is excluded by !**/*.snap
  • packages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContentTabs.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (11)
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsx
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsx
  • packages/frontend/src/store/slices/fileTreeSlice.ts
  • packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContent.test.tsx
  • packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContentTabs.test.tsx
  • packages/frontend/test/utils.ts
  • src/server/routes/diff.ts
  • src/server/routes/filetree.ts
  • test/e2e/server.test.ts
  • test/unit/server/routes/diff.test.ts
  • test/unit/server/routes/filetree.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsx
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsx
  • packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContent.test.tsx

Comment thread src/server/routes/diff.ts Resolved
- Show error Alert in diff views when fetch fails (#0)
- Encode file path segments in diff API URLs (#1)
- Clear stale diff data on fetch rejection (#2)
- Add -- separator to git diff for safe file path handling (#5)
- Only fallback to empty tree on root commit errors, re-throw others (#7)
- Add test for non-root-commit error propagation
Add thunk execution tests for diffSlice covering null path, URL
encoding, and null response cases. Add diff/diff-prev view mode tests
for MarkdownContentView covering content rendering, empty state,
loading, and error states.
@unhappychoice
unhappychoice merged commit 9f6bf10 into main Mar 17, 2026
9 checks passed
@unhappychoice
unhappychoice deleted the feat/diff-view branch March 17, 2026 23:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: add markdown diff view

1 participant