Skip to content

feat: ux improvements - #96

Merged
fum4 merged 9 commits into
masterfrom
fix/placeholder-flicker
Mar 24, 2026
Merged

fum4 merged 9 commits into
masterfrom
fix/placeholder-flicker

Conversation

@fum4

@fum4 fum4 commented Mar 24, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Move-to-existing: UI flow and server API to move uncommitted changes into an existing worktree; worktree selection/navigation from details.
    • Diff view: per-file “Discard”, folder-level discard, and “Discard all” batch revert controls; undo/discard actions available in file headers and sidebars.
  • Improvements

    • Better worktree name sanitization and in-modal error banners; reduced persistent error toasts across integrations.
    • ANSI-colored output rendering for hook logs.
  • Tests

    • Added/updated tests for discard/revert and worktree create/move flows.
  • Documentation

    • Added code-layering guidance and updated project-structure links.

fum4 added 2 commits March 23, 2026 23:19
- add per-file, per-folder, and per-section discard buttons in diff viewer
  (server endpoint uses git checkout with fallback for new/untracked files)
- add stage/unstage/discard buttons to folder headers in sidebar
  (batch API calls for all files in the folder)
- sanitize branch name when auto-deriving worktree name
  (swaps `/`, `_`, `.` with hyphens to prevent validation errors)
- suppress all creation error toasts from useApi interceptor
  (modal now handles errors inline with styled banner and red input border)
@fum4 fum4 self-assigned this Mar 24, 2026
@vercel

vercel Bot commented Mar 24, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
openkit Skipped Skipped Mar 24, 2026 10:31am

@coderabbitai

coderabbitai Bot commented Mar 24, 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 a shared async git library (staging, stash, revert, diff, status), moves git helpers out of integrations, extends WorktreeManager with moveChangesToExistingWorktree, adds server endpoints for move-to-existing and revert, and wires frontend UI for selecting worktrees and discarding changes.

Changes

Cohort / File(s) Summary
Worktree manager
apps/server/src/manager.ts
Added WorktreeManager.moveChangesToExistingWorktree(targetId) implementing resolve → stash root → apply to target → conflict/restore/drop handling and listener notification with structured success/error returns.
Server routes
apps/server/src/routes/worktrees.ts, apps/server/src/routes/github.ts
Added POST /api/worktrees/move-to-existing and POST /api/worktrees/:id/revert; replaced inline git execs with @openkit/shared/git helpers (stageFiles, unstageFiles, stageAll, unstageAll, validatePathsWithinCwd, revertFiles, etc.).
Shared git library
libs/shared/src/git.ts, libs/shared/src/worktree-types.ts
New async git primitives: exec wrapper, stage/unstage (per-path & all), validatePathsWithinCwd, revertFiles, stash APIs (hasUncommittedChanges, stashPush, stashApply, stashDrop), diff APIs (getChangedFiles, getFileContent), status/commit/push helpers, and exported GitStatusInfo.
Integrations cleanup
libs/integrations/src/github/*
Removed old git helper exports and git-diff module from integrations; callers updated to import git primitives and GitStatusInfo from @openkit/shared.
Frontend: detail / move UI
apps/web-app/src/App.tsx, apps/web-app/src/components/detail/DetailPanel.tsx, apps/web-app/src/components/detail/DetailHeader.tsx
DetailPanel now accepts worktrees + onSelectWorktree; move modal supports "New" vs "Existing" modes with searchable existing-worktree picker; selection callback invoked on success; removed Tooltip around root move/delete buttons.
Frontend: diff / discard UI
apps/web-app/src/components/detail/DiffFileSection.tsx, apps/web-app/src/components/detail/DiffFileSidebar.tsx, apps/web-app/src/components/detail/DiffViewerTab.tsx
Added per-file and bulk "Discard" (revert) controls, folder-level batch actions, new stage/unstage/revert callbacks wired to APIs, and gitOpKey prop to trigger refresh after git ops.
Frontend API & hooks
apps/web-app/src/hooks/api.ts, apps/web-app/src/hooks/useApi.ts
Added moveToExistingWorktree() and revertFiles() client methods; bound moveToExistingWorktree in useApi(); adjusted toast-suppression logic for worktree creation failure cases.
CreateWorktree modal & tests
apps/web-app/src/components/CreateWorktreeModal.tsx, apps/web-app/src/components/__test__/CreateWorktreeModal.test.tsx
Replaced deriveBranch with sanitizeWorktreeName, added ErrorBanner, renamed manual-edit flag, updated derivation/validation and tests to new placeholders and server-side error clearing behavior.
Diff tests & UI tests
apps/web-app/src/components/detail/__test__/*
Added tests for per-file discard, discard-all, folder-level batch stage/discard, and conditional rendering when revert callbacks are omitted.
Server tests & mocks
apps/server/src/__test__/*
Updated tests to import shared git modules and shared logger; adjusted some type import paths from integrations to shared.
Docs & architecture
AGENTS.md, CLAUDE.md, docs/*, README.md
Added "Code Layering" / project-structure docs requiring git/business logic in libs/shared and integrations in libs/integrations; fixed doc links.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Web Client
    participant Server as API Server
    participant Git as Git
    participant FS as Filesystem

    Client->>Server: POST /api/worktrees/move-to-existing\n{ worktreeId }
    activate Server
    Server->>Git: hasUncommittedChanges(root)
    Git-->>Server: boolean
    alt has uncommitted
        Server->>Git: stashPush(root, message)
        Git-->>Server: stashRef / null
        alt stashRef
            Server->>Git: stashApply(targetPath, stashRef)
            Git-->>Server: { applied: true/false, hasConflicts? }
            alt applied true and no conflicts
                Server->>Git: stashDrop(root, stashRef)
                Server->>Server: notifyListeners()
                Server-->>Client: { success: true }
            else applied true but hasConflicts
                Server->>Server: (do not drop stash)
                Server->>Server: notifyListeners()
                Server-->>Client: { success: true }
            else applied false (error)
                Server->>Git: stashApply(root, stashRef)  // best-effort restore
                Server-->>Client: { success: false, error }
            end
        else no stashRef
            Server-->>Client: { success: false, error }
        end
    else no uncommitted
        Server-->>Client: { success: false, error: "No uncommitted changes to move" }
    end
    deactivate Server
Loading
sequenceDiagram
    participant Client as Web Client
    participant Server as API Server
    participant Git as Git

    Client->>Server: POST /api/worktrees/{id}/revert\n{ paths, staged }
    activate Server
    Server->>Server: validatePathsWithinCwd(cwd, paths)
    alt validation fails
        Server-->>Client: 400 { success:false, error }
    else valid
        Server->>Git: revertFiles(cwd, paths, staged)
        Git-->>Server: [] | [errorStrings]
        alt errors returned
            Server-->>Client: 400 { success:false, error: joinedErrors }
        else success
            Server-->>Client: 200 { success:true }
        end
    end
    deactivate Server
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hopped and stashed in the night,

nudged stray patches into place just right,
a discard click, a tidy sweep,
worktrees calm while branches sleep,
tiny paws keep codebase bright.

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.52% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'feat: ux improvements' is too vague and generic. It uses a non-descriptive term 'ux improvements' that doesn't convey meaningful information about the changeset, which includes extensive backend refactoring (git operations migration to shared library), frontend UX changes (move to worktree, revert files), modal improvements, and documentation updates. Revise the title to be more specific about the primary change. Examples: 'feat: move git operations to shared library and add revert/move-to-existing worktree features' or 'refactor: consolidate git operations into shared library with enhanced worktree management'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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 fix/placeholder-flicker

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

@github-actions

github-actions Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude Review

🔴 Major

  1. stageFiles/unstageFiles and other git operations in libs/shared/src/git.ts still don't use resolveCommandPath/withAugmentedPathEnv — libs/shared/src/git.ts:68-89. The execFileAsync used by stageFiles, unstageFiles, stageAll, unstageAll, revertFiles, hasGitRemote, hasGitCommits, createInitialCommit, getGitStatus, commitAll, pushBranch, hasUncommittedChanges, stashPush, stashApply, and stashDrop is plain promisify(execFileCb) without PATH augmentation. Meanwhile, execCmd (used by diff operations in the same file) correctly uses resolveCommandPath and withAugmentedPathEnv. On systems where git is in a non-standard location (e.g. macOS with Homebrew), these operations will fail while diff operations succeed.

🟠 Medium

  1. shouldSuppressWorktreeCreationToast still suppresses ALL creation errors — apps/web-app/src/hooks/useApi.ts:87-91. The function unconditionally returns true for all failed creation methods. Network errors, 500s, and transport failures are blanket-suppressed. The modal's inline error display only handles errors from successful HTTP responses with error strings — network failures that throw before returning a response body will be silently swallowed by the wrapClientWithErrorToasts proxy.

  2. Removed reportPersistentErrorToast calls throughout without replacement — Multiple files (IntegrationsPanel.tsx, JiraDetailPanel.tsx, LinearDetailPanel.tsx, CustomTaskDetailPanel.tsx, DetailPanel.tsx) had specific, scoped error toasts removed. Many error handlers now silently do nothing on failure (e.g. handleStart, handleStop, handleRename, handleOpenProjectIn, handleRecoverLocalTask in DetailPanel.tsx; status/priority/type/comment updates in JiraDetailPanel.tsx and LinearDetailPanel.tsx; GitHub setup operations in IntegrationsPanel.tsx). Users get no feedback when these operations fail.

  3. collectFilePaths memo in FolderSection depends on unstable reference — apps/web-app/src/components/detail/DiffFileSidebar.tsx:388. useMemo(() => collectFilePaths(node), [node]) — node is rebuilt each render from buildFolderTree/compactTree, so the memo never actually caches. The function result is passed directly to click handlers so the perf impact is minor, but it's misleading.

🟡 Minor

  1. Removed Tooltip from "Move to worktree" and "Delete" buttons — apps/web-app/src/components/detail/DetailHeader.tsx:424-458. Both buttons had tooltips; these were removed. The buttons do have text labels so it's not critical, but per CLAUDE.md the shared Tooltip component should be used for interactive elements.

  2. ansi-to-html dependency added but not visible in package.json diff — apps/web-app/src/components/detail/HooksTab.tsx:24. The import from "ansi-to-html" is new but the diff doesn't include a package.json change. Verify it was added via pnpm add.

  3. selectedExistingWorktreeId not cleared on mode switch — apps/web-app/src/components/detail/DetailPanel.tsx. When switching from "existing" to "new" mode and back, a previously selected worktree ID persists. If the user filters and the selected worktree is no longer visible, they could submit a stale selection.

🟢 Resolved

  1. Path traversal vulnerability in revert endpoint — Fixed. The revert endpoint in worktrees.ts:718 calls validatePathsWithinCwd, and revertFiles in libs/shared/src/git.ts:112 also validates as defense-in-depth.

  2. Stash dropped after conflicting apply — Fixed. moveChangesToExistingWorktree at manager.ts:1641-1649 now only drops the stash when !applyResult.hasConflicts, preserving the user's clean copy on conflicts.

  3. stageFiles/unstageFiles pass unsanitized paths to git — Fixed. The route handlers in github.ts:400-403 and github.ts:426-429 now call validatePathsWithinCwd before calling the library functions.

  4. moveChangesToExistingWorktree uses raw execFile instead of library functions — Fixed. The method now uses library functions hasUncommittedChanges, stashPush, stashApply, stashDrop from @openkit/shared/git.

  5. Path traversal in revertFiles — unlink reachable without validation at library level — Fixed. revertFiles in libs/shared/src/git.ts:112-114 now validates paths internally as defense-in-depth.

  6. Stash not dropped after successful apply — Fixed. Stash is properly dropped after clean apply at manager.ts:1641-1649.

  7. Stash restore error logging — Fixed. Error recovery includes stashRef and proper error context at manager.ts:1617-1625.

  8. Missing operational logging in revert endpoint — Fixed. The revert route has start, success, and error logging in worktrees.ts:726-749.

  9. Revert endpoint in wrong file — Fixed. Revert endpoint is in worktrees.ts.

  10. Duplicated error display markup — Fixed. Extracted ErrorBanner component in CreateWorktreeModal.tsx:13-19.

  11. Dynamic import inside request handler — Fixed. fs/promises and path are imported statically in libs/shared/src/git.ts.

  12. No confirmation dialog for destructive revert operations — Fixed. Both DiffViewerTab.tsx and DiffFileSidebar.tsx now show ConfirmDialog before executing revert/discard operations (sidebar at line 213, content view at line 730).

  13. stashDrop uses SHA ref which may not resolve — Fixed. stashDrop in libs/shared/src/git.ts:354-365 now looks up the stash index from the SHA via git stash list --format=%H before calling git stash drop stash@{N}.

  14. Duplicated branch-to-name sanitization logic — Fixed. Extracted to sanitizeWorktreeName in CreateWorktreeModal.tsx:34-38 and reused in DetailPanel.tsx.

  15. Missing operational logging in moveChangesToExistingWorktree — Fixed. Method has start and completion logging at manager.ts:1555-1560 and manager.ts:1670-1676.

  16. existingWorktrees toggle uses filtered count — Fixed. The disabled check now uses allExistingWorktrees.length === 0 (unfiltered list) at DetailPanel.tsx:2258.

@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: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web-app/src/components/CreateWorktreeModal.tsx (1)

132-145: ⚠️ Potential issue | 🟠 Major

Toast these operational failures as well as rendering them inline.

Every non-happy path here now only calls setError(...). In this repo, create/pull failures should still go through a persistent toast so the message is not lost when the modal closes.

As per coding guidelines "Always surface user-facing errors through toast notifications (showPersistentErrorToast / reportPersistentErrorToast)" and "Do not introduce inline error text for operational failures when a toast can communicate the failure."

Also applies to: 164-177, 196-212

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

In `@apps/web-app/src/components/CreateWorktreeModal.tsx` around lines 132 - 145,
The failure branches that only call setError (e.g., the branch after checking
result.code === "WORKTREE_EXISTS" / requiresWorktreeRecoveryPrompt(result) and
the final else where errorMsg is set) must also surface persistent toasts;
update the branches that currently call setError(errorMsg) or
onClose()/onSetupNeeded() to additionally call the repo's persistent toast
helper (showPersistentErrorToast or reportPersistentErrorToast) with the same
error message before returning or setting inline state, and ensure the branch
that handles missing worktree id likewise calls the persistent toast; reference
setError, setExistingWorktree, requiresWorktreeRecoveryPrompt, onClose, and
onSetupNeeded when making these changes so all operational failures are both
shown as persistent toasts and still rendered inline where appropriate.
🧹 Nitpick comments (3)
apps/web-app/src/components/detail/DetailHeader.tsx (1)

424-433: Consider adding a Tooltip for consistency with other action buttons.

The "Move to worktree" button no longer has a Tooltip wrapper, while the adjacent "Delete worktree" button (line 435) still uses one. This creates an inconsistent hover experience for users. If the removal was intentional (e.g., to avoid tooltip flicker mentioned in the branch name), consider documenting that reasoning; otherwise, wrap this button with a Tooltip similar to the delete button.

💡 Suggested fix for consistency
               {isRoot ? (
+                <Tooltip text="Move uncommitted changes to a worktree">
                 <button
                   type="button"
                   onClick={onMoveToWorktree}
                   disabled={isLoading || !worktree.hasUncommitted}
                   aria-label="Move changes to worktree"
                   className={`group h-7 px-2.5 text-[11px] font-medium ${button.secondary} hover:text-accent rounded-md disabled:opacity-50 transition-colors duration-150 inline-flex items-center gap-1.5`}
                 >
                   <GitBranch className="w-3.5 h-3.5 text-[`#6b7280`] transition-colors group-hover:text-accent" />
                   Move to worktree
                 </button>
+                </Tooltip>
               ) : (
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/detail/DetailHeader.tsx` around lines 424 - 433,
The "Move to worktree" button (onMoveToWorktree, uses worktree.hasUncommitted
and GitBranch) should be wrapped with the same Tooltip component used by the
adjacent "Delete worktree" button to restore consistent hover behavior: wrap the
existing <button> markup with the Tooltip wrapper, pass the same tooltip text
and ensure the button remains the Tooltip trigger (preserve aria-label,
disabled, className and children), and keep the existing onClick handler; if the
removal was intentional, add a short comment near the onMoveToWorktree button
explaining why the Tooltip was omitted to document the decision.
apps/server/src/routes/github.ts (1)

492-590: Add operational logging for the revert operation.

Per coding guidelines, git operations must log their start and terminal outcome with actionable metadata. This endpoint performs destructive git operations but has no logging.

💡 Suggested logging additions
   app.post("/api/worktrees/:id/revert", async (c) => {
     try {
       const id = c.req.param("id");
       const resolved = manager.resolveWorktree(id);
       if (!resolved.success) {
         return c.json({ success: false, error: resolved.error }, toResolutionStatus(resolved.code));
       }
       const body = await c.req.json<{ paths?: string[]; staged?: boolean }>();
       const paths = body.paths;
       const staged = body.staged ?? false;
       if (!paths || !Array.isArray(paths) || paths.length === 0) {
         return c.json({ success: false, error: "paths array is required" }, 400);
       }
       const cwd = resolved.worktree.path;
+      log.info("Reverting files", {
+        domain: "GitHub",
+        worktreeId: resolved.worktreeId,
+        paths,
+        staged,
+      });
       if (staged) {
         // ... existing logic
       }
+      log.info("Files reverted successfully", {
+        domain: "GitHub",
+        worktreeId: resolved.worktreeId,
+        count: paths.length,
+      });
       return c.json({ success: true });
     } catch (error) {
+      log.error("Failed to revert files", {
+        domain: "GitHub",
+        error: error instanceof Error ? error.message : String(error),
+      });
       return c.json(
         {
           success: false,
           error: error instanceof Error ? error.message : "Failed to revert files",
         },
         400,
       );
     }
   });

As per coding guidelines: "Treat ops logging as mandatory for all operations; always log start and terminal outcome (success/failure) for git operations."

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

In `@apps/server/src/routes/github.ts` around lines 492 - 590, The revert endpoint
(app.post("/api/worktrees/:id/revert")) lacks operational logs; add a start log
before running any git commands (include id, resolved.worktree.path as cwd,
paths array and staged flag) and add terminal logs after completion: a success
log when returning { success: true } and an error log in each failure path
(batch catch blocks, per-file errors arrays, and the outer catch) including
actionable metadata (id, cwd, paths, staged, and the error messages). Use the
module's existing logger (e.g., app.log or processLogger) consistently for these
messages and ensure each log clearly marks operation start vs terminal outcome
and includes the unique symbols: id, cwd, paths, staged, and any captured error
variable (e.g., rmErr, unlinkErr, or error).
apps/web-app/src/components/detail/DiffViewerTab.tsx (1)

358-385: Use the shared confirmation dialog instead of window.confirm.

These discard actions now open native browser confirms, which bypass the app's dialog styling and interaction patterns. Reusing the shared confirmation modal keeps this flow consistent and easier to control/test.

As per coding guidelines "Use the shared Modal component for dialogs; avoid bespoke dialog shells unless there is a documented exception."

Also applies to: 428-460

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

In `@apps/web-app/src/components/detail/DiffViewerTab.tsx` around lines 358 - 385,
Replace the native window.confirm calls in handleRevertPaths and
handleRevertFile with the app's shared confirmation dialog API (e.g.,
openConfirmModal / showConfirmDialog — import the actual helper used across the
app) so the same styled/modal flow is used; call the modal with the same
confirmation message strings, await the modal result, and early-return when the
user cancels, then proceed to call revertFiles and showPersistentErrorToast as
before; also update the analogous handlers around lines 428-460 to use the same
shared modal.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server/src/manager.ts`:
- Around line 1578-1593: The code creates a stash (via the execFile "git stash
push" and records its ref in stashRef) but later uses "git stash apply" which
leaves the stash behind; update the move cleanup logic (the paths around the
stashRef usage and the code sections handling the apply/restore—referencing
stashRef, the execFile calls for "git stash push"/"git stash list", and the
later apply logic) to explicitly remove the stash when the move succeeds by
running "git stash drop <stashRef>" (or equivalent via execFile) for any
non-null stashRef, and ensure this drop is executed in both success branches
(the block around lines 1578–1593 and the similar block at 1605–1647) so no
hidden stash remains after a successful move.
- Around line 1560-1576: The current git root status check swallows errors
(catch block) leaving hasUncommitted false and returning "No uncommitted changes
to move"; change the catch in the block that calls execFile("git", ["status",
"--porcelain"], { cwd: gitRoot, ... }) so that on error you fail the operation
instead of continuing—either rethrow the caught error or return an explicit
failure object (e.g., { success: false, error: err.message }) from the
surrounding function; update the catch that logs via log.warn to return or throw
using the original err (referencing execFile, gitRoot, hasUncommitted, and
log.warn) so callers receive the real git failure.

In `@apps/server/src/routes/github.ts`:
- Around line 566-572: The unlink call using join(cwd, p) can delete files
outside the repository; fix by resolving and validating the target is inside the
intended worktree before unlinking: use path.resolve or fs.realpath on join(cwd,
p) and on cwd, then check e.g. path.relative(cwdResolved, targetResolved) does
not start with ".." and targetResolved.startsWith(cwdResolved) (and reject
absolute/out-of-tree paths or symlink escapes); only call unlink(join(cwd, p))
when the validation passes, otherwise push a safe error into errors; update the
block around the try/catch where unlink(join(cwd, p)) is used to perform this
validation using the existing cwd, p, errors variables.

In `@apps/server/src/routes/worktrees.ts`:
- Around line 427-444: Add operational logging around the move-to-existing
route: before calling manager.moveChangesToExistingWorktree log a start message
(e.g., "Worktree move-to-existing requested") including the incoming worktreeId;
after the call log the terminal outcome with success/failure and metadata
(worktreeId, result.success) and on catch log the error message and stack (or
error instanceof Error ? error.message : String(error)) with the same metadata.
Use the same logger used elsewhere in this file (e.g., processLogger) and add
logs in the POST handler surrounding the call to
manager.moveChangesToExistingWorktree so both start and terminal events are
recorded.

In `@apps/web-app/src/components/CreateWorktreeModal.tsx`:
- Around line 122-124: The code falls back to the raw branch string for
resolvedName which causes server-side validation failures (e.g.,
"feat/my-feature"); change the logic so that when name.trim() is empty you do
not pass resolvedBranch directly to api.createWorktree but instead derive a safe
worktree name: sanitize the branch string (e.g., replace slashes and other
invalid chars with hyphens, remove leading/trailing punctuation, or append a
short unique suffix) and assign that to resolvedName before calling
api.createWorktree(resolvedBranch, resolvedName); update the variables
referenced (branch, name, resolvedBranch, resolvedName, api.createWorktree)
accordingly.

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 333-339: The auto-derived move target name (moveToWorktreeName
derived from moveToWorktreeBranch and moveToWorktreeNameRaw) can contain invalid
characters (e.g. slashes) and causes new worktree creation to fail; update the
logic that computes moveToWorktreeName and the submit fallback that uses
resolvedBranch to sanitize the branch-derived name (replace or remove
filesystem-invalid characters such as "/", trim whitespace, collapse repeated
separators, and ensure non-empty fallback) before using it for new worktree
creation, and apply the same sanitation at the other occurrence mentioned; touch
the state initialization/derivation around moveToWorktreeBranch,
moveToWorktreeNameRaw, moveToWorktreeNameManuallyEdited, moveToWorktreeName and
the submit path that references resolvedBranch so both manual and auto names are
validated/sanitized consistently.

In `@apps/web-app/src/components/detail/DiffFileSidebar.tsx`:
- Around line 226-257: The action buttons are only revealed on hover via
"opacity-0 group-hover:opacity-100" (and some folder buttons are hidden until
hover), which prevents keyboard users from seeing/focusing them; update the
visibility classes so keyboard focus also reveals them: on the container span
replace or augment "group-hover:opacity-100" with "group-hover:opacity-100
group-focus-within:opacity-100" (or "group-focus:opacity-100") and on the
individual buttons add focus styles (e.g. include "focus:text-white
focus:bg-white/[0.08] focus:outline-none" or "focus-visible:..." equivalents) so
revertAction, action, Undo2 and ActionIcon buttons become visible and usable via
keyboard; for any folder buttons currently using "hidden" for hover-only,
replace with "hidden group-hover:block group-focus:block" (or similar
focus-visible variant) so they are not inaccessible to keyboard users.

---

Outside diff comments:
In `@apps/web-app/src/components/CreateWorktreeModal.tsx`:
- Around line 132-145: The failure branches that only call setError (e.g., the
branch after checking result.code === "WORKTREE_EXISTS" /
requiresWorktreeRecoveryPrompt(result) and the final else where errorMsg is set)
must also surface persistent toasts; update the branches that currently call
setError(errorMsg) or onClose()/onSetupNeeded() to additionally call the repo's
persistent toast helper (showPersistentErrorToast or reportPersistentErrorToast)
with the same error message before returning or setting inline state, and ensure
the branch that handles missing worktree id likewise calls the persistent toast;
reference setError, setExistingWorktree, requiresWorktreeRecoveryPrompt,
onClose, and onSetupNeeded when making these changes so all operational failures
are both shown as persistent toasts and still rendered inline where appropriate.

---

Nitpick comments:
In `@apps/server/src/routes/github.ts`:
- Around line 492-590: The revert endpoint
(app.post("/api/worktrees/:id/revert")) lacks operational logs; add a start log
before running any git commands (include id, resolved.worktree.path as cwd,
paths array and staged flag) and add terminal logs after completion: a success
log when returning { success: true } and an error log in each failure path
(batch catch blocks, per-file errors arrays, and the outer catch) including
actionable metadata (id, cwd, paths, staged, and the error messages). Use the
module's existing logger (e.g., app.log or processLogger) consistently for these
messages and ensure each log clearly marks operation start vs terminal outcome
and includes the unique symbols: id, cwd, paths, staged, and any captured error
variable (e.g., rmErr, unlinkErr, or error).

In `@apps/web-app/src/components/detail/DetailHeader.tsx`:
- Around line 424-433: The "Move to worktree" button (onMoveToWorktree, uses
worktree.hasUncommitted and GitBranch) should be wrapped with the same Tooltip
component used by the adjacent "Delete worktree" button to restore consistent
hover behavior: wrap the existing <button> markup with the Tooltip wrapper, pass
the same tooltip text and ensure the button remains the Tooltip trigger
(preserve aria-label, disabled, className and children), and keep the existing
onClick handler; if the removal was intentional, add a short comment near the
onMoveToWorktree button explaining why the Tooltip was omitted to document the
decision.

In `@apps/web-app/src/components/detail/DiffViewerTab.tsx`:
- Around line 358-385: Replace the native window.confirm calls in
handleRevertPaths and handleRevertFile with the app's shared confirmation dialog
API (e.g., openConfirmModal / showConfirmDialog — import the actual helper used
across the app) so the same styled/modal flow is used; call the modal with the
same confirmation message strings, await the modal result, and early-return when
the user cancels, then proceed to call revertFiles and showPersistentErrorToast
as before; also update the analogous handlers around lines 428-460 to use the
same shared modal.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 913137cd-0bbb-40b5-915c-12363d6e955f

📥 Commits

Reviewing files that changed from the base of the PR and between 9bd0d8c and 6554c38.

📒 Files selected for processing (15)
  • apps/server/src/manager.ts
  • apps/server/src/routes/github.ts
  • apps/server/src/routes/worktrees.ts
  • apps/web-app/src/App.tsx
  • apps/web-app/src/components/CreateWorktreeModal.tsx
  • apps/web-app/src/components/__test__/CreateWorktreeModal.test.tsx
  • apps/web-app/src/components/detail/DetailHeader.tsx
  • apps/web-app/src/components/detail/DetailPanel.tsx
  • apps/web-app/src/components/detail/DiffFileSection.tsx
  • apps/web-app/src/components/detail/DiffFileSidebar.tsx
  • apps/web-app/src/components/detail/DiffViewerTab.tsx
  • apps/web-app/src/components/detail/__test__/DiffFileSection.test.tsx
  • apps/web-app/src/components/detail/__test__/DiffFileSidebar.test.tsx
  • apps/web-app/src/hooks/api.ts
  • apps/web-app/src/hooks/useApi.ts

Comment thread apps/server/src/manager.ts Resolved
Comment thread apps/server/src/manager.ts Resolved
Comment thread apps/server/src/routes/github.ts Resolved
Comment thread apps/server/src/routes/worktrees.ts Resolved

@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: 2

♻️ Duplicate comments (1)
apps/web-app/src/components/CreateWorktreeModal.tsx (1)

131-133: ⚠️ Potential issue | 🟠 Major

Still sanitize the fallback worktree name before submit.

If the user clears the auto-filled worktree name, Line 132 falls back to resolvedBranch and sends values like feat/my-feature back to api.createWorktree. That still trips server-side worktree-name validation.

🐛 Proposed fix
-    const resolvedName = name.trim() || resolvedBranch;
+    const resolvedName = name.trim() || sanitizeWorktreeName(resolvedBranch);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/CreateWorktreeModal.tsx` around lines 131 - 133,
The fallback uses raw resolvedBranch when name is empty, causing invalid names
to be sent to api.createWorktree; ensure the fallback is sanitized the same way
as the explicit name by applying the same trimming/normalization to
resolvedBranch before assigning resolvedName (i.e., compute resolvedBranch =
branch.trim(), sanitize/normalize that value, then set resolvedName =
name.trim() || sanitizedResolvedBranch) so api.createWorktree always receives a
validated worktree name.
🧹 Nitpick comments (7)
libs/shared/src/git.ts (3)

70-88: Document or enforce path safety requirements.

The staging functions accept paths arrays without validation. While git add/restore have some built-in protections, documenting that callers must validate paths (or adding validation internally) would clarify the contract.

📝 Option 1: Document the requirement
-/** Stage specific files in the working tree. */
+/**
+ * Stage specific files in the working tree.
+ * `@param` paths - Relative paths within cwd. Caller must validate paths don't escape cwd.
+ */
 export async function stageFiles(cwd: string, paths: string[]): Promise<void> {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/shared/src/git.ts` around lines 70 - 88, The stage/unstage helpers
(stageFiles, unstageFiles, stageAll, unstageAll) accept caller-supplied paths
without any validation; either document that callers must provide safe,
repository-relative paths or add internal validation to reject unsafe inputs
(e.g., empty strings, paths with null bytes, absolute paths, or path traversal
like ../). Update the function signatures for stageFiles and unstageFiles to
validate the paths array at the start (reject or normalize invalid entries) and
throw a clear error, and add a JSDoc comment to each function describing the
expected path safety contract so callers know they must supply repo-relative,
sanitized paths.

229-304: Consider adding debug logging in catch blocks instead of silent ignores.

The function has several catch { // Ignore } blocks. While resilience is appropriate here (partial failures shouldn't break status), adding log.debug() calls would aid debugging without changing behavior.

As per coding guidelines: "every catch block... must do something meaningful (log via logger or surface via toast)".

📝 Example for one catch block
   } catch {
-    // Ignore
+    log.debug("Failed to get uncommitted status", { domain: "git", worktreePath });
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/shared/src/git.ts` around lines 229 - 304, The catch blocks that
silently ignore errors around the execFileAsync calls (git status, git rev-list
--left-right, git rev-list --count for origin/${baseBranch}..HEAD, git diff
--numstat, and git ls-files/wc) should log debug details instead of being empty;
update each catch to capture the error (e) and call the module's logger (e.g.,
log.debug or logger.debug) with a concise message including the operation
context (e.g., "git status failed", "rev-list upstream failed", "compare to base
failed", "diff numstat failed", "ls-files/wc failed") and the error object so
behavior is unchanged but failures are visible for debugging, and if no logger
exists in scope, wire in the existing logger used by this module or accept one
as a parameter.

106-162: Add path validation inside revertFiles for defense-in-depth.

The revertFiles function calls unlink(path.join(cwd, p)) without validating that p resolves within cwd. While callers should validate paths beforehand, this shared utility could be misused if called without validation. Adding internal validation would provide defense-in-depth.

🔒 Proposed fix to add internal validation
 export async function revertFiles(
   cwd: string,
   paths: string[],
   staged: boolean,
 ): Promise<string[]> {
+  const invalidPath = validatePathsWithinCwd(cwd, paths);
+  if (invalidPath) {
+    return [`${invalidPath}: path traversal not allowed`];
+  }
+
   if (staged) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/shared/src/git.ts` around lines 106 - 162, revertFiles must defensively
validate each input path so callers cannot escape cwd before running git
commands or unlink; inside revertFiles (before any execFileAsync or unlink
calls) resolve cwd and each path with path.resolve and ensure the resolved path
equals cwdResolved or startsWith cwdResolved + path.sep (reject absolute/../
escapes), treat invalid paths as failures by adding a descriptive entry to the
errors array and skip running execFileAsync/unlink for them; apply this
validation in both the staged and unstaged code paths (the batch and per-file
fallback loops that call execFileAsync, execFileAsync(... "rm", "-f"), and
unlink) so all operations reference only validated paths.
apps/server/src/routes/github.ts (1)

387-407: Consider adding path validation before staging files.

The paths array from the request body is passed directly to stageFiles without validation. While git add itself has some protections, explicitly validating that paths don't escape the worktree directory (using validatePathsWithinCwd from @openkit/shared/git) would provide defense-in-depth.

This applies similarly to the /unstage endpoint.

♻️ Proposed fix to add path validation
+import {
+  stageFiles,
+  unstageFiles,
+  stageAll,
+  unstageAll,
+  getChangedFiles,
+  getFileContent,
+  validatePathsWithinCwd,
+} from "@openkit/shared/git";

Then in the stage endpoint:

       const paths = body.paths;
       if (!paths || !Array.isArray(paths) || paths.length === 0) {
         return c.json({ success: false, error: "paths array is required" }, 400);
       }
+      const invalidPath = validatePathsWithinCwd(resolved.worktree.path, paths);
+      if (invalidPath) {
+        return c.json({ success: false, error: `Invalid path: ${invalidPath}` }, 400);
+      }
       await stageFiles(resolved.worktree.path, paths);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/github.ts` around lines 387 - 407, Validate incoming
paths before calling stageFiles: after parsing body.paths in the POST
/api/worktrees/:id/stage handler and after resolving the worktree via
manager.resolveWorktree, call validatePathsWithinCwd(paths,
resolved.worktree.path) (from `@openkit/shared/git`) and return a 400 JSON error
if validation fails; only then call stageFiles(resolved.worktree.path, paths).
Apply the same pattern to the corresponding /unstage endpoint to ensure paths
cannot escape the worktree.
apps/server/src/manager.ts (2)

1542-1666: Missing operational logging for this git operation.

Per coding guidelines, git operations should log start and terminal outcome. This method lacks log.info at entry and log.success/log.error at completion, making production diagnosis harder compared to other operations like removeWorktree which logs phases extensively.

💡 Suggested logging additions
   async moveChangesToExistingWorktree(targetId: string): Promise<{
     success: boolean;
     error?: string;
   }> {
     const gitRoot = this.getGitRoot();
+    log.info("Moving uncommitted changes to existing worktree", {
+      domain: "worktree",
+      action: "worktree.moveToExisting.start",
+      targetId,
+    });

     const resolved = this.resolveWorktree(targetId);
     if (!resolved.success) {
+      log.warn("Failed to resolve target worktree for move", {
+        domain: "worktree",
+        targetId,
+        error: resolved.error,
+      });
       return { success: false, error: resolved.error };
     }
     // ... rest of method ...

     // At the end, before return { success: true }:
+    log.success("Successfully moved changes to existing worktree", {
+      domain: "worktree",
+      action: "worktree.moveToExisting.complete",
+      targetId: resolved.worktreeId,
+    });
     return { success: true };
   }

As per coding guidelines: "Treat ops logging as mandatory for all operations; always log start and terminal outcome (success/failure) for git operations".

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

In `@apps/server/src/manager.ts` around lines 1542 - 1666, The
moveChangesToExistingWorktree function lacks operational logs: add a log.info at
the start of moveChangesToExistingWorktree (include worktreeId/targetId and
gitRoot) and ensure you emit a terminal log.success on successful completion and
log.error on any early-return failure paths (including stash failures, apply
failures, restore failures, and "No changes were stashed"), attaching contextual
fields like resolved.worktreeId/targetId, stashRef, and the error message; keep
existing intermediate logs but augment exit points (both success and all error
returns) to follow the same op-log structure used in removeWorktree.

1614-1620: Conflict detection relies on fragile string matching.

The check errMsg.includes("CONFLICT") || errMsg.includes("conflict") may not catch all conflict scenarios (e.g., different git versions, localized messages, or other apply failures that should still be treated as partial success). Consider checking the exit code or inspecting the working directory state instead.

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

In `@apps/server/src/manager.ts` around lines 1614 - 1620, The current conflict
detection uses fragile string matching on errMsg; instead detect
partial-success/conflict by checking structured error properties (e.g.,
err.exitCode, err.code, or err.signal) or by inspecting the worktree state after
the apply (e.g., run a git status --porcelain or a helper like
isWorkingTreeDirty) to determine if files were partially applied; update the
branch handling where err/errMsg is used (around the stash apply handling that
logs "Stash applied with conflicts in target worktree" using resolved.worktreeId
and stashRef) to use these reliable checks and only log/info for true
partial-apply/conflict cases.
apps/web-app/src/components/detail/DetailPanel.tsx (1)

2371-2385: Consider adding keyboard navigation for worktree picker.

The worktree list items are buttons which is good for click accessibility, but the list lacks keyboard navigation (arrow keys to move selection, enter to confirm). For a better accessible experience, consider adding role="listbox" to the container and role="option" with aria-selected to items.

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

In `@apps/web-app/src/components/detail/DetailPanel.tsx` around lines 2371 - 2385,
The worktree picker needs keyboard navigation and ARIA roles: wrap the
existingWorktrees map output in a container element with role="listbox" and add
onKeyDown handler to that container to handle ArrowUp/ArrowDown to move
selection and Enter to confirm; update each item (the button rendered in the
existingWorktrees.map) to include role="option" and
aria-selected={selectedExistingWorktreeId === wt.id} and ensure each option can
receive focus (buttons already do). Implement the onKeyDown logic to compute the
next/previous index from existingWorktrees, call setSelectedExistingWorktreeId
with the new wt.id on arrow navigation, and on Enter call the same confirm
action as the onClick; reference the mapped component rendering
(existingWorktrees.map), the state setter setSelectedExistingWorktreeId, and
selectedExistingWorktreeId when adding these changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/web-app/src/components/CreateWorktreeModal.tsx`:
- Around line 1-2: Add a top-of-file JSDoc comment (1–3 sentences) explaining
the purpose of this module (the CreateWorktreeModal component that renders the
modal UI and logic for creating worktrees) to the very top of
CreateWorktreeModal.tsx above all imports; update the comment to reflect the
file’s responsibility and keep it succinct per the project's coding guidelines.
- Around line 11-18: The ErrorBanner change made createWorktree / createFromJira
/ createFromLinear failures modal-local — restore persistent toast and logging
for those error paths: when any of the submission handlers catch an error, call
showPersistentErrorToast (or reportPersistentErrorToast) with a user-friendly
message and also call logger.error/report with the operation metadata and the
error; if you still render ErrorBanner for inline feedback, add role="alert" to
the banner element (ErrorBanner) so assistive tech announces it. Ensure the
logger and toast calls are invoked in the same catch/failed branch where
createWorktree, createFromJira, and createFromLinear handle errors.

---

Duplicate comments:
In `@apps/web-app/src/components/CreateWorktreeModal.tsx`:
- Around line 131-133: The fallback uses raw resolvedBranch when name is empty,
causing invalid names to be sent to api.createWorktree; ensure the fallback is
sanitized the same way as the explicit name by applying the same
trimming/normalization to resolvedBranch before assigning resolvedName (i.e.,
compute resolvedBranch = branch.trim(), sanitize/normalize that value, then set
resolvedName = name.trim() || sanitizedResolvedBranch) so api.createWorktree
always receives a validated worktree name.

---

Nitpick comments:
In `@apps/server/src/manager.ts`:
- Around line 1542-1666: The moveChangesToExistingWorktree function lacks
operational logs: add a log.info at the start of moveChangesToExistingWorktree
(include worktreeId/targetId and gitRoot) and ensure you emit a terminal
log.success on successful completion and log.error on any early-return failure
paths (including stash failures, apply failures, restore failures, and "No
changes were stashed"), attaching contextual fields like
resolved.worktreeId/targetId, stashRef, and the error message; keep existing
intermediate logs but augment exit points (both success and all error returns)
to follow the same op-log structure used in removeWorktree.
- Around line 1614-1620: The current conflict detection uses fragile string
matching on errMsg; instead detect partial-success/conflict by checking
structured error properties (e.g., err.exitCode, err.code, or err.signal) or by
inspecting the worktree state after the apply (e.g., run a git status
--porcelain or a helper like isWorkingTreeDirty) to determine if files were
partially applied; update the branch handling where err/errMsg is used (around
the stash apply handling that logs "Stash applied with conflicts in target
worktree" using resolved.worktreeId and stashRef) to use these reliable checks
and only log/info for true partial-apply/conflict cases.

In `@apps/server/src/routes/github.ts`:
- Around line 387-407: Validate incoming paths before calling stageFiles: after
parsing body.paths in the POST /api/worktrees/:id/stage handler and after
resolving the worktree via manager.resolveWorktree, call
validatePathsWithinCwd(paths, resolved.worktree.path) (from `@openkit/shared/git`)
and return a 400 JSON error if validation fails; only then call
stageFiles(resolved.worktree.path, paths). Apply the same pattern to the
corresponding /unstage endpoint to ensure paths cannot escape the worktree.

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 2371-2385: The worktree picker needs keyboard navigation and ARIA
roles: wrap the existingWorktrees map output in a container element with
role="listbox" and add onKeyDown handler to that container to handle
ArrowUp/ArrowDown to move selection and Enter to confirm; update each item (the
button rendered in the existingWorktrees.map) to include role="option" and
aria-selected={selectedExistingWorktreeId === wt.id} and ensure each option can
receive focus (buttons already do). Implement the onKeyDown logic to compute the
next/previous index from existingWorktrees, call setSelectedExistingWorktreeId
with the new wt.id on arrow navigation, and on Enter call the same confirm
action as the onClick; reference the mapped component rendering
(existingWorktrees.map), the state setter setSelectedExistingWorktreeId, and
selectedExistingWorktreeId when adding these changes.

In `@libs/shared/src/git.ts`:
- Around line 70-88: The stage/unstage helpers (stageFiles, unstageFiles,
stageAll, unstageAll) accept caller-supplied paths without any validation;
either document that callers must provide safe, repository-relative paths or add
internal validation to reject unsafe inputs (e.g., empty strings, paths with
null bytes, absolute paths, or path traversal like ../). Update the function
signatures for stageFiles and unstageFiles to validate the paths array at the
start (reject or normalize invalid entries) and throw a clear error, and add a
JSDoc comment to each function describing the expected path safety contract so
callers know they must supply repo-relative, sanitized paths.
- Around line 229-304: The catch blocks that silently ignore errors around the
execFileAsync calls (git status, git rev-list --left-right, git rev-list --count
for origin/${baseBranch}..HEAD, git diff --numstat, and git ls-files/wc) should
log debug details instead of being empty; update each catch to capture the error
(e) and call the module's logger (e.g., log.debug or logger.debug) with a
concise message including the operation context (e.g., "git status failed",
"rev-list upstream failed", "compare to base failed", "diff numstat failed",
"ls-files/wc failed") and the error object so behavior is unchanged but failures
are visible for debugging, and if no logger exists in scope, wire in the
existing logger used by this module or accept one as a parameter.
- Around line 106-162: revertFiles must defensively validate each input path so
callers cannot escape cwd before running git commands or unlink; inside
revertFiles (before any execFileAsync or unlink calls) resolve cwd and each path
with path.resolve and ensure the resolved path equals cwdResolved or startsWith
cwdResolved + path.sep (reject absolute/../ escapes), treat invalid paths as
failures by adding a descriptive entry to the errors array and skip running
execFileAsync/unlink for them; apply this validation in both the staged and
unstaged code paths (the batch and per-file fallback loops that call
execFileAsync, execFileAsync(... "rm", "-f"), and unlink) so all operations
reference only validated paths.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 32644829-c13b-4010-afe0-67ec9167a442

📥 Commits

Reviewing files that changed from the base of the PR and between 6554c38 and c79a2bb.

📒 Files selected for processing (22)
  • AGENTS.md
  • CLAUDE.md
  • README.md
  • apps/server/src/__test__/auto-cleanup.test.ts
  • apps/server/src/__test__/git-diff.test.ts
  • apps/server/src/__test__/git-status.test.ts
  • apps/server/src/__test__/github-manager-pr-callback.test.ts
  • apps/server/src/manager.ts
  • apps/server/src/routes/github.ts
  • apps/server/src/routes/worktrees.ts
  • apps/web-app/src/components/CreateWorktreeModal.tsx
  • apps/web-app/src/components/detail/DetailPanel.tsx
  • apps/web-app/src/components/detail/DiffViewerTab.tsx
  • docs/ARCHITECTURE.md
  • docs/DEVELOPMENT.md
  • docs/PROJECT-STRUCTURE.md
  • libs/integrations/src/github/gh-client.ts
  • libs/integrations/src/github/git-diff.ts
  • libs/integrations/src/github/github-manager.ts
  • libs/integrations/src/github/types.ts
  • libs/shared/src/git.ts
  • libs/shared/src/worktree-types.ts
💤 Files with no reviewable changes (2)
  • libs/integrations/src/github/types.ts
  • libs/integrations/src/github/git-diff.ts
✅ Files skipped from review due to trivial changes (9)
  • apps/server/src/test/auto-cleanup.test.ts
  • README.md
  • docs/DEVELOPMENT.md
  • docs/ARCHITECTURE.md
  • apps/server/src/test/git-diff.test.ts
  • docs/PROJECT-STRUCTURE.md
  • CLAUDE.md
  • AGENTS.md
  • libs/integrations/src/github/github-manager.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/server/src/routes/worktrees.ts
  • apps/web-app/src/components/detail/DiffViewerTab.tsx

Comment on lines +11 to +18
function ErrorBanner({ message }: { message: string }) {
return (
<div className="flex items-start gap-2 rounded-md bg-red-900/20 px-3 py-2">
<AlertTriangle className="w-3.5 h-3.5 text-red-400 flex-shrink-0 mt-px" />
<p className="text-[11px] text-red-300">{message}</p>
</div>
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep toast + logger handling for create/pull failures.

The new ErrorBanner paths make createWorktree, createFromJira, and createFromLinear failures modal-local. Please keep a persistent toast and a logger call with the operation metadata when these submissions fail; if the banner stays, give it role="alert" so the fallback UI is announced too. As per coding guidelines "Always surface user-facing errors through toast notifications (showPersistentErrorToast / reportPersistentErrorToast)", "Errors that surface as toasts must also be logged through the logger; toasts are for users, logs are for debugging - both are required", and "Do not introduce inline error text for operational failures when a toast can communicate the failure".

Also applies to: 312-312, 351-351, 390-390

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

In `@apps/web-app/src/components/CreateWorktreeModal.tsx` around lines 11 - 18,
The ErrorBanner change made createWorktree / createFromJira / createFromLinear
failures modal-local — restore persistent toast and logging for those error
paths: when any of the submission handlers catch an error, call
showPersistentErrorToast (or reportPersistentErrorToast) with a user-friendly
message and also call logger.error/report with the operation metadata and the
error; if you still render ErrorBanner for inline feedback, add role="alert" to
the banner element (ErrorBanner) so assistive tech announces it. Ensure the
logger and toast calls are invoked in the same catch/failed branch where
createWorktree, createFromJira, and createFromLinear handle errors.

@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: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/web-app/src/components/detail/HooksTab.tsx`:
- Around line 43-45: stripAnsiBg currently only removes standalone 40-49 /
100-107 SGR codes; update it to remove any SGR escape that sets a background
even when combined or extended (e.g. \x1b[1;41m, \x1b[48;5;196m,
\x1b[48;2;R;G;Bm). Modify the function stripAnsiBg to match /\x1b\[([0-9;]*)m/g
and in the replace callback parse the captured params (split on ';') and drop
the entire escape if any param sequence matches background patterns (4[0-9],
10[0-7], the two-token sequence starting with 48;5;NNN, or the four-token
sequence starting with 48;2;R;G;B); leave other SGR sequences untouched. This
keeps other styling but reliably strips combined and extended ANSI background
sequences; update tests or add cases for "\x1b[1;41m", "\x1b[48;5;196m", and
"\x1b[48;2;255;0;0m" to verify behavior.
- Line 19: Add a top-of-file JSDoc comment (1–3 sentences) describing this
file’s responsibility—explain that HooksTab renders hook details and now
includes ANSI-to-HTML rendering for hook output (references: HooksTab component
and the AnsiToHtml import). Place the JSDoc at the very top of the file, update
the description to reflect the new ANSI/HTML rendering path, and ensure it
follows the project JSDoc style guidelines.
- Around line 36-41: Replace the hard-coded hex passed to the AnsiToHtml
constructor in HooksTab.tsx by importing a shared token from the theme; export a
plain-hex token (e.g., ansiFallbackColor) from apps/web-app/src/theme.ts and
import it into HooksTab.tsx, then use that token as the fg value when
constructing new AnsiToHtml (the ansiConverter instance), ensuring you pass the
raw hex the converter expects rather than an ad-hoc literal.
- Around line 1172-1176: Add a new test file HooksTab.test.tsx that mounts the
HooksTab component and asserts ANSI-to-HTML rendering and escaping behavior:
render a sample hook result (the prop/fixture containing result.output used in
the component) containing mixed ANSI color codes and literal HTML characters,
then verify that the DOM produced by the component (the nodes that use
dangerouslySetInnerHTML with ansiToHtml(result.output)) contains the expected
ANSI-converted spans/classes for foreground color, does not contain
background-color inline styles (ensuring background stripping), and that raw
HTML characters (<, >, &, ", ') are escaped (not interpreted as tags) because
ansiToHtml is configured with escapeXML: true; use the same helpers/test harness
used by sibling tests (e.g., render from `@testing-library/react`) and reference
HooksTab and ansiToHtml to locate the rendering path to test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9386ad84-edb3-4452-8ed7-8551a2dab516

📥 Commits

Reviewing files that changed from the base of the PR and between c79a2bb and 5066e89.

📒 Files selected for processing (1)
  • apps/web-app/src/components/detail/HooksTab.tsx

Comment on lines +43 to +45
/** Strip ANSI background color codes that are unreadable on the dark UI. */
function stripAnsiBg(text: string): string {
return text.replace(/\x1b\[(4[0-9]|10[0-7])m/g, "");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Background stripping misses common ANSI sequences.

This only removes standalone 40-49 / 100-107 SGR escapes. Combined or extended backgrounds like \x1b[1;41m, \x1b[48;5;196m, and \x1b[48;2;…m will still render, so the unreadable-background fix won’t hold for a lot of modern CLI output.

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

In `@apps/web-app/src/components/detail/HooksTab.tsx` around lines 43 - 45,
stripAnsiBg currently only removes standalone 40-49 / 100-107 SGR codes; update
it to remove any SGR escape that sets a background even when combined or
extended (e.g. \x1b[1;41m, \x1b[48;5;196m, \x1b[48;2;R;G;Bm). Modify the
function stripAnsiBg to match /\x1b\[([0-9;]*)m/g and in the replace callback
parse the captured params (split on ';') and drop the entire escape if any param
sequence matches background patterns (4[0-9], 10[0-7], the two-token sequence
starting with 48;5;NNN, or the four-token sequence starting with 48;2;R;G;B);
leave other SGR sequences untouched. This keeps other styling but reliably
strips combined and extended ANSI background sequences; update tests or add
cases for "\x1b[1;41m", "\x1b[48;5;196m", and "\x1b[48;2;255;0;0m" to verify
behavior.

Comment on lines +1172 to +1176
dangerouslySetInnerHTML={{
// Safe: output is from local process execution (hooks/scripts), not user-supplied.
// AnsiToHtml has escapeXML enabled, which escapes <, >, &, ", '.
__html: ansiToHtml(result.output),
}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Candidate HooksTab tests:"
fd -t f 'HooksTab\.(test|spec)\.(ts|tsx|js|jsx)$' .

echo
echo "ANSI/HTML rendering assertions in test files:"
rg -n -C2 'HooksTab|ansi-to-html|dangerouslySetInnerHTML|escapeXML|&lt;script|\\x1b\[' \
  -g '*.test.ts' -g '*.test.tsx' -g '*.test.js' -g '*.test.jsx' \
  -g '*.spec.ts' -g '*.spec.tsx' -g '*.spec.js' -g '*.spec.jsx' .

Repository: fum4/openkit

Length of output: 681


🏁 Script executed:

# First, locate and examine the HooksTab component
fd -t f 'HooksTab\.tsx$' . | head -5

Repository: fum4/openkit

Length of output: 105


🏁 Script executed:

# Check file size to understand scope
wc -l apps/web-app/src/components/detail/HooksTab.tsx

Repository: fum4/openkit

Length of output: 108


🏁 Script executed:

# Verify the exact lines mentioned in the review (1172-1176)
sed -n '1170,1180p' apps/web-app/src/components/detail/HooksTab.tsx

Repository: fum4/openkit

Length of output: 600


🏁 Script executed:

# Search for any test files in the detail components directory
fd -t f '\.(test|spec)\.(ts|tsx|js|jsx)$' apps/web-app/src/components/detail/

Repository: fum4/openkit

Length of output: 483


🏁 Script executed:

# Check if this is new code by looking at git history for this file
git log --oneline -n 10 apps/web-app/src/components/detail/HooksTab.tsx

Repository: fum4/openkit

Length of output: 86


🏁 Script executed:

# Search for ansiToHtml usage and tests elsewhere in the codebase
rg -n 'ansiToHtml' --type ts --type tsx . | head -20

Repository: fum4/openkit

Length of output: 83


🏁 Script executed:

# Check if there are any tests that use ansiToHtml or test HTML escaping
rg -n 'ansiToHtml|escapeXML' --type ts --type tsx . -g '*.test.*' -g '*.spec.*'

Repository: fum4/openkit

Length of output: 83


🏁 Script executed:

# Search for ansiToHtml usage
rg -n 'ansiToHtml' .

Repository: fum4/openkit

Length of output: 375


🏁 Script executed:

# Search for test files that might test HTML escaping or rendering
rg -n 'escapeXML|dangerouslySetInnerHTML' . -g '*.test.*'

Repository: fum4/openkit

Length of output: 38


🏁 Script executed:

# Check if ansiToHtml is installed as a dependency
fd -t f 'package\.json$' . | xargs rg -l 'ansi-to-html'

Repository: fum4/openkit

Length of output: 83


🏁 Script executed:

# Look at DetailPanel.test to understand HooksTab mocking
sed -n '1,50p' apps/web-app/src/components/detail/DetailPanel.test.tsx

Repository: fum4/openkit

Length of output: 1537


🏁 Script executed:

# Look at the ansiToHtml function implementation
sed -n '49,100p' apps/web-app/src/components/detail/HooksTab.tsx

Repository: fum4/openkit

Length of output: 1469


🏁 Script executed:

# Check if there are any existing tests for HooksTab in the file or nearby
find apps/web-app/src/components/detail -name '*.test.*' -o -name '*.spec.*' | xargs ls -la

Repository: fum4/openkit

Length of output: 833


🏁 Script executed:

# Look for the full ansiToHtml function to understand its implementation
sed -n '49,80p' apps/web-app/src/components/detail/HooksTab.tsx

Repository: fum4/openkit

Length of output: 1001


🏁 Script executed:

# Check what ansiConverter is
rg -n 'ansiConverter' apps/web-app/src/components/detail/HooksTab.tsx -B5 -A5 | head -30

Repository: fum4/openkit

Length of output: 766


🏁 Script executed:

# Check for stripAnsiBg function
rg -n 'stripAnsiBg' apps/web-app/src/components/detail/HooksTab.tsx -B2 -A5

Repository: fum4/openkit

Length of output: 537


🏁 Script executed:

# Look at the imports and setup at top of HooksTab.tsx
head -60 apps/web-app/src/components/detail/HooksTab.tsx

Repository: fum4/openkit

Length of output: 1577


Add tests for HooksTab component covering HTML escaping and ANSI rendering.

HooksTab lacks a dedicated test file despite other sibling components (TerminalView, TodoList, NotesSection, etc.) having comprehensive test coverage. This component uses dangerouslySetInnerHTML with ansiToHtml() output in two places (lines 1172–1176 and 1306), which requires focused test coverage to verify:

  • HTML is properly escaped via escapeXML: true
  • ANSI color codes are correctly converted to HTML
  • ANSI background colors are stripped as intended

Per coding guidelines, tests are mandatory for every code change. Create HooksTab.test.tsx with assertions covering the ANSI-to-HTML rendering path.

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

In `@apps/web-app/src/components/detail/HooksTab.tsx` around lines 1172 - 1176,
Add a new test file HooksTab.test.tsx that mounts the HooksTab component and
asserts ANSI-to-HTML rendering and escaping behavior: render a sample hook
result (the prop/fixture containing result.output used in the component)
containing mixed ANSI color codes and literal HTML characters, then verify that
the DOM produced by the component (the nodes that use dangerouslySetInnerHTML
with ansiToHtml(result.output)) contains the expected ANSI-converted
spans/classes for foreground color, does not contain background-color inline
styles (ensuring background stripping), and that raw HTML characters (<, >, &,
", ') are escaped (not interpreted as tags) because ansiToHtml is configured
with escapeXML: true; use the same helpers/test harness used by sibling tests
(e.g., render from `@testing-library/react`) and reference HooksTab and ansiToHtml
to locate the rendering path to test.

@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: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
apps/web-app/src/components/detail/DetailPanel.tsx (2)

1-23: ⚠️ Potential issue | 🟡 Minor

Add the required file-level JSDoc.

This file still starts with imports even though its responsibility just expanded again.

As per coding guidelines "Every source file must have a JSDoc comment at the top (1-3 sentences) explaining what the file is for; update JSDoc when changing file responsibility".

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

In `@apps/web-app/src/components/detail/DetailPanel.tsx` around lines 1 - 23, Add
a 1–3 sentence file-level JSDoc comment at the very top of
apps/web-app/src/components/detail/DetailPanel.tsx describing the file's
responsibility (e.g., managing the detail panel UI, header, tabs like
DetailHeader, DiffViewerTab, LogsViewer, TerminalView, HooksTab, and related
modal/confirm logic); place it above all imports and keep it concise and
up-to-date with the expanded responsibilities of DetailPanel, mentioning the
main role and any notable subcomponents or responsibilities for quick reader
orientation.

1649-1659: ⚠️ Potential issue | 🟠 Major

Commit/push failures are swallowed in both handlers.

When commitChanges() or pushChanges() returns { success: false }, these handlers only clear loading state. The user gets no toast/banner, and there’s no log entry.

🐛 Proposed fix
   try {
     const result = await api.commitChanges(worktree.id, commitMessage.trim());
-    if (result.success) {
-      setShowCommitInput(false);
-      setCommitMessage("");
-      setGitOpKey((k) => k + 1);
-
-      if (pushAfterCommit) {
-        setGitAction("push");
-        await api.pushChanges(worktree.id);
-      }
-    }
+    if (!result.success) {
+      log.error("Failed to commit changes", {
+        domain: "git",
+        action: "git.commit",
+        worktreeId: worktree.id,
+        error: result.error ?? null,
+      });
+      setError(result.error || "Failed to commit changes");
+      return;
+    }
+
+    setShowCommitInput(false);
+    setCommitMessage("");
+    setGitOpKey((k) => k + 1);
+
+    if (pushAfterCommit) {
+      setGitAction("push");
+      const pushResult = await api.pushChanges(worktree.id);
+      if (!pushResult.success) {
+        log.error("Failed to push changes after commit", {
+          domain: "git",
+          action: "git.push",
+          worktreeId: worktree.id,
+          error: pushResult.error ?? null,
+        });
+        setError(pushResult.error || "Failed to push changes");
+        return;
+      }
+    }
     onUpdate();
   } finally {
@@
   try {
     const result = await api.pushChanges(worktree.id);
-    if (result.success) {
-      setGitOpKey((k) => k + 1);
-    }
+    if (!result.success) {
+      log.error("Failed to push changes", {
+        domain: "git",
+        action: "git.push",
+        worktreeId: worktree.id,
+        error: result.error ?? null,
+      });
+      setError(result.error || "Failed to push changes");
+      return;
+    }
+    setGitOpKey((k) => k + 1);
     onUpdate();
   } finally {

As per coding guidelines "Treat error handling as a first-class concern; every feature, bugfix, or refactor must account for every failure path", "Always surface user-facing errors through toast notifications (showPersistentErrorToast / reportPersistentErrorToast) and also log them through the logger — toasts are for users, logs are for debugging", and "Include actionable metadata in error logs: what operation failed, what inputs caused it, any IDs or state needed to reproduce".

Also applies to: 1673-1676

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

In `@apps/web-app/src/components/detail/DetailPanel.tsx` around lines 1649 - 1659,
The commit/push handlers swallow failures; update the success branches for
api.commitChanges(worktree.id, commitMessage.trim()) and
api.pushChanges(worktree.id) to handle result.success === false by calling
showPersistentErrorToast with a clear user message and calling
reportPersistentErrorToast or logger.error with actionable metadata (operation:
"commit" or "push", worktreeId: worktree.id, commitMessage:
commitMessage.trim(), and any result.error) so failures are both surfaced to the
user and logged for debugging; ensure existing state updates
(setShowCommitInput, setCommitMessage, setGitOpKey, loading flags, setGitAction)
still occur only on true success and that loading state is cleared on failure.
apps/web-app/src/components/detail/DiffFileSidebar.tsx (1)

210-257: ⚠️ Potential issue | 🟠 Major

Guard the header/row hotkeys from nested button key presses.

Line 215 and Line 446 still handle Enter/Space on the parent container, so now that these action buttons are keyboard-focusable, activating them also toggles the section or selects the file. That makes the new discard/stage actions unreliable without a mouse.

♿ Proposed fix
       onKeyDown={(e) => {
+        if (e.target !== e.currentTarget) return;
         if (e.key === "Enter" || e.key === " ") {
           e.preventDefault();
           onToggle();
         }
       }}
@@
       onKeyDown={(e) => {
+        if (e.target !== e.currentTarget) return;
         if (e.key === "Enter" || e.key === " ") {
           e.preventDefault();
           onSelect(key);
         }
       }}

Also applies to: 440-510

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

In `@apps/web-app/src/components/detail/DiffFileSidebar.tsx` around lines 210 -
257, The parent container's onKeyDown currently triggers on Enter/Space even
when focus is on nested interactive elements (the new discard/stage buttons), so
update the onKeyDown handler in the DiffFileSidebar header div (the div that
calls onToggle) to bail out when the event originated from a nested interactive
element: check e.key for "Enter" or " " as before but first if (e.target !==
e.currentTarget) return (or use e.target.closest('button, [role="button"], a,
input, textarea, select') to detect nested controls) so nested buttons handle
their own keys; apply the same guard to the other header/row onKeyDown
occurrences (the other div that toggles/selects the file) so keyboard activation
of nested buttons doesn't also toggle the section or select the file.
♻️ Duplicate comments (1)
apps/web-app/src/components/CreateWorktreeModal.tsx (1)

15-22: ⚠️ Potential issue | 🟠 Major

Restore toast + logger handling for create/pull failures.

These branches still only call setError, so branch/Jira/Linear failures stay modal-local instead of emitting the required toast + log pair. If ErrorBanner remains as a secondary cue, it also needs role="alert" so the failure is announced.

As per coding guidelines "Always surface user-facing errors through toast notifications (showPersistentErrorToast / reportPersistentErrorToast)", "Errors that surface as toasts must also be logged through the logger; toasts are for users, logs are for debugging - both are required", and "Do not introduce inline error text for operational failures when a toast can communicate the failure".

Also applies to: 145-157, 177-189, 219-224

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

In `@apps/web-app/src/components/CreateWorktreeModal.tsx` around lines 15 - 22,
Restore the persistent toast + logger behavior for create/pull failure paths
that currently only call setError: in the handlers that setError (e.g., the
create/pull failure branches inside CreateWorktreeModal) call
showPersistentErrorToast with a user-facing message and call
reportPersistentErrorToast or logger.error with the same error object/message so
the failure is both surfaced and logged; keep setError only for inline/secondary
UI state if desired. Also, if you keep ErrorBanner as an inline secondary cue,
add role="alert" to its root div (the ErrorBanner component) to ensure screen
readers announce the failure. Ensure you reference the existing functions
ErrorBanner, setError, showPersistentErrorToast,
reportPersistentErrorToast/logger when making the changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server/src/manager.ts`:
- Around line 1550-1653: The moveChangesToExistingWorktree workflow lacks a
start log and terminal outcome logs with stable metadata; add an entry log at
the start of moveChangesToExistingWorktree (include action:
"moveChangesToExistingWorktree", targetId: resolved.worktreeId,
gitRoot/targetPath) and add terminal logs on every exit point (both failure and
success) that include action, targetId, stashRef (when available), hasConflicts
(from applyResult when available) and error details; instrument failures like
the hasUncommitted check, stashPush catch, failed apply branch, stash restore
failure, stash drop warn, and the final success return to emit these structured
logs so each path records action/targetId/stashRef/hasConflicts and error where
applicable (use existing symbols: moveChangesToExistingWorktree,
resolved.worktreeId, gitRoot, targetPath, stashRef, applyResult, restoreResult,
dropErr, notifyListeners).
- Around line 1606-1625: When applyResult.applied is false and you call
stashApply(gitRoot, stashRef), if restoreResult.applied is true you must drop
the stash to avoid resurrecting duplicate changes later; update the failure
branch in the code handling applyResult (around variables applyResult,
stashApply, restoreResult, stashRef, gitRoot) to call the stash drop operation
(using the project's existing stash-drop helper or git command) when
restoreResult.applied is true, log the drop outcome, and only skip dropping when
restoreResult.applied is false (in which case retain the current error logging).

In `@libs/shared/src/git.ts`:
- Around line 725-798: The getFileContent function currently always reads the
working copy for the "new" side, which shows unstaged edits instead of staged
snapshots; add a boolean parameter (e.g., staged: boolean) to getFileContent and
when staged is true read the index snapshot for the "new" side instead of
readWorkingCopy; specifically, update the switch cases for "modified" and
"renamed" (and "added"/"untracked" if you want staged adds) to call a helper
that reads the index (create or use a gitShowIndex/gitShowFromIndex helper or
call gitShow with the index ref) for the newContent when staged===true,
otherwise keep using readWorkingCopy; ensure callers are updated to pass staged
appropriately.
- Around line 428-433: validateFilePath currently only performs lexical checks
and allows repo-controlled symlinks that point outside the worktree; update
validateFilePath to reject symlink targets by resolving and comparing real
paths: compute realWorktree = fs.realpathSync(worktreePath) and realResolved =
fs.realpathSync(resolved) (or use async equivalents), and return false if
realResolved does not start with realWorktree; also treat symlinks specially by
using fs.lstat to detect symlinks and reject when the symlink points outside the
worktree before calling readFile; apply the same realpath/lstat guard to the
callers mentioned (countUntrackedLines and readWorkingCopy) so any file reads
always verify the file’s realpath is inside the worktree.
- Around line 71-168: The git helpers (stageFiles, unstageFiles, stageAll,
unstageAll, revertFiles) call execFileAsync("git", ...) directly and therefore
skip resolveCommandPath()/withAugmentedPathEnv() and the centralized
start/success/failure logging; update each helper to invoke the shared git
runner (e.g., runGit(...) or execCmd(...) you added elsewhere) instead of
execFileAsync so the command path resolution, augmented PATH env, and
standardized logs are always used; ensure you pass the same args and cwd,
propagate errors and return values unchanged, and include the command/args/cwd
metadata when calling the runner so start/success/failure logs contain
actionable details (also update the per-file fallbacks in revertFiles to use the
runner for "checkout" and "rm" calls).
- Around line 76-88: unstageFiles and unstageAll fail in unborn repos because
they rely on HEAD; update both to first detect an unborn repo the same way
getChangedFiles() does (check if HEAD exists via git rev-parse --verify HEAD)
and, when HEAD is missing, use git commands that don't require HEAD: for
unstageFiles(cwd, paths) run git rm --cached --ignore-unmatch -- <paths> as the
fallback, and for unstageAll(cwd) run git rm --cached -r --ignore-unmatch -- .
as the fallback; otherwise keep the existing git restore --staged and git reset
HEAD behavior. Ensure detection and fallback logic is implemented inside the
unstageFiles and unstageAll functions.

---

Outside diff comments:
In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 1-23: Add a 1–3 sentence file-level JSDoc comment at the very top
of apps/web-app/src/components/detail/DetailPanel.tsx describing the file's
responsibility (e.g., managing the detail panel UI, header, tabs like
DetailHeader, DiffViewerTab, LogsViewer, TerminalView, HooksTab, and related
modal/confirm logic); place it above all imports and keep it concise and
up-to-date with the expanded responsibilities of DetailPanel, mentioning the
main role and any notable subcomponents or responsibilities for quick reader
orientation.
- Around line 1649-1659: The commit/push handlers swallow failures; update the
success branches for api.commitChanges(worktree.id, commitMessage.trim()) and
api.pushChanges(worktree.id) to handle result.success === false by calling
showPersistentErrorToast with a clear user message and calling
reportPersistentErrorToast or logger.error with actionable metadata (operation:
"commit" or "push", worktreeId: worktree.id, commitMessage:
commitMessage.trim(), and any result.error) so failures are both surfaced to the
user and logged for debugging; ensure existing state updates
(setShowCommitInput, setCommitMessage, setGitOpKey, loading flags, setGitAction)
still occur only on true success and that loading state is cleared on failure.

In `@apps/web-app/src/components/detail/DiffFileSidebar.tsx`:
- Around line 210-257: The parent container's onKeyDown currently triggers on
Enter/Space even when focus is on nested interactive elements (the new
discard/stage buttons), so update the onKeyDown handler in the DiffFileSidebar
header div (the div that calls onToggle) to bail out when the event originated
from a nested interactive element: check e.key for "Enter" or " " as before but
first if (e.target !== e.currentTarget) return (or use e.target.closest('button,
[role="button"], a, input, textarea, select') to detect nested controls) so
nested buttons handle their own keys; apply the same guard to the other
header/row onKeyDown occurrences (the other div that toggles/selects the file)
so keyboard activation of nested buttons doesn't also toggle the section or
select the file.

---

Duplicate comments:
In `@apps/web-app/src/components/CreateWorktreeModal.tsx`:
- Around line 15-22: Restore the persistent toast + logger behavior for
create/pull failure paths that currently only call setError: in the handlers
that setError (e.g., the create/pull failure branches inside
CreateWorktreeModal) call showPersistentErrorToast with a user-facing message
and call reportPersistentErrorToast or logger.error with the same error
object/message so the failure is both surfaced and logged; keep setError only
for inline/secondary UI state if desired. Also, if you keep ErrorBanner as an
inline secondary cue, add role="alert" to its root div (the ErrorBanner
component) to ensure screen readers announce the failure. Ensure you reference
the existing functions ErrorBanner, setError, showPersistentErrorToast,
reportPersistentErrorToast/logger when making the changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 732864b2-fb4a-4c4e-9690-d415bd3764ff

📥 Commits

Reviewing files that changed from the base of the PR and between 5066e89 and 6cb58c8.

📒 Files selected for processing (7)
  • apps/server/src/manager.ts
  • apps/server/src/routes/github.ts
  • apps/server/src/routes/worktrees.ts
  • apps/web-app/src/components/CreateWorktreeModal.tsx
  • apps/web-app/src/components/detail/DetailPanel.tsx
  • apps/web-app/src/components/detail/DiffFileSidebar.tsx
  • libs/shared/src/git.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/server/src/routes/github.ts
  • apps/server/src/routes/worktrees.ts

Comment thread apps/server/src/manager.ts Resolved
Comment thread apps/server/src/manager.ts Resolved
Comment thread libs/shared/src/git.ts
Comment on lines +71 to +168
export async function stageFiles(cwd: string, paths: string[]): Promise<void> {
await execFileAsync("git", ["add", "--", ...paths], { cwd, encoding: "utf-8" });
}

/** Unstage specific files (move from index back to working tree). */
export async function unstageFiles(cwd: string, paths: string[]): Promise<void> {
await execFileAsync("git", ["restore", "--staged", "--", ...paths], { cwd, encoding: "utf-8" });
}

/** Stage all changes in the working tree. */
export async function stageAll(cwd: string): Promise<void> {
await execFileAsync("git", ["add", "-A"], { cwd, encoding: "utf-8" });
}

/** Unstage all staged changes. */
export async function unstageAll(cwd: string): Promise<void> {
await execFileAsync("git", ["reset", "HEAD"], { cwd, encoding: "utf-8" });
}

/**
* Validate that all paths are relative and resolve within cwd.
* Returns the first invalid path, or null if all paths are valid.
*/
export function validatePathsWithinCwd(cwd: string, paths: string[]): string | null {
const resolvedCwd = path.resolve(cwd);
for (const p of paths) {
const abs = path.resolve(cwd, p);
const rel = path.relative(resolvedCwd, abs);
if (rel.startsWith("..") || !abs.startsWith(resolvedCwd)) {
return p;
}
}
return null;
}

/**
* Revert (discard) changes for specific files.
* For staged files: restores from HEAD to both index and working tree.
* For unstaged files: restores working tree from index (deletes untracked files).
* Returns partial failure details if some files couldn't be reverted.
*/
export async function revertFiles(
cwd: string,
paths: string[],
staged: boolean,
): Promise<string[]> {
// Defense-in-depth: validate paths even if the caller already checked
const invalidPath = validatePathsWithinCwd(cwd, paths);
if (invalidPath) {
return [`${invalidPath}: path traversal not allowed`];
}

if (staged) {
// Batch first — works for all files that exist in HEAD
try {
await execFileAsync("git", ["checkout", "HEAD", "--", ...paths], { cwd, encoding: "utf-8" });
return [];
} catch {
// Batch failed — process individually. Newly added files (not in HEAD) need git rm -f.
const errors: string[] = [];
for (const p of paths) {
try {
await execFileAsync("git", ["checkout", "HEAD", "--", p], { cwd, encoding: "utf-8" });
} catch {
try {
await execFileAsync("git", ["rm", "-f", "--", p], { cwd, encoding: "utf-8" });
} catch (rmErr) {
errors.push(`${p}: ${rmErr instanceof Error ? rmErr.message : "failed to revert"}`);
}
}
}
return errors;
}
} else {
// Batch first — works for tracked modified/deleted files
try {
await execFileAsync("git", ["checkout", "--", ...paths], { cwd, encoding: "utf-8" });
return [];
} catch {
// Batch failed — process individually. Untracked files need to be deleted.
const errors: string[] = [];
for (const p of paths) {
try {
await execFileAsync("git", ["checkout", "--", p], { cwd, encoding: "utf-8" });
} catch {
try {
await unlink(path.join(cwd, p));
} catch (unlinkErr) {
errors.push(
`${p}: ${unlinkErr instanceof Error ? unlinkErr.message : "failed to revert"}`,
);
}
}
}
return errors;
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Route the new git helpers through one logged runGit() path.

These helpers all shell out with raw execFileAsync("git", ...), so they skip the resolveCommandPath() / withAugmentedPathEnv() handling you added later in execCmd() and never emit required start/success/failure logs. That makes behavior inconsistent across operations and leaves git failures without actionable metadata.

♻️ Sketch of the shared runner
+async function runGit(
+  cwd: string,
+  args: string[],
+  metadata: Record<string, unknown> = {},
+) {
+  log.info("git command started", { domain: "git", cwd, args, ...metadata });
+  try {
+    const result = await execCmd("git", args, cwd);
+    log.success("git command completed", { domain: "git", cwd, args, ...metadata });
+    return result;
+  } catch (error) {
+    log.error("git command failed", {
+      domain: "git",
+      cwd,
+      args,
+      ...metadata,
+      error: error instanceof Error ? error.message : String(error),
+    });
+    throw error;
+  }
+}
...
-  await execFileAsync("git", ["add", "--", ...paths], { cwd, encoding: "utf-8" });
+  await runGit(cwd, ["add", "--", ...paths], { operation: "stageFiles", paths });

Based on learnings "Treat ops logging as mandatory for all operations — always log start and terminal outcome for git operations..." and "Include actionable metadata in operational logs whenever available (command, args, cwd, status code, request/response payload metadata, worktreeId, projectName, error details)".

Also applies to: 175-415

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

In `@libs/shared/src/git.ts` around lines 71 - 168, The git helpers (stageFiles,
unstageFiles, stageAll, unstageAll, revertFiles) call execFileAsync("git", ...)
directly and therefore skip resolveCommandPath()/withAugmentedPathEnv() and the
centralized start/success/failure logging; update each helper to invoke the
shared git runner (e.g., runGit(...) or execCmd(...) you added elsewhere)
instead of execFileAsync so the command path resolution, augmented PATH env, and
standardized logs are always used; ensure you pass the same args and cwd,
propagate errors and return values unchanged, and include the command/args/cwd
metadata when calling the runner so start/success/failure logs contain
actionable details (also update the per-file fallbacks in revertFiles to use the
runner for "checkout" and "rm" calls).

Comment thread libs/shared/src/git.ts
Comment on lines +76 to +88
export async function unstageFiles(cwd: string, paths: string[]): Promise<void> {
await execFileAsync("git", ["restore", "--staged", "--", ...paths], { cwd, encoding: "utf-8" });
}

/** Stage all changes in the working tree. */
export async function stageAll(cwd: string): Promise<void> {
await execFileAsync("git", ["add", "-A"], { cwd, encoding: "utf-8" });
}

/** Unstage all staged changes. */
export async function unstageAll(cwd: string): Promise<void> {
await execFileAsync("git", ["reset", "HEAD"], { cwd, encoding: "utf-8" });
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT

git init "$tmp_dir/repro" >/dev/null
cd "$tmp_dir/repro"

printf 'tracked\n' > tracked.txt
git add tracked.txt

echo '$ git restore --staged -- tracked.txt'
git restore --staged -- tracked.txt 2>&1 || true
echo

git add tracked.txt
printf 'untracked\n' > untracked.txt

echo '$ git diff --cached --name-status'
git diff --cached --name-status
echo

echo '$ git ls-files --others --exclude-standard'
git ls-files --others --exclude-standard
echo

echo '$ git reset HEAD'
git reset HEAD 2>&1 || true

Repository: fum4/openkit

Length of output: 997


🏁 Script executed:

#!/bin/bash
# First, let's locate and examine the git.ts file
find . -type f -name "git.ts" | head -5

Repository: fum4/openkit

Length of output: 80


🏁 Script executed:

#!/bin/bash
# Check lines around 76-88 to see unstageFiles, stageAll, unstageAll
sed -n '70,95p' "libs/shared/src/git.ts" | cat -n

Repository: fum4/openkit

Length of output: 1333


🏁 Script executed:

#!/bin/bash
# Check lines around 598-602 to see what's mentioned there
wc -l "libs/shared/src/git.ts"

Repository: fum4/openkit

Length of output: 82


🏁 Script executed:

#!/bin/bash
# Find getChangedFiles function
rg "function getChangedFiles" "libs/shared/src/git.ts" -A 15

Repository: fum4/openkit

Length of output: 546


🏁 Script executed:

#!/bin/bash
# Check lines around 598-602
sed -n '595,610p' "libs/shared/src/git.ts" | cat -n

Repository: fum4/openkit

Length of output: 633


🏁 Script executed:

#!/bin/bash
# Check what's at the exact lines 598-602 to understand "Also applies to" reference
sed -n '598,610p' "libs/shared/src/git.ts" | cat -n

Repository: fum4/openkit

Length of output: 583


🏁 Script executed:

#!/bin/bash
# Search for where unstageFiles and unstageAll are called
rg "unstageFiles|unstageAll" "libs/shared/src/" -B 2 -A 2

Repository: fum4/openkit

Length of output: 720


🏁 Script executed:

#!/bin/bash
# Search for callers of unstageFiles and unstageAll across the entire codebase
rg "unstageFiles|unstageAll" . --type ts --type tsx -B 2 -A 2 | grep -v "node_modules"

Repository: fum4/openkit

Length of output: 83


🏁 Script executed:

#!/bin/bash
# Check what's exported from git.ts to understand the public API
head -50 "libs/shared/src/git.ts" | cat -n

Repository: fum4/openkit

Length of output: 2213


🏁 Script executed:

#!/bin/bash
# Search for callers of unstageFiles and unstageAll across the entire codebase
rg "unstageFiles|unstageAll" . -B 2 -A 2 | head -100

Repository: fum4/openkit

Length of output: 6395


🏁 Script executed:

#!/bin/bash
# Check if there are any tests for these functions
fd "git" . -type f -name "*.test.ts" -o -name "*.spec.ts" | head -10

Repository: fum4/openkit

Length of output: 226


🏁 Script executed:

#!/bin/bash
# Find test files related to git
fd ".*test.*" . -type f -path "*git*" | head -20

Repository: fum4/openkit

Length of output: 226


🏁 Script executed:

#!/bin/bash
# Look at the server route handler for unstageFiles/unstageAll to see error handling
sed -n '1,50p' "apps/server/src/routes/github.ts" | cat -n

Repository: fum4/openkit

Length of output: 2000


🏁 Script executed:

#!/bin/bash
# Search for the unstageFiles endpoint in github.ts
rg "unstageFiles|unstageAll" "apps/server/src/routes/github.ts" -B 5 -A 10

Repository: fum4/openkit

Length of output: 1671


Handle unborn repositories in unstage functions to match getChangedFiles() behavior.

unstageFiles() and unstageAll() fail with "fatal: could not resolve HEAD" in fresh repositories, while getChangedFiles() gracefully returns empty files when HEAD is missing. This creates an inconsistency: the diff panel shows no changes in unborn repos, but attempting to unstage staged files throws an error—even though git diff --cached and git ls-files --others continue to work and report staged/untracked files.

Both functions require HEAD to exist (used by git restore --staged and git reset HEAD). Either check for unborn repos upfront (like getChangedFiles() does) or use alternative commands that work in that state.

Also applies to: 598-602

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

In `@libs/shared/src/git.ts` around lines 76 - 88, unstageFiles and unstageAll
fail in unborn repos because they rely on HEAD; update both to first detect an
unborn repo the same way getChangedFiles() does (check if HEAD exists via git
rev-parse --verify HEAD) and, when HEAD is missing, use git commands that don't
require HEAD: for unstageFiles(cwd, paths) run git rm --cached --ignore-unmatch
-- <paths> as the fallback, and for unstageAll(cwd) run git rm --cached -r
--ignore-unmatch -- . as the fallback; otherwise keep the existing git restore
--staged and git reset HEAD behavior. Ensure detection and fallback logic is
implemented inside the unstageFiles and unstageAll functions.

Comment thread libs/shared/src/git.ts
Comment on lines +373 to +387
export async function stashPush(cwd: string, message: string): Promise<string | null> {
const { stdout } = await execFileAsync(
"git",
["stash", "push", "--include-untracked", "-m", message],
{ cwd, encoding: "utf-8" },
);
if (stdout.includes("No local changes")) {
return null;
}
const { stdout: refOut } = await execFileAsync(
"git",
["stash", "list", "--max-count=1", "--format=%H"],
{ cwd, encoding: "utf-8" },
);
return refOut.trim() || null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT

git init "$tmp_dir/repro" >/dev/null
cd "$tmp_dir/repro"
git config user.email [email protected]
git config user.name tester

printf 'base\n' > file.txt
git add file.txt
git commit -m init >/dev/null

printf 'first\n' > file.txt
git stash push -m stash-a >/dev/null

# Another stash appears before the first caller resolves "its" ref.
printf 'second\n' > file.txt
git stash push -m stash-b >/dev/null

echo '$ git stash list --max-count=1 --format=%H%x09%gs'
git stash list --max-count=1 --format=%H%x09%gs
echo
echo '$ git stash list --format=%H%x09%gs'
git stash list --format=%H%x09%gs

Repository: fum4/openkit

Length of output: 886


🏁 Script executed:

cat -n libs/shared/src/git.ts | sed -n '373,387p'

Repository: fum4/openkit

Length of output: 650


🏁 Script executed:

rg "stashPush" --type ts --type tsx -B 2 -A 5

Repository: fum4/openkit

Length of output: 83


🏁 Script executed:

rg "stashPush" --type ts -B 2 -A 5

Repository: fum4/openkit

Length of output: 1580


🏁 Script executed:

rg "stashRef" apps/server/src/manager.ts -B 5 -A 10

Repository: fum4/openkit

Length of output: 5349


Fix race condition in stashPush() that can return the wrong stash ref.

stashPush() creates a stash with one command, then attempts to resolve its ref with a separate git stash list --max-count=1 command. If another stash operation completes between these two commands, this function returns the wrong SHA. The stash ref is subsequently used to apply, restore, or drop changes in the move-to-existing-worktree flow—applying the wrong stash corrupts user state.

Use git stash push output directly to capture the stash ref atomically, rather than querying for the newest stash afterward.

Comment thread libs/shared/src/git.ts
Comment on lines +428 to +433
function validateFilePath(worktreePath: string, filePath: string): boolean {
if (!filePath || filePath.startsWith("/") || filePath.includes("..")) return false;
const resolved = path.resolve(worktreePath, filePath);
const rel = path.relative(worktreePath, resolved);
return !rel.startsWith("..") && !rel.startsWith("/");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Reject symlink targets before reading file contents.

validateFilePath() only does lexical checks. A repo-controlled symlink like leak -> /etc/passwd still passes that validator, and both countUntrackedLines() and readWorkingCopy() will follow it with readFile(). That turns the diff endpoints into an arbitrary local-file read primitive outside the worktree.

Also applies to: 541-558, 826-846

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

In `@libs/shared/src/git.ts` around lines 428 - 433, validateFilePath currently
only performs lexical checks and allows repo-controlled symlinks that point
outside the worktree; update validateFilePath to reject symlink targets by
resolving and comparing real paths: compute realWorktree =
fs.realpathSync(worktreePath) and realResolved = fs.realpathSync(resolved) (or
use async equivalents), and return false if realResolved does not start with
realWorktree; also treat symlinks specially by using fs.lstat to detect symlinks
and reject when the symlink points outside the worktree before calling readFile;
apply the same realpath/lstat guard to the callers mentioned
(countUntrackedLines and readWorkingCopy) so any file reads always verify the
file’s realpath is inside the worktree.

Comment thread libs/shared/src/git.ts
Comment on lines +725 to +798
export async function getFileContent(
worktreePath: string,
filePath: string,
fileStatus: DiffFileInfo["status"],
baseBranch: string,
includeCommitted: boolean,
oldPath?: string,
): Promise<{ oldContent: string; newContent: string; error?: string }> {
log.debug("getFileContent started", {
domain: "diff",
filePath,
fileStatus,
includeCommitted,
});

if (!validateFilePath(worktreePath, filePath)) {
return { oldContent: "", newContent: "", error: "Invalid file path" };
}
if (oldPath && !validateFilePath(worktreePath, oldPath)) {
return { oldContent: "", newContent: "", error: "Invalid old file path" };
}

// Use base branch ref when showing committed changes; fall back to HEAD if it doesn't exist
let ref = "HEAD";
if (includeCommitted) {
const baseRef = `origin/${normalizeBaseBranch(baseBranch)}`;
if (await hasRef(worktreePath, baseRef)) {
ref = baseRef;
}
}

try {
let oldContent = "";
let newContent = "";

switch (fileStatus) {
case "modified": {
const [old, current] = await Promise.all([
gitShow(worktreePath, ref, filePath),
readWorkingCopy(worktreePath, filePath),
]);
oldContent = old;
newContent = current;
break;
}
case "added":
case "untracked": {
newContent = await readWorkingCopy(worktreePath, filePath);
break;
}
case "deleted": {
oldContent = await gitShow(worktreePath, ref, filePath);
break;
}
case "renamed": {
const [old, current] = await Promise.all([
gitShow(worktreePath, ref, oldPath ?? filePath),
readWorkingCopy(worktreePath, filePath),
]);
oldContent = old;
newContent = current;
break;
}
}

return { oldContent, newContent };
} catch (err) {
log.error("getFileContent failed", { domain: "diff", filePath, error: err });
return {
oldContent: "",
newContent: "",
error: err instanceof Error ? err.message : String(err),
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Thread staged state into getFileContent().

Lines 615-617 and Lines 631-633 deliberately split staged and unstaged rows, but this API only receives fileStatus and always reads the working copy for the “new” side. If a file has staged changes plus later unstaged edits, opening the staged row renders the wrong diff because it shows the current working tree instead of the index snapshot.

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

In `@libs/shared/src/git.ts` around lines 725 - 798, The getFileContent function
currently always reads the working copy for the "new" side, which shows unstaged
edits instead of staged snapshots; add a boolean parameter (e.g., staged:
boolean) to getFileContent and when staged is true read the index snapshot for
the "new" side instead of readWorkingCopy; specifically, update the switch cases
for "modified" and "renamed" (and "added"/"untracked" if you want staged adds)
to call a helper that reads the index (create or use a
gitShowIndex/gitShowFromIndex helper or call gitShow with the index ref) for the
newContent when staged===true, otherwise keep using readWorkingCopy; ensure
callers are updated to pass staged appropriately.

@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: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web-app/src/components/detail/DetailPanel.tsx (1)

1627-1663: ⚠️ Potential issue | 🟠 Major

Commit and push handlers don't surface errors.

handleCommit and handlePush call onUpdate() but don't show toast on failure. Users performing git operations need feedback when they fail.

♻️ Proposed fix for handlePush
 const handlePush = async () => {
   setIsGitLoading(true);
   setGitAction("push");
   try {
     const result = await api.pushChanges(worktree.id);
     if (result.success) {
       setGitOpKey((k) => k + 1);
+    } else {
+      showPersistentErrorToast(result.error ?? "Failed to push changes");
     }
     onUpdate();
   } finally {
     setIsGitLoading(false);
     setGitAction(null);
   }
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/detail/DetailPanel.tsx` around lines 1627 - 1663,
Both handleCommit and handlePush swallow API failures and only call onUpdate();
update them to detect when api.commitChanges or api.pushChanges returns a
non-success result (or throws) and show a user-facing toast error with the
failure message, while preserving existing success behavior (e.g., setGitOpKey,
hide commit input, clear commitMessage, and pushAfterCommit flow in
handleCommit). In handleCommit, after awaiting api.commitChanges(worktree.id,
commitMessage.trim()), if result.success is false or result.error exists, call
the toast error helper with the error text and skip the success-only state
changes; similarly in handlePush, if result.success is false show a toast error
with the returned/exception message before calling onUpdate(). Also wrap API
calls in try/catch to catch thrown errors, showing a toast in the catch block
and reusing setIsGitLoading(false)/setGitAction(null) in the finally block as
currently implemented.
🧹 Nitpick comments (2)
libs/shared/src/git.ts (1)

241-243: Silent catch blocks violate error handling guidelines.

Multiple catch blocks in getGitStatus silently ignore errors without logging. Per coding guidelines, every catch block must do something meaningful—either log or surface the error. While these are non-critical status checks, production debugging becomes impossible without any trace of failures.

   } catch {
-    // Ignore
+    log.debug("Failed to get uncommitted status", { domain: "git", worktreePath });
   }

Apply similar logging to all silent catch blocks in this function.

Also applies to: 254-257, 268-271, 287-289, 308-310

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

In `@libs/shared/src/git.ts` around lines 241 - 243, In getGitStatus, replace the
silent catch blocks (currently written as catch { // Ignore }) with logging that
records the error and context so failures can be diagnosed: inside each catch in
getGitStatus (the blocks around lines handling worktree detection, branch
parsing, remote checks, and file status checks) call the project's logger (or
console.warn/debug) to log a brief message including the function name, which
sub-step failed (e.g., "detecting worktree", "parsing branch", "checking
remote", "reading file status"), and the caught error object; ensure you
preserve existing control flow (don’t rethrow) but include the error details in
the log for every previously-silent catch.
apps/web-app/src/components/detail/DiffViewerTab.tsx (1)

191-195: Missing fetchFiles in dependency array triggers lint warning.

The effect depends on fetchFiles but the eslint-disable comment suppresses the warning. While the intent is to only trigger on gitOpKey changes, this pattern is fragile. Consider using a ref to track the previous key instead.

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

In `@apps/web-app/src/components/detail/DiffViewerTab.tsx` around lines 191 - 195,
Replace the current effect and eslint-disable by tracking the previous gitOpKey
with a ref: create a prevGitOpKeyRef in the DiffViewerTab component, then in a
useEffect compare prevGitOpKeyRef.current to the current gitOpKey and call
fetchFiles() only when they differ and showMergedDiff is false, finally update
prevGitOpKeyRef.current = gitOpKey; include fetchFiles and showMergedDiff in the
effect dependency array so the linter is satisfied and remove the eslint-disable
comment.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/web-app/src/components/detail/DiffViewerTab.tsx`:
- Around line 303-327: Each handler (handleStageFile, handleUnstageFile,
handleStageAll, handleUnstageAll) currently awaits the API call and always calls
fetchFiles; change them to capture the API response, check its success flag, and
surface failures via the persistent toast utilities: call
showPersistentErrorToast or reportPersistentErrorToast with the returned error
message when response.success is false (and do not call fetchFiles), and also
wrap the await in try/catch to report unexpected exceptions via the same toast
functions; reference the API calls stageFiles, unstageFiles, stageAllFiles,
unstageAllFiles and the refresh function fetchFiles when implementing this
logic.
- Around line 329-359: The handlers handleStagePaths, handleUnstagePaths,
handleRevertPaths and handleRevertFile call stageFiles/unstageFiles/revertFiles
but ignore the returned result and any errors; update each to capture the API
response (e.g., const result = await stageFiles(...)), wrap the await in
try/catch to surface thrown errors, check result.success before calling
fetchFiles, and on failure show an error to the user (e.g., toast or setError)
with result.error or the caught exception; keep fetchFiles() only on success so
the UI isn't refreshed on failed operations.
- Around line 402-422: The bulk-revert handlers handleRevertAllStaged and
handleRevertAllUnstaged call revertFiles but ignore its result and any errors;
wrap the await revertFiles(...) call in a try/catch, inspect the API response
(or thrown error) and if it indicates failure surface a user-visible error
(e.g., call the existing notification/toast or error handler used elsewhere in
this file) and do not call fetchFiles on failure; on success proceed to call
fetchFiles as now. Refer to handleRevertAllStaged, handleRevertAllUnstaged,
revertFiles and fetchFiles to locate where to add the try/catch and notification
logic.

In `@apps/web-app/src/components/detail/JiraDetailPanel.tsx`:
- Line 478: Replace the silent early return on failed operations with a
user-facing persistent toast and optional logging: wherever you have checks like
"if (!result.success) return;" in JiraDetailPanel handlers (e.g.,
handleUpdateStatus, handleUpdatePriority, handleUpdateType, comment handlers,
handleSaveDescription and similar), call reportPersistentErrorToast or
showPersistentErrorToast with a clear message (e.g., "Failed to update status" /
"Failed to save description") and include any result.error or result.message;
also log the error via logger.error where appropriate, then return. Ensure every
catch/failure branch in those functions surfaces a toast and/or logs instead of
silently returning.

In `@apps/web-app/src/components/detail/LinearDetailPanel.tsx`:
- Line 361: The handlers in LinearDetailPanel (e.g., handleAddComment and the
status/priority/comment/description handlers) currently short-circuit on
failures with "if (!result.success) return;" (and some silent catch blocks);
replace these silent failures with user-facing toast error notifications: when
result.success is false, call the existing toast/error utility to show a
descriptive message including result.error or a sensible default, and in catch
blocks do the same instead of swallowing errors; ensure you update all affected
methods referenced in the comment (the handlers at the indicated locations) so
every failed async operation surfaces a toast with context (e.g., "Failed to add
comment" / "Failed to update status") and the underlying error text when
available.

In `@libs/shared/src/git.ts`:
- Around line 299-310: The current block uses execFileAsync("wc", ["-l",
...untrackedFiles], ...) which is not portable (missing on Windows); replace
this with Node fs APIs: iterate untrackedFiles, read each file from worktreePath
(use fs.promises.readFile or a streaming reader), count line breaks (e.g., count
"\n" occurrences, treating empty file as 0), sum into linesAdded, and preserve
the same error-tolerant behavior around the try/catch; update references to
untrackedFiles, worktreePath and linesAdded and remove reliance on
wcOut/execFileAsync.

---

Outside diff comments:
In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 1627-1663: Both handleCommit and handlePush swallow API failures
and only call onUpdate(); update them to detect when api.commitChanges or
api.pushChanges returns a non-success result (or throws) and show a user-facing
toast error with the failure message, while preserving existing success behavior
(e.g., setGitOpKey, hide commit input, clear commitMessage, and pushAfterCommit
flow in handleCommit). In handleCommit, after awaiting
api.commitChanges(worktree.id, commitMessage.trim()), if result.success is false
or result.error exists, call the toast error helper with the error text and skip
the success-only state changes; similarly in handlePush, if result.success is
false show a toast error with the returned/exception message before calling
onUpdate(). Also wrap API calls in try/catch to catch thrown errors, showing a
toast in the catch block and reusing setIsGitLoading(false)/setGitAction(null)
in the finally block as currently implemented.

---

Nitpick comments:
In `@apps/web-app/src/components/detail/DiffViewerTab.tsx`:
- Around line 191-195: Replace the current effect and eslint-disable by tracking
the previous gitOpKey with a ref: create a prevGitOpKeyRef in the DiffViewerTab
component, then in a useEffect compare prevGitOpKeyRef.current to the current
gitOpKey and call fetchFiles() only when they differ and showMergedDiff is
false, finally update prevGitOpKeyRef.current = gitOpKey; include fetchFiles and
showMergedDiff in the effect dependency array so the linter is satisfied and
remove the eslint-disable comment.

In `@libs/shared/src/git.ts`:
- Around line 241-243: In getGitStatus, replace the silent catch blocks
(currently written as catch { // Ignore }) with logging that records the error
and context so failures can be diagnosed: inside each catch in getGitStatus (the
blocks around lines handling worktree detection, branch parsing, remote checks,
and file status checks) call the project's logger (or console.warn/debug) to log
a brief message including the function name, which sub-step failed (e.g.,
"detecting worktree", "parsing branch", "checking remote", "reading file
status"), and the caught error object; ensure you preserve existing control flow
(don’t rethrow) but include the error details in the log for every
previously-silent catch.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a83e3b66-16c6-4baa-86f4-078dd64453e5

📥 Commits

Reviewing files that changed from the base of the PR and between 6cb58c8 and ba3b368.

📒 Files selected for processing (9)
  • .claude/settings.json
  • apps/web-app/src/components/IntegrationsPanel.tsx
  • apps/web-app/src/components/detail/CustomTaskDetailPanel.tsx
  • apps/web-app/src/components/detail/DetailHeader.tsx
  • apps/web-app/src/components/detail/DetailPanel.tsx
  • apps/web-app/src/components/detail/DiffViewerTab.tsx
  • apps/web-app/src/components/detail/JiraDetailPanel.tsx
  • apps/web-app/src/components/detail/LinearDetailPanel.tsx
  • libs/shared/src/git.ts
💤 Files with no reviewable changes (2)
  • apps/web-app/src/components/IntegrationsPanel.tsx
  • apps/web-app/src/components/detail/CustomTaskDetailPanel.tsx
✅ Files skipped from review due to trivial changes (2)
  • .claude/settings.json
  • apps/web-app/src/components/detail/DetailHeader.tsx

Comment on lines +329 to +359
const handleStagePaths = useCallback(
async (paths: string[]) => {
await stageFiles(worktree.id, paths, serverUrl);
fetchFiles();
},
[worktree.id, serverUrl, fetchFiles],
);

const handleUnstagePaths = useCallback(
async (paths: string[]) => {
await unstageFiles(worktree.id, paths, serverUrl);
fetchFiles();
},
[worktree.id, serverUrl, fetchFiles],
);

const handleRevertPaths = useCallback(
async (paths: string[], staged: boolean) => {
await revertFiles(worktree.id, paths, staged, serverUrl);
fetchFiles();
},
[worktree.id, serverUrl, fetchFiles],
);

const handleRevertFile = useCallback(
async (filePath: string, staged: boolean) => {
await revertFiles(worktree.id, [filePath], staged, serverUrl);
fetchFiles();
},
[worktree.id, serverUrl, fetchFiles],
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Revert handlers silently ignore API failures.

Same issue as above—handleStagePaths, handleUnstagePaths, handleRevertPaths, and handleRevertFile don't check result.success or surface errors to users.

♻️ Proposed fix for handleRevertFile
 const handleRevertFile = useCallback(
   async (filePath: string, staged: boolean) => {
-    await revertFiles(worktree.id, [filePath], staged, serverUrl);
-    fetchFiles();
+    const result = await revertFiles(worktree.id, [filePath], staged, serverUrl);
+    if (!result.success) {
+      showPersistentErrorToast(result.error ?? "Failed to discard changes");
+    }
+    fetchFiles();
   },
   [worktree.id, serverUrl, fetchFiles],
 );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/detail/DiffViewerTab.tsx` around lines 329 - 359,
The handlers handleStagePaths, handleUnstagePaths, handleRevertPaths and
handleRevertFile call stageFiles/unstageFiles/revertFiles but ignore the
returned result and any errors; update each to capture the API response (e.g.,
const result = await stageFiles(...)), wrap the await in try/catch to surface
thrown errors, check result.success before calling fetchFiles, and on failure
show an error to the user (e.g., toast or setError) with result.error or the
caught exception; keep fetchFiles() only on success so the UI isn't refreshed on
failed operations.

});
return;
}
if (!result.success) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Silent failure handling violates error notification guidelines.

These changes remove reportPersistentErrorToast calls and replace them with silent early returns. When status/priority/type updates, comment operations, or description saves fail, users receive no feedback—they'll assume the action succeeded when it didn't.

As per coding guidelines: "Always surface user-facing errors through toast notifications (showPersistentErrorToast / reportPersistentErrorToast)" and "Every catch block, fallback branch, and error callback must do something meaningful (log via logger, surface via toast); silent catch {} blocks are never acceptable."

🔧 Example fix for handleUpdateStatus (apply similar pattern to other handlers)
   const handleUpdateStatus = async (statusName: string) => {
     if (!statusName) return;
     const currentIssueKey = issue?.key;
     if (!currentIssueKey) return;
     if (statusName === issue?.status) return;
     setIsUpdatingStatus(true);
     const result = await api.updateJiraIssueStatus(currentIssueKey, statusName);
     setIsUpdatingStatus(false);
-    if (!result.success) return;
+    if (!result.success) {
+      reportPersistentErrorToast(
+        result.error || "Failed to update status",
+        "Status update failed",
+        { scope: "jira:update-status" }
+      );
+      return;
+    }
     await refetch();
   };

Also applies to: 490-490, 502-502, 550-550, 573-573, 586-586, 907-907

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

In `@apps/web-app/src/components/detail/JiraDetailPanel.tsx` at line 478, Replace
the silent early return on failed operations with a user-facing persistent toast
and optional logging: wherever you have checks like "if (!result.success)
return;" in JiraDetailPanel handlers (e.g., handleUpdateStatus,
handleUpdatePriority, handleUpdateType, comment handlers, handleSaveDescription
and similar), call reportPersistentErrorToast or showPersistentErrorToast with a
clear message (e.g., "Failed to update status" / "Failed to save description")
and include any result.error or result.message; also log the error via
logger.error where appropriate, then return. Ensure every catch/failure branch
in those functions surfaces a toast and/or logs instead of silently returning.

});
return;
}
if (!result.success) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Silent failure handling violates error notification guidelines.

Same issue as in JiraDetailPanel.tsx—these changes remove toast notifications for failed operations, leaving users without feedback when status/priority updates, comment operations, or description saves fail.

As per coding guidelines: "Always surface user-facing errors through toast notifications" and "silent catch {} blocks are never acceptable."

🔧 Example fix for handleAddComment (apply similar pattern to other handlers)
   const handleAddComment = async () => {
     const comment = newComment.trim();
     if (!comment) return;
     const currentIssueIdentifier = issue?.identifier;
     if (!currentIssueIdentifier) return;
     setIsAddingComment(true);
     const result = await api.addLinearIssueComment(currentIssueIdentifier, comment);
     setIsAddingComment(false);
-    if (!result.success) return;
+    if (!result.success) {
+      reportPersistentErrorToast(
+        result.error || "Failed to add comment",
+        "Comment failed",
+        { scope: "linear:add-comment" }
+      );
+      return;
+    }
     setNewComment("");
     if (newCommentTextareaRef.current) {
       newCommentTextareaRef.current.style.height = "auto";
     }
     await refetch();
   };

Also applies to: 372-372, 420-420, 443-443, 456-456, 755-755

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

In `@apps/web-app/src/components/detail/LinearDetailPanel.tsx` at line 361, The
handlers in LinearDetailPanel (e.g., handleAddComment and the
status/priority/comment/description handlers) currently short-circuit on
failures with "if (!result.success) return;" (and some silent catch blocks);
replace these silent failures with user-facing toast error notifications: when
result.success is false, call the existing toast/error utility to show a
descriptive message including result.error or a sensible default, and in catch
blocks do the same instead of swallowing errors; ensure you update all affected
methods referenced in the comment (the handlers at the indicated locations) so
every failed async operation surfaces a toast with context (e.g., "Failed to add
comment" / "Failed to update status") and the underlying error text when
available.

Comment thread libs/shared/src/git.ts Resolved
@fum4
fum4 merged commit 804a6bf into master Mar 24, 2026
23 checks passed
@fum4
fum4 deleted the fix/placeholder-flicker branch March 24, 2026 14:24

This branch was previously deployed

1 inactive deployment
Preview — b05f48bd Deployed Mar 24, 2026 by vercel[bot]
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.

1 participant