Repository navigation
feat: add markdown diff view and previous commit history tabs - #599
Conversation
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
✅ Deploy Preview for mdts-unhappychoice ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds markdown diff viewing: new backend routes (/api/diff, /api/diff-prev), Redux diff slice with async thunks, UI tabs and view modes for Changes
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
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. Comment |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
diffSlicedoesn'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
viewModechanging anddiffLoadingbecomingtrue.♻️ 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 ViewModedoesn'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~1doesn't exist, causinggit.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
⛔ Files ignored due to path filters (4)
packages/frontend/test/unit/__snapshots__/Layout.test.tsx.snapis excluded by!**/*.snappackages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/DiffView.test.tsx.snapis excluded by!**/*.snappackages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContent.test.tsx.snapis excluded by!**/*.snappackages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContentTabs.test.tsx.snapis excluded by!**/*.snap
📒 Files selected for processing (14)
packages/frontend/src/components/Content/MarkdownContent/DiffView.tsxpackages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsxpackages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsxpackages/frontend/src/components/Content/MarkdownContent/MarkdownContentView.tsxpackages/frontend/src/hooks/useViewMode.tspackages/frontend/src/store/slices/diffSlice.tspackages/frontend/src/store/store.tspackages/frontend/test/unit/components/Content/MarkdownContent/DiffView.test.tsxpackages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContent.test.tsxpackages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContentView.test.tsxpackages/frontend/test/utils.tssrc/server/routes/diff.tssrc/server/server.tstest/unit/server/routes/diff.test.ts
…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.
There was a problem hiding this comment.
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
Frontmattertab which is conditionally rendered based onhasFrontmatter, these tabs are always visible. This works well if theDiffViewcomponent 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
DiffViewdoesn't handle these gracefully, you might consider adding props likehasDiff/hasPrevDifffor 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
⛔ Files ignored due to path filters (3)
packages/frontend/test/unit/__snapshots__/Layout.test.tsx.snapis excluded by!**/*.snappackages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContent.test.tsx.snapis excluded by!**/*.snappackages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContentTabs.test.tsx.snapis excluded by!**/*.snap
📒 Files selected for processing (3)
packages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsxsrc/server/routes/diff.tstest/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
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.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/server/routes/diff.ts (1)
23-23:⚠️ Potential issue | 🟠 MajorUse
--beforefilePathin working-tree diff call.Line 23 passes
filePathdirectly togit 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
⛔ Files ignored due to path filters (3)
packages/frontend/test/unit/__snapshots__/Layout.test.tsx.snapis excluded by!**/*.snappackages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContent.test.tsx.snapis excluded by!**/*.snappackages/frontend/test/unit/components/Content/MarkdownContent/__snapshots__/MarkdownContentTabs.test.tsx.snapis excluded by!**/*.snap
📒 Files selected for processing (11)
packages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsxpackages/frontend/src/components/Content/MarkdownContent/MarkdownContentTabs.tsxpackages/frontend/src/store/slices/fileTreeSlice.tspackages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContent.test.tsxpackages/frontend/test/unit/components/Content/MarkdownContent/MarkdownContentTabs.test.tsxpackages/frontend/test/utils.tssrc/server/routes/diff.tssrc/server/routes/filetree.tstest/e2e/server.test.tstest/unit/server/routes/diff.test.tstest/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
- 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.
Summary
git diffgit diff HEAD~1 HEADChanges
Backend
/api/diff/:pathendpoint: returns git diff for current working tree changes/api/diff-prev/:pathendpoint: returns diff between HEAD~1 and HEAD for a fileserver.tsFrontend
DiffViewcomponent for rendering color-coded unified diff outputdiffSliceRedux slice for managing diff/diff-prev stateuseViewModehook to supportdiffanddiff-prevtab valuesMarkdownContentTabsto include Diff and History tabsMarkdownContentViewto render diff views when selectedMarkdownContentto fetch diff data on tab selectionTests
Closes #108
Summary by CodeRabbit
New Features
Backend / API
Tests