Skip to content

various improvements - #95

Merged
fum4 merged 19 commits into
masterfrom
fix/various-2
Mar 23, 2026
Merged

fum4 merged 19 commits into
masterfrom
fix/various-2

Conversation

@fum4

@fum4 fum4 commented Mar 22, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Desktop app detects installed AI agent CLIs.
    • View full merged-PR diffs and per-file base/merge content.
    • "Move to worktree" action to create worktrees from root changes.
    • Stage/unstage controls and staged/unstaged sidebar with stage-all.
  • Improvements

    • Optional “push after commit” flow and updated commit button labels.
    • Per-worktree cleanup settings with UI toggles; root shown distinctly.
    • Richer error toasts (title/description) and improved logs empty state.
  • Tests

    • Added unit tests covering git diff, PR-diff, and staging behavior.
  • Documentation

    • Electron API and merged-PR/staging/cleanup design docs updated.

@fum4 fum4 self-assigned this Mar 22, 2026
@vercel

vercel Bot commented Mar 22, 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 23, 2026 8:50pm

@coderabbitai

coderabbitai Bot commented Mar 22, 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 Electron agent-CLI discovery, per-worktree settings and move-to-worktree workflow, merged-PR diff support via the GitHub CLI (server + frontend), staged/unstaged diff and staging endpoints/UI, assorted UI/UX tweaks, many tests, and documentation updates.

Changes

Cohort / File(s) Summary
Agent Discovery (Electron)
apps/desktop-app/src/main.ts, apps/desktop-app/src/preload.cjs, apps/desktop-app/src/preload.ts, apps/web-app/src/env.d.ts, docs/ELECTRON.md
Added IPC handler get-installed-agents (uses isCommandOnPath) and exposed electronAPI.getInstalledAgents() to renderer; documented API.
Worktree Settings & Auto-Cleanup
apps/server/src/worktree-settings.ts, libs/shared/src/worktree-types.ts, apps/server/src/manager.ts, apps/server/src/__test__/auto-cleanup.test.ts
New per-worktree settings storage API (loadWorktreeSettings, updateWorktreeSettings, deleteWorktreeSettings), WorktreeManager now consults per-worktree overrides when handling PR state, and tests updated/mocked accordingly.
Move-to-Worktree Backend & Route
apps/server/src/manager.ts, apps/server/src/routes/worktrees.ts
Added WorktreeManager.moveToWorktree() (unpushed/uncommitted checks, stash/create/reset/restore logic) and POST /api/worktrees/move-from-root route.
Move-to-Worktree Frontend
apps/web-app/src/components/detail/DetailHeader.tsx, apps/web-app/src/components/detail/DetailPanel.tsx, apps/web-app/src/hooks/api.ts, apps/web-app/src/hooks/useApi.ts
UI + modal for Move-to-worktree; API hook moveToWorktree, bound hook method, branch derivation UI, push-after-commit option, and humanized error toast titles.
Merged PR Diff Backend (GitHub)
libs/integrations/src/github/pr-diff.ts, libs/integrations/src/github/git-diff.ts, libs/integrations/src/github/github-manager.ts, libs/integrations/src/github/index.ts, apps/server/src/routes/github.ts
New pr-diff integration (exec gh), exported getPrDiffFiles/getPrFileContent, enhanced git numstat/rename parsing, GitHubManager.getRepoConfig(), and server endpoints to expose PR diff metadata and per-file contents.
Merged PR Diff Frontend
apps/web-app/src/components/detail/DiffViewerTab.tsx, apps/web-app/src/components/detail/DiffFileSection.tsx, apps/web-app/src/components/detail/__test__/DiffViewerTab.test.tsx, apps/web-app/src/hooks/api.ts
Detect merged PR state, add "Show merged" mode, use react-query for PR diffs, inject PR fetcher into file sections, add PR-diff API hooks, and tests for merged behavior.
Staged/Unstaged Diff + Staging Endpoints & UI
libs/integrations/src/github/git-diff.ts, apps/server/src/routes/github.ts, apps/web-app/src/components/detail/DiffFileSidebar.tsx, apps/web-app/src/components/detail/DiffFileSection.tsx, apps/web-app/src/components/detail/DiffFileSidebar.test.tsx, apps/web-app/src/hooks/api.ts, docs/superpowers/plans/...
Split getChangedFiles into staged vs unstaged diffs (add staged flag), updated getFileContent to read index when staged, added /stage, /unstage, /stage-all endpoints and corresponding frontend hooks, updated sidebar and file-section to show staging controls and tests.
Worktree Listing & Types / Root Worktree
apps/web-app/src/components/WorktreeItem.tsx, apps/web-app/src/components/WorktreeList.tsx, apps/web-app/src/types.ts, libs/shared/src/worktree-types.ts
Introduce ROOT_WORKTREE_ID and WorktreeInfo.isRoot, prepend synthetic root worktree in listings, render root separately and exclude it from child filtering.
Project Manager Lifecycle
apps/desktop-app/src/project-manager.ts
Reordered close flows to call notifyChange() before stopping/killing project.serverProcess in both persisted and non-persisted close paths.
Error Toasts & Activity UI
apps/web-app/src/errorToasts.tsx, apps/web-app/src/App.tsx, apps/web-app/src/components/ActivityPage.tsx
Extended error toast detail with optional title and description; prefer detail.title for toast message and render title/description in activity logs.
Logs UI Update
apps/web-app/src/components/detail/LogsViewer.tsx
Replaced empty logs placeholder with a terminal icon, title, and caption layout.
Tests
apps/server/src/__test__/git-diff.test.ts, apps/server/src/__test__/pr-diff.test.ts, apps/web-app/src/components/detail/__test__/DiffViewerTab.test.tsx, apps/web-app/src/components/__test__/CreateCustomTaskModal.test.tsx, other tests
Added/extended tests covering staged vs unstaged diffs, brace-style rename parsing, PR-diff helpers and file-content handling, merged-diff UI behavior, per-worktree settings, and UI label updates (Create Issue).
Integrations Exports & Shared Types
libs/integrations/src/github/index.ts, libs/shared/src/worktree-types.ts, apps/web-app/src/types.ts
Re-exported PR-diff helpers, added ROOT_WORKTREE_ID, WorktreeInfo.isRoot?, DiffFileInfo.staged?, PrDiffListResponse, and WorktreeSettings types.
Docs & Minor UX/Config
docs/ELECTRON.md, docs/superpowers/*, AGENTS.md, CLAUDE.md, apps/e2e/.oxlintrc.json
Documented new Electron API and merged-PR/worktree plans/specs; updated AGENTS/CLAUDE tooltip guidance; added e2e ESLint override and a range of design/plan docs.

Sequence Diagrams

sequenceDiagram
    participant User as User
    participant Renderer as Electron Renderer
    participant Server as Backend Server
    participant Git as Local Git

    User->>Renderer: Click "Move to Worktree"
    Renderer->>Renderer: Open branch modal
    Renderer->>Server: POST /api/worktrees/move-from-root (branch, name)
    Server->>Git: git rev-list / git status (unpushed/uncommitted checks)
    alt uncommitted present
        Server->>Git: git stash push --include-untracked
    end
    Server->>Server: createWorktree(request)
    alt create succeeded
        opt had unpushed
            Server->>Git: git reset --hard HEAD~N
        end
        opt stash captured
            Server->>Server: register onSuccess to apply stash in new worktree
        end
        Server->>Renderer: 201 { success: true, worktree }
    else create failed
        Server->>Git: git stash apply (attempt restore, best-effort)
        Server->>Renderer: 400 { success: false, error }
    end
Loading
sequenceDiagram
    participant User as User
    participant Renderer as Web Renderer
    participant Server as Backend Server
    participant GitHub as GitHub (gh CLI)

    User->>Renderer: Toggle "Show merged" PR diff
    Renderer->>Server: GET /api/worktrees/:id/pr-diff
    Server->>GitHub: gh api pull/{pr} (fetch baseSha, mergeSha, headSha)
    GitHub->>Server: PR metadata
    Server->>GitHub: gh api repos/.../pulls/{pr}/files?per_page=100
    GitHub->>Server: Files list (patch, status, changes)
    Server->>Server: git rev-parse HEAD (localHeadSha, non-fatal)
    Server->>Renderer: 200 { files, baseSha, mergeSha, headSha, localHeadSha }
    User->>Renderer: Expand file
    Renderer->>Server: GET /api/worktrees/:id/pr-diff/file?path=...&baseSha=...&mergeSha=...
    Server->>GitHub: gh api repos/.../contents/{path}?ref=baseSha
    GitHub->>Server: base content (base64)
    Server->>GitHub: gh api repos/.../contents/{path}?ref=mergeSha
    GitHub->>Server: merge content (base64)
    Server->>Renderer: Decoded old/new content
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I sniff the PATH for agents, one hop then two,
I stash a small bundle and leap to a branch made new.
Merged diffs glow like moonbeams fetched by a tiny CLI,
The root gets a crown while child trees stand tidy and spry.
Hooray — a rabbit's nudge: worktrees move and errors speak true.

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.75% 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 "various improvements" is overly vague and generic, failing to convey meaningful information about the substantial changes in this pull request. Consider a more descriptive title that captures the main feature or theme, such as "Add merged PR diff view, worktree auto-cleanup, and staging UI" or a similar summary of the primary change.
✅ 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/various-2

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

@github-actions

github-actions Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude Review

🔴 Major

  1. Stage/unstage endpoints pass unsanitized file paths to git add/git restore (apps/server/src/routes/github.ts:393-443). The paths array from the request body is spread directly into execFile args (["add", "--", ...paths]). While execFile avoids shell injection and -- prevents flag injection, paths containing null bytes or path traversal (e.g., ../../.env) could allow staging/unstaging files outside the worktree. Add validation that paths don't contain null bytes and are relative (no .. components).

  2. moveToWorktree uses fire-and-forget git reset --hard (apps/server/src/manager.ts:1440-1458). The onSuccess callback fires execFile("git", ["reset", "--hard", ...]) without awaiting the result. If this fails, the root branch is in an unknown state while the user sees a success response. The .catch logs the error but the user has no idea the root wasn't reset. Additionally, if origin/{baseBranch} doesn't exist or is stale, unpushedCount could be wrong and git reset --hard HEAD~N could destroy commits.

🟠 Medium

  1. get-installed-agents IPC handler is synchronous and blocking (apps/desktop-app/src/main.ts:431-438). isCommandOnPath likely uses synchronous shell lookups. Running 4 synchronous checks in the Electron main process blocks the UI thread. Consider using ipcMain.handle with async checks or offloading to a worker.

  2. PR files pagination limited to 100 (libs/integrations/src/github/pr-diff.ts:148). There's a log warning when files.length >= 100 (line 166-172), but files beyond 100 are still silently dropped. Consider implementing pagination or documenting this limitation more prominently to users.

  3. DiffFileSection changed from <button> to <div role="button"> (apps/web-app/src/components/detail/DiffFileSection.tsx:119). The custom keyboard handler only handles Enter and Space, but native <button> also handles form submission, focus management, and assistive technology hints automatically. The same pattern is used in DiffFileSidebar.tsx:261 (FileRow) and DiffFileSidebar.tsx:197 (SectionHeader). Unless there's a specific reason (e.g., nested buttons for stage/unstage), prefer keeping <button> for accessibility.

  4. moveToWorktree endpoint has no input sanitization on branch name (apps/server/src/routes/worktrees.ts:428). The branch name from body.branch is passed to git stash push -m "openkit-move-to-${request.branch}" in manager.ts:1395. Special characters in the branch name could cause issues with the stash message.

  5. 3-second polling interval in DiffViewerTab (apps/web-app/src/components/detail/DiffViewerTab.tsx:168). setInterval(fetchFiles, 3000) re-fetches the full diff every 3 seconds. The diff-change detection (filesChanged check at line 127-137) mitigates unnecessary re-renders, which is good. However, this still runs git diff --cached, git diff, and git ls-files every 3s even when nothing changes. Consider using SSE events or a longer interval with manual refresh.

  6. showMergedDiff not auto-enabled for merged worktrees with no uncommitted changes (apps/web-app/src/components/detail/DiffViewerTab.tsx). showMergedDiff starts as false for merged worktrees, meaning users always see the (likely empty) local diff first and must manually toggle. Consider auto-enabling showMergedDiff for merged worktrees with no uncommitted changes, since the local diff is typically empty post-merge.

  7. stageAllFiles / unstageAllFiles don't send a Content-Type header (apps/web-app/src/hooks/api.ts:4264,4284). The POST has no body and no Content-Type: application/json header. Minor since the Hono server handles it fine, but inconsistent with other endpoints.

🟡 Minor

  1. humanizeMethodName in useApi.ts (apps/web-app/src/hooks/useApi.ts:28-31). The regex ([a-z])([A-Z]) won't handle consecutive uppercase (e.g., fetchPRDiff → "Fetch p r diff"). Consider handling acronyms.

  2. Plan/spec files included in PR (docs/superpowers/plans/, docs/superpowers/specs/). Six large plan/spec files (~5000+ lines total) are included. These are implementation artifacts — verify they should be committed.

  3. Test file pr-diff.test.ts uses btoa (apps/server/src/__test__/pr-diff.test.ts:201). Buffer.from(...).toString('base64') would be more idiomatic for server-side Node tests.

  4. Duplicated staged/unstaged section headers — The collapsible section headers ("Staged Changes", "Changes") are implemented in both DiffFileSidebar.tsx and DiffViewerTab.tsx with nearly identical markup. Consider extracting a shared component or having only one source for section rendering.

  5. worktree-settings.test.ts imports fs functions but the mock order is fragile — The file imports log from ../logger (line 3) while also mocking it (line 17-24). The mock must be hoisted above the import. This works in vitest due to hoisting, but the pattern is fragile — consider importing log lazily or verifying mock order.

  6. Empty catch block in moveToWorktree (apps/server/src/manager.ts:1420-1422). The preResetHead capture has an empty catch with just a comment. Per CLAUDE.md error handling rules, this should at minimum log a debug/warn message.

🟢 Resolved

  • Pre-reset HEAD SHA is now recorded before git reset --hard (previously issue build(deps): bump actions/checkout from 4 to 6 #1, partially). manager.ts:1350-1358 logs the pre-reset HEAD SHA with metadata, enabling recovery.

  • Stash race condition fixed with ref-based apply (previously issue build(deps): bump actions/setup-node from 4 to 6 #2). moveToWorktree captures the stash ref via git stash list --max-count=1 --format=%H after creation (manager.ts:1325-1333) and uses git stash apply <ref> instead of git stash pop (manager.ts:1395).

  • getPrFileContent no longer silently returns success: true on non-size errors (previously issue build(deps): bump astro from 5.17.2 to 5.17.3 in /website #3). The old content fetch path now returns { success: false, ... } for non-size-related errors (pr-diff.ts:233-240).

  • Empty catch blocks in moveToWorktree now log warnings (previously issue build(deps): bump react from 19.1.0 to 19.2.4 in /apps/mobile-app #8). Both the unpushed count check (manager.ts:1283-1286) and uncommitted changes check (manager.ts:1296-1299) now use log.warn with domain and error metadata.

  • ROOT_WORKTREE_ID duplication fixed (previously issue build(deps): bump react-native-screens from 4.16.0 to 4.24.0 #11). apps/web-app/src/types.ts:1 now re-exports from @openkit/shared/worktree-types instead of redefining.

  • notifyChange() moved before stopServer() (previously issue build(deps): bump react-native from 0.81.5 to 0.84.0 in /apps/mobile-app #6). Both closeProject and forgetProject in project-manager.ts now notify the renderer before killing the server, with clear comments explaining the rationale.

  • Stash pop error handling improved (previously partially resolved). The worktree creation failure path now uses git stash apply <ref> with proper error logging (manager.ts:1341-1347).

  • PR diff endpoint returns headSha (previously resolved, still holds).

  • DiffFileSection removed loading state (previously resolved, still holds).

  • DiffViewerTab resets showMergedDiff when switching worktrees (previously resolved, still holds — line 155-163).

  • title attribute removed from diff status label (DiffFileSection.tsx:134). The title={file.status} was removed from the status span, consistent with CLAUDE.md's tooltip policy.

  • pushAfterCommit now uses ToggleSwitch component (previously issue build(deps): bump react-native-screens from 4.16.0 to 4.24.0 #11). The toggle in DetailPanel.tsx:2112-2122 uses the shared ToggleSwitch component, consistent with CLAUDE.md guidelines.

  • PrDiffListResponse has localHeadSha included directly (previously issue build(deps): bump react-native from 0.81.5 to 0.84.0 in /apps/mobile-app #6 about fragile type split). The type now includes localHeadSha in the shared definition, and getPrDiffFiles returns Omit<PrDiffListResponse, "localHeadSha"> explicitly, making the server-side reconstruction clear.

  • DiffFileSection test updated (DiffFileSection.test.tsx:66). Changed from getByTitle("modified") to getByText("M"), removing the title attribute query per CLAUDE.md guidelines.

  • notifyChange() before stopServer() race condition (previously issue build(deps): bump node-pty from 1.2.0-beta.10 to 1.2.0-beta.11 in /apps/server #7). The code now has clear comments explaining the rationale and consistent ordering in both closeProject and forgetProject.

  • DiffViewerTab polling no longer triggers unnecessary re-renders (previously issue build(deps): bump react-native-screens from 4.16.0 to 4.24.0 in /apps/mobile-app #9, partially). The filesChanged check at line 127-137 compares file properties before updating state, preventing Monaco editor flickering. Loading spinner is only shown on first fetch.

  • Global auto-cleanup labels updated (ConfigurationPanel.tsx:713-739). Labels now read "Delete worktrees on PR merge/close" (plural) instead of "Auto-delete on PR merge/close", which is clearer.

  • Empty catch in github.ts for localHeadSha (previously issue build(deps): bump node-pty from 1.2.0-beta.10 to 1.2.0-beta.11 in /apps/cli #5). The empty catch now logs via log.warn with domain and error context (github.ts:583-587).

  • title attributes removed from DetailHeader.tsx (previously issue build(deps): bump react-native from 0.81.5 to 0.84.0 #14). The "Move to worktree" and "Delete worktree" buttons now use the shared Tooltip component instead of title attributes.

  • worktree-settings.test.ts imports vitest globals explicitly (previously issue chore: update readme #15). The file now has import { beforeEach, describe, expect, it, vi } from "vitest" on line 1.

  • pushAfterCommit toggle label logic is a nested ternary (previously issue build(deps): bump react from 19.1.0 to 19.2.4 in /apps/mobile-app #8 about readability). The button label now uses three separate conditional expressions (DetailPanel.tsx:2143-2146), which is clearer than the nested ternary.

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

Caution

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

⚠️ Outside diff range comments (2)
apps/desktop-app/src/project-manager.ts (1)

1-1: 🛠️ Refactor suggestion | 🟠 Major

Add the required file-level JSDoc header.

This TS source file is missing the mandatory top-of-file JSDoc describing its responsibility.

✍️ Proposed fix
+/**
+ * Manages desktop project lifecycle: opening/restoring projects, allocating ports,
+ * spawning/stopping per-project servers, and notifying renderer state changes.
+ */
 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";

As per coding guidelines, **/*.{ts,tsx,js,jsx,mjs,cjs}: Every source file must have a JSDoc comment at the top explaining what the file is for (1-3 sentences). Update JSDoc when changing a file's responsibility.

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

In `@apps/desktop-app/src/project-manager.ts` at line 1, This file is missing the
required top-of-file JSDoc; add a brief 1–3 sentence /** ... */ JSDoc comment at
the very top of apps/desktop-app/src/project-manager.ts that succinctly
describes the module's responsibility (e.g., managing project directories,
reading/writing project metadata) and update it whenever the file's
responsibility changes so it follows the repository's source-file documentation
guideline.
apps/web-app/src/hooks/api.ts (1)

1-37: ⚠️ Potential issue | 🟡 Minor

Add the required file-level JSDoc header

This file still starts without a top JSDoc block. A 1–3 sentence header is required at the top of every TS/JS source file (Line 1 onward).

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

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

In `@apps/web-app/src/hooks/api.ts` around lines 1 - 37, Add a 1–3 sentence
file-level JSDoc comment at the very top of the file (above the existing import
block) that briefly describes the purpose of this module — e.g., that it defines
API hook utilities for calling backend endpoints (accepting an optional
serverUrl for relative vs full URLs) and lists the main responsibilities such as
types imported like JiraIssueDetail, LinearIssueSummary, and PrDiffListResponse
to help future maintainers; ensure the JSDoc follows project style and is
updated if the file’s responsibility changes.
🧹 Nitpick comments (5)
apps/web-app/src/components/detail/LogsViewer.tsx (1)

88-95: Use theme tokens instead of hardcoded color values.

The empty state uses hardcoded hex colors (#4b5563, #6b7280) instead of the shared color palette from theme.ts. The file already imports text tokens on line 6.

♻️ Suggested refactor using theme tokens
-      <div className="h-full w-full min-h-0 rounded-t-lg rounded-b-md bg-black overflow-hidden px-2 flex flex-col items-center justify-center gap-1.5">
-        <Terminal className="w-7 h-7 text-[`#4b5563`] mb-3" strokeWidth={1.5} />
-        <span className="text-[13px] font-medium tracking-[-0.01em] text-[`#6b7280`]">
+      <div className="h-full w-full min-h-0 rounded-t-lg rounded-b-md bg-black overflow-hidden px-2 flex flex-col items-center justify-center gap-1.5">
+        <Terminal className={`w-7 h-7 ${text.muted} mb-3`} strokeWidth={1.5} />
+        <span className={`text-[13px] font-medium tracking-[-0.01em] ${text.dimmed}`}>
           No logs yet
         </span>
-        <span className="text-[11px] text-[`#4b5563`] max-w-[240px] text-center leading-relaxed">
+        <span className={`text-[11px] ${text.muted} max-w-[240px] text-center leading-relaxed`}>
           Start the worktree to see dev server output
         </span>

As per coding guidelines: "Always use the standard shared color palette and tokens from apps/web-app/src/theme.ts; do not introduce ad-hoc lighter/darker variants."

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

In `@apps/web-app/src/components/detail/LogsViewer.tsx` around lines 88 - 95, The
empty-state UI in LogsViewer.tsx uses hardcoded hex colors (`#4b5563`, `#6b7280`) in
the Terminal icon and the two <span> elements; replace those hardcoded values
with the shared theme tokens already imported (e.g., use the imported text token
names from theme.ts) so the Terminal className and the two spans reference the
appropriate theme color tokens instead of literal hex values; update the
className strings for the Terminal and the two spans to use the token names
(keep the rest of the markup/layout unchanged).
apps/server/src/routes/worktrees.ts (1)

426-445: LGTM! The endpoint follows established patterns.

The new move-from-root endpoint correctly:

  • Validates required branch parameter
  • Delegates to manager.moveToWorktree(body)
  • Uses consistent error handling and HTTP status codes

Consider adding structured logging similar to the delete endpoint (lines 547-555) for operational visibility into move operations — this would help with debugging and audit trails.

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

In `@apps/server/src/routes/worktrees.ts` around lines 426 - 445, Add structured
operational logging to the new app.post("/api/worktrees/move-from-root")
handler: instrument the route to log incoming request details and the result of
manager.moveToWorktree(body) (including branch and success/failure and
error.message) using the same logger and format used in the delete endpoint (see
the delete endpoint logging block) so move operations are auditable and failures
include context for debugging.
apps/web-app/src/types.ts (1)

1-2: Duplicate constant definition — prefer re-exporting from shared.

ROOT_WORKTREE_ID is already defined in libs/shared/src/worktree-types.ts (line 75). Defining it again here creates a maintenance risk if the values diverge. Consider re-exporting it alongside the other diff viewer types:

♻️ Suggested fix
-/** Sentinel ID used for the root project entry in the worktree list. */
-export const ROOT_WORKTREE_ID = "root";
-
 export interface WorktreeInfo {

Then add to the re-exports at line 354-359:

 export type {
   DiffFileInfo,
   DiffListResponse,
   DiffFileContentResponse,
   PrDiffListResponse,
 } from "@openkit/shared/worktree-types";
+
+export { ROOT_WORKTREE_ID } from "@openkit/shared/worktree-types";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/types.ts` around lines 1 - 2, Remove the duplicate
ROOT_WORKTREE_ID constant from this module and instead re-export the existing
constant from the shared definition (the one in worktree-types where
ROOT_WORKTREE_ID is originally declared); update this module's exports (the diff
viewer re-exports group) to include ROOT_WORKTREE_ID so callers import it from
here without redefining it locally, ensuring all references use the re-exported
ROOT_WORKTREE_ID symbol.
docs/superpowers/plans/2026-03-20-merged-pr-diff-view.md (1)

1039-1082: Minor discrepancy between plan and implementation — consider updating.

The plan mentions setLoading(true/false) calls in DiffFileSection.tsx, but the actual implementation removed the loading state and simplified the approach (using only fetchingRef for gating). This is fine — the implementation is cleaner. Consider updating the plan to match the actual implementation for accuracy.

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

In `@docs/superpowers/plans/2026-03-20-merged-pr-diff-view.md` around lines 1039 -
1082, The plan text is out of date: the implementation in DiffFileSection.tsx's
doFetch now uses fetchingRef for gating and retains setLoading/setError calls
but the plan claims loading state was removed; update the plan to reflect the
current implementation by noting doFetch uses fetchingRef.current to prevent
duplicate fetches, calls fetchContentRef.current or fetchDiffFileContent(...),
and still calls setLoading(true)/setLoading(false) and setError as shown
(references: doFetch, fetchingRef, fetchContentRef, fetchDiffFileContent,
setLoading, setError, setContent) so the plan accurately describes the actual
behavior.
apps/web-app/src/components/detail/DetailPanel.tsx (1)

2091-2108: Reuse ToggleSwitch for “Push after commit”.

This bespoke switch duplicates a shared control the app already uses elsewhere, which makes styling and accessibility behavior easier to drift over time.

As per coding guidelines, "For switches/toggles, reuse the app-standard treatment (bg-accent when enabled, neutral off-state styling when disabled)."

🤖 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 2091 - 2108,
Replace the custom button/span switch in DetailPanel with the shared
ToggleSwitch component: remove the bespoke markup around pushAfterCommit and
instead render <ToggleSwitch checked={pushAfterCommit} onChange={() =>
setPushAfterCommit(v => !v)} label="Push after commit" /> (or the app's
ToggleSwitch props shape) ensuring aria-checked/role behavior is preserved and
the ToggleSwitch uses the app-standard enabled (bg-accent) and neutral off-state
styling; update any imports to include ToggleSwitch and keep state variables
pushAfterCommit and setPushAfterCommit unchanged.
🤖 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/__test__/pr-diff.test.ts`:
- Around line 54-58: The test mock metadata omits head_sha so it won't catch
regressions; update the BASE_META JSON in pr-diff.test.ts (the BASE_META
constant) to include a head_sha field (e.g., "head_sha": "ghi789") and add an
assertion in the happy-path test that the parsed metadata/response includes the
expected headSha value (reference head_sha/headSha) so DiffViewerTab's reliance
on headSha is validated; apply the same change to the other mock metadata used
later in the file that mirrors BASE_META.

In `@apps/server/src/manager.ts`:
- Around line 668-675: The root WorktreeInfo uses
getWorktreeBranch(this.configDir) which only handles worktree-style .git files,
causing the root entry to fall back to this.config.baseBranch; update the root
branch detection for the root entry (where id is ROOT_WORKTREE_ID and path is
this.configDir) to handle a normal repo .git directory by checking the actual
checked-out branch (e.g., read HEAD or run a git symbolic-ref/abbrev-ref on
rootPath) and use that value when present, otherwise fall back to
this.config.baseBranch; keep getWorktreeBranch for worktree cases and only use
the repo-HEAD check when .git is a directory.
- Around line 1333-1378: moveToWorktree() currently resets the root branch
immediately after createWorktree() returns (which only queues async creation),
risking history rewrite before the new worktree exists; instead, defer the hard
reset and any stash restoration until the worktree creation is confirmed in the
async success callback. Concretely: in the moveToWorktree flow, remove the
immediate git reset --hard block and any stash restore tied to that path; use
the worktreeId from result.worktree?.id and attach logic to
this.worktreeCallbacks.set(worktreeId, ...) (or extend existing onSuccess) to
run the git reset --hard `HEAD~${unpushedCount}` against the original gitRoot
and to handle stash pop/restore only after the worktree is successfully added
(using getWorktreesAbsolutePath() to locate the new worktree for stash pop and
ensure errors are logged via log.error). Ensure createWorktree,
worktreeCallbacks, worktreeId, and getWorktreesAbsolutePath are the anchors for
the change so the root history is only rewritten once the destination worktree
actually exists.

In `@apps/server/src/routes/github.ts`:
- Around line 498-546: Validate the status query before casting and calling
getPrFileContent: check the value of the status variable (from
c.req.query("status")) against the allowed set
("modified","added","deleted","renamed","untracked") and if it is
missing/invalid return the same JSON error shape with a 400 status instead of
casting to the union; update the code path around the status variable and the
call to getPrFileContent to use the validated value so no incorrect/unknown
status is passed through.

In `@apps/web-app/src/components/ActivityPage.tsx`:
- Around line 486-498: The code is unsafely casting event.metadata?.title and
.description to string; change to runtime-guarded reads in ActivityPage (where
title and description are defined) by checking typeof event.metadata?.title ===
"string" and typeof event.metadata?.description === "string" and only assign
those to title/description when they pass, otherwise leave undefined or use a
safe fallback; update the conditional that renders the title/description to rely
on these guarded values (and keep using event.message as the fallback).

In `@apps/web-app/src/components/detail/DetailHeader.tsx`:
- Around line 306-328: The Move to worktree button currently only enables when
worktree.hasUncommitted is true; update the disabled prop on the button (inside
DetailHeader's JSX around the isRoot branch and onClick={onMoveToWorktree}) to
use disabled={isLoading || (!worktree.hasUncommitted && !worktree.hasUnpushed)}
so it is enabled when there are uncommitted OR unpushed changes, and change the
title attribute from "Move uncommitted changes to a new worktree" to a phrase
that mentions both "uncommitted changes and unpushed commits" to match the
moveToWorktree behavior and modal copy.

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 1219-1243: Wrap the async IIFE inside the useEffect in a try/catch
so any rejection from window.electronAPI.getInstalledAgents or
api.fetchAgentCliStatus is caught; on error call the app logger (e.g., log.error
or log.warn) and reset installedAgents via setInstalledAgents(new Set()) (or
null/empty) to avoid stale state; also ensure the early branch when !serverUrl
clears previous value by calling setInstalledAgents(new Set()) before returning.
Target the async block inside useEffect and the calls to
window.electronAPI.getInstalledAgents, api.fetchAgentCliStatus, and
setInstalledAgents for these changes.

In `@apps/web-app/src/components/detail/DiffViewerTab.tsx`:
- Around line 67-72: The query is over-cached because useQuery's key only uses
worktree.id while fetchPrDiffFiles depends on serverUrl and the response
includes mutable localHeadSha; update the queryKey for prDiffQuery to include
serverUrl and the current localHeadSha (e.g., ["pr-diff", worktree.id,
serverUrl, localHeadSha]) so caching is scoped correctly to server and local
state, and remove or avoid staleTime: Infinity (use a sensible TTL or let React
Query default) so hasPostMergeCommits reflects new local commits without
requiring the view to be recreated; keep the enabled condition (isMerged &&
visible) and continue calling fetchPrDiffFiles(worktree.id, serverUrl) in
queryFn.
- Around line 213-215: The refresh handler always calls fetchFiles(), which in
merged mode overwrites the merged PR diff; update handleRefresh to detect
showMergedDiff: if showMergedDiff is true, call the merged-diff refetch path
(e.g. prDiffQuery.refetch() or the existing fetchMergedPrDiff/fetchMergedFiles
helper) so the merged PR data is re-fetched, otherwise call fetchFiles(); ensure
the dependency array still includes any refetch function you use (e.g.
prDiffQuery.refetch or fetchMergedPrDiff) and keep the handler name
handleRefresh unchanged.

In `@apps/web-app/src/errorToasts.tsx`:
- Around line 23-27: Add a clear schema entry for the OpenKit:error-toast custom
event to docs/NOTIFICATIONS.md: document the EventDetail shape using the
ErrorToastEventDetail fields (message: string, optional title?: string, optional
description?: string, optional scope?: string), show example JSON payload and
note which fields are required vs optional, and reference the event name
"OpenKit:error-toast" and where consumers should listen for it.

In `@apps/web-app/src/hooks/api.ts`:
- Around line 122-127: The catch blocks that currently only return an error
object (e.g., the catch using "err" that returns { success: false, error: ... })
must also log or surface the error; update the three catch sites (the one shown
and the ones at the other reported locations) to call log.error(...) with the
error (or call a UI toast helper) before returning, ensuring you pass the actual
error object/message (err or err.message) and include contextual text so the
logs show where the failure occurred (e.g., "Failed to move to worktree:" +
err).

In `@docs/superpowers/plans/2026-03-20-worktree-auto-cleanup.md`:
- Around line 583-664: The step numbering in the plan is inconsistent; renumber
the checklist so steps progress sequentially (e.g., make "Add the auto-cleanup
handler method" Step 3, "Wire the callback into initGitHub()" Step 4, and "Run
tests..." Step 5) and update any in-text references accordingly; ensure the
referenced symbols (handlePrStateChange, initGitHub,
this.githubManager.startPolling) remain correctly linked to their steps so
readers can follow the sequence without confusion.

In `@libs/integrations/src/github/pr-diff.ts`:
- Around line 210-239: The catch blocks that handle fetching file content
(checking errMsg and returning { success: true, oldContent: "", newContent: "",
error: "File too large to display" }) should only return success:true for the
specific size-related conditions; for all other errors (the non-403/"too
large"/"1 MB" cases) change the behavior in the catch blocks in pr-diff.ts to
return success:false and propagate the error message (use the existing errMsg)
instead of silently returning success:true, and ensure the caller sees the
failure by including the error field and preserving logging via log.error; apply
the same change to the analogous block around the later fetch (the second catch
covering lines 251-291) so non-size failures are surfaced consistently.
- Around line 119-125: The PR file listing currently only fetches a single page;
modify the logic around the execGh call (the code that produces filesOut and
ghFiles for owner/repo/prNumber) to paginate: add a page counter (starting at
1), call execGh in a loop with both per_page=100 and page=<page>, JSON.parse
each page's stdout and append results into a cumulative array (replace the
single ghFiles with this accumulator), and break the loop when the returned
batch length is less than 100; ensure you pass the page param to the same execGh
invocation and preserve existing trimming/json parsing per iteration.
- Around line 206-207: The GitHub contents API URLs interpolate raw fetchPath
and filePath which can contain unsafe characters; update the places building
`repos/${owner}/${repo}/contents/${fetchPath}?ref=${baseSha}` and the similar
`filePath` usage to percent-encode each path segment: split the path on '/', run
encodeURIComponent on each segment, then join with '/' so slashes are preserved,
and use that encoded string in the URL interpolation wherever `fetchPath` or
`filePath` are used.

---

Outside diff comments:
In `@apps/desktop-app/src/project-manager.ts`:
- Line 1: This file is missing the required top-of-file JSDoc; add a brief 1–3
sentence /** ... */ JSDoc comment at the very top of
apps/desktop-app/src/project-manager.ts that succinctly describes the module's
responsibility (e.g., managing project directories, reading/writing project
metadata) and update it whenever the file's responsibility changes so it follows
the repository's source-file documentation guideline.

In `@apps/web-app/src/hooks/api.ts`:
- Around line 1-37: Add a 1–3 sentence file-level JSDoc comment at the very top
of the file (above the existing import block) that briefly describes the purpose
of this module — e.g., that it defines API hook utilities for calling backend
endpoints (accepting an optional serverUrl for relative vs full URLs) and lists
the main responsibilities such as types imported like JiraIssueDetail,
LinearIssueSummary, and PrDiffListResponse to help future maintainers; ensure
the JSDoc follows project style and is updated if the file’s responsibility
changes.

---

Nitpick comments:
In `@apps/server/src/routes/worktrees.ts`:
- Around line 426-445: Add structured operational logging to the new
app.post("/api/worktrees/move-from-root") handler: instrument the route to log
incoming request details and the result of manager.moveToWorktree(body)
(including branch and success/failure and error.message) using the same logger
and format used in the delete endpoint (see the delete endpoint logging block)
so move operations are auditable and failures include context for debugging.

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 2091-2108: Replace the custom button/span switch in DetailPanel
with the shared ToggleSwitch component: remove the bespoke markup around
pushAfterCommit and instead render <ToggleSwitch checked={pushAfterCommit}
onChange={() => setPushAfterCommit(v => !v)} label="Push after commit" /> (or
the app's ToggleSwitch props shape) ensuring aria-checked/role behavior is
preserved and the ToggleSwitch uses the app-standard enabled (bg-accent) and
neutral off-state styling; update any imports to include ToggleSwitch and keep
state variables pushAfterCommit and setPushAfterCommit unchanged.

In `@apps/web-app/src/components/detail/LogsViewer.tsx`:
- Around line 88-95: The empty-state UI in LogsViewer.tsx uses hardcoded hex
colors (`#4b5563`, `#6b7280`) in the Terminal icon and the two <span> elements;
replace those hardcoded values with the shared theme tokens already imported
(e.g., use the imported text token names from theme.ts) so the Terminal
className and the two spans reference the appropriate theme color tokens instead
of literal hex values; update the className strings for the Terminal and the two
spans to use the token names (keep the rest of the markup/layout unchanged).

In `@apps/web-app/src/types.ts`:
- Around line 1-2: Remove the duplicate ROOT_WORKTREE_ID constant from this
module and instead re-export the existing constant from the shared definition
(the one in worktree-types where ROOT_WORKTREE_ID is originally declared);
update this module's exports (the diff viewer re-exports group) to include
ROOT_WORKTREE_ID so callers import it from here without redefining it locally,
ensuring all references use the re-exported ROOT_WORKTREE_ID symbol.

In `@docs/superpowers/plans/2026-03-20-merged-pr-diff-view.md`:
- Around line 1039-1082: The plan text is out of date: the implementation in
DiffFileSection.tsx's doFetch now uses fetchingRef for gating and retains
setLoading/setError calls but the plan claims loading state was removed; update
the plan to reflect the current implementation by noting doFetch uses
fetchingRef.current to prevent duplicate fetches, calls fetchContentRef.current
or fetchDiffFileContent(...), and still calls setLoading(true)/setLoading(false)
and setError as shown (references: doFetch, fetchingRef, fetchContentRef,
fetchDiffFileContent, setLoading, setError, setContent) so the plan accurately
describes the actual behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fb5f7a40-8af6-4262-9f4c-0b5af70aa4d0

📥 Commits

Reviewing files that changed from the base of the PR and between 36d7aae and 5178b15.

📒 Files selected for processing (35)
  • apps/desktop-app/src/main.ts
  • apps/desktop-app/src/preload.cjs
  • apps/desktop-app/src/preload.ts
  • apps/desktop-app/src/project-manager.ts
  • apps/e2e/src/fixtures.ts
  • apps/server/src/__test__/git-diff.test.ts
  • apps/server/src/__test__/pr-diff.test.ts
  • 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/ActivityPage.tsx
  • apps/web-app/src/components/WorktreeItem.tsx
  • apps/web-app/src/components/WorktreeList.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/DiffViewerTab.tsx
  • apps/web-app/src/components/detail/LogsViewer.tsx
  • apps/web-app/src/components/detail/__test__/DiffViewerTab.test.tsx
  • apps/web-app/src/env.d.ts
  • apps/web-app/src/errorToasts.tsx
  • apps/web-app/src/hooks/api.ts
  • apps/web-app/src/hooks/useApi.ts
  • apps/web-app/src/types.ts
  • docs/ELECTRON.md
  • docs/superpowers/plans/2026-03-20-merged-pr-diff-view.md
  • docs/superpowers/plans/2026-03-20-worktree-auto-cleanup.md
  • docs/superpowers/specs/2026-03-20-merged-pr-diff-view-design.md
  • docs/superpowers/specs/2026-03-20-worktree-auto-cleanup-design.md
  • libs/integrations/src/github/git-diff.ts
  • libs/integrations/src/github/github-manager.ts
  • libs/integrations/src/github/index.ts
  • libs/integrations/src/github/pr-diff.ts
  • libs/shared/src/worktree-types.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/web-app/src/hooks/api.ts Resolved
Comment on lines +583 to +664
- [ ] **Step 3: Add the auto-cleanup handler method**

In `apps/server/src/manager.ts`, add a new private method before `initGitHub()` (around line 435):

```typescript
private async handlePrStateChange(
worktreeId: string,
_oldState: string,
newState: string,
): Promise<void> {
const config = this.getConfig();

if (newState === "merged" && !config.autoCleanupOnPrMerge) return;
if (newState === "closed" && !config.autoCleanupOnPrClose) return;

// Safety gate: check for uncommitted or unpushed changes
const git = this.githubManager?.getCachedGitStatus(worktreeId);
if (git) {
const hasUnpushed = git.ahead > 0 || git.noUpstream;
if (git.hasUncommitted || hasUnpushed) {
log.info(`Auto-cleanup skipped for "${worktreeId}" — dirty state`, {
domain: "auto-cleanup",
worktreeId,
hasUncommitted: git.hasUncommitted,
hasUnpushed,
});
this.activityLog.addEvent({
category: "worktree",
type: ACTIVITY_TYPES.AUTO_CLEANUP_SKIPPED,
severity: "warning",
title: "Auto-cleanup skipped",
detail: `Worktree "${worktreeId}" has uncommitted/unpushed changes — skipped auto-cleanup (PR was ${newState})`,
worktreeId,
projectName: this.activityProjectName(),
});
return;
}
}

log.info(`Auto-cleaning worktree "${worktreeId}" — PR was ${newState}`, {
domain: "auto-cleanup",
worktreeId,
});

const result = await this.removeWorktree(worktreeId);

if (result.success) {
this.activityLog.addEvent({
category: "worktree",
type: ACTIVITY_TYPES.AUTO_CLEANUP,
severity: "info",
title: "Worktree auto-deleted",
detail: `Worktree "${worktreeId}" was auto-deleted — PR was ${newState}`,
worktreeId,
projectName: this.activityProjectName(),
});
} else {
log.warn(`Auto-cleanup failed for "${worktreeId}": ${result.error}`, {
domain: "auto-cleanup",
worktreeId,
error: result.error,
});
}
}
```

- [ ] **Step 2: Wire the callback into `initGitHub()`**

In `apps/server/src/manager.ts`, update `initGitHub()` (line 439-442) to pass the callback:

```typescript
this.githubManager.startPolling(
() => this.getWorktrees(),
() => this.notifyListeners(),
(worktreeId, oldState, newState) => this.handlePrStateChange(worktreeId, oldState, newState),
);
```

- [ ] **Step 5: Run tests to verify they pass**

Run: `pnpm nx run server:test -- --run -t "handlePrStateChange"`
Expected: PASS

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

Step numbering is inconsistent in Task 6.

The steps in Task 6 have incorrect numbering:

  • Line 583: "Step 3: Add the auto-cleanup handler method"
  • Line 649: "Step 2: Wire the callback into initGitHub()" (should be Step 4)
  • Line 661: "Step 5: Run test to verify it passes" (continues from wrong base)

This creates confusion when following the plan sequentially.

📝 Suggested fix
-- [ ] **Step 2: Wire the callback into `initGitHub()`**
+- [ ] **Step 4: Wire the callback into `initGitHub()`**
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/superpowers/plans/2026-03-20-worktree-auto-cleanup.md` around lines 583
- 664, The step numbering in the plan is inconsistent; renumber the checklist so
steps progress sequentially (e.g., make "Add the auto-cleanup handler method"
Step 3, "Wire the callback into initGitHub()" Step 4, and "Run tests..." Step 5)
and update any in-text references accordingly; ensure the referenced symbols
(handlePrStateChange, initGitHub, this.githubManager.startPolling) remain
correctly linked to their steps so readers can follow the sequence without
confusion.

Comment on lines +119 to +125
const { stdout: filesOut } = await execGh([
"api",
`repos/${owner}/${repo}/pulls/${prNumber}/files?per_page=100`,
]);

const ghFiles = JSON.parse(filesOut.trim()) as GitHubPRFile[];

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

🌐 Web query:

What are the pagination rules (default, max per_page, and paging mechanism) for GitHub REST endpoint GET /repos/{owner}/{repo}/pulls/{pull_number}/files?

💡 Result:

For GET /repos/{owner}/{repo}/pulls/{pull_number}/files:

  • Default page size (per_page): 30 files per page. Max per_page: 100. Default page: 1. [1]
  • Paging mechanism: Use query parameters ?per_page=…&page=…, and follow the HTTP Link response header URLs (with rel="next", rel="last", etc.) to traverse pages. [1][2]
  • Hard cap: responses include a maximum of 3000 files total (even with pagination). [1]

Sources: [1] GitHub Docs – “List pull requests files” (Pulls REST API) https://docs.github.com/ja/rest/pulls/pulls#list-pull-requests-files, [2] GitHub Docs – “Using pagination in the REST API” https://docs.github.com/v3/guides/traversing-with-pagination


🏁 Script executed:

# Check if file exists and get context around lines 119-125
fd -e ts "pr-diff.ts" | head -5

Repository: fum4/openkit

Length of output: 95


🏁 Script executed:

# Read the actual code around lines 119-125
sed -n '115,130p' libs/integrations/src/github/pr-diff.ts

Repository: fum4/openkit

Length of output: 525


Implement pagination for PR file listing

The current code fetches only a single page with per_page=100 (line 121), which truncates results for PRs with more than 100 changed files. GitHub's /repos/{owner}/{repo}/pulls/{pull_number}/files endpoint requires pagination using page query parameter and HTTP Link header to retrieve all files. Implement a loop that continues fetching pages until fewer than 100 files are returned in a batch.

♻️ Suggested pagination approach
-    const { stdout: filesOut } = await execGh([
-      "api",
-      `repos/${owner}/${repo}/pulls/${prNumber}/files?per_page=100`,
-    ]);
-
-    const ghFiles = JSON.parse(filesOut.trim()) as GitHubPRFile[];
+    const ghFiles: GitHubPRFile[] = [];
+    let page = 1;
+    while (true) {
+      const { stdout: filesOut } = await execGh([
+        "api",
+        `repos/${owner}/${repo}/pulls/${prNumber}/files?per_page=100&page=${page}`,
+      ]);
+      const batch = JSON.parse(filesOut.trim()) as GitHubPRFile[];
+      ghFiles.push(...batch);
+      if (batch.length < 100) break;
+      page += 1;
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { stdout: filesOut } = await execGh([
"api",
`repos/${owner}/${repo}/pulls/${prNumber}/files?per_page=100`,
]);
const ghFiles = JSON.parse(filesOut.trim()) as GitHubPRFile[];
const ghFiles: GitHubPRFile[] = [];
let page = 1;
while (true) {
const { stdout: filesOut } = await execGh([
"api",
`repos/${owner}/${repo}/pulls/${prNumber}/files?per_page=100&page=${page}`,
]);
const batch = JSON.parse(filesOut.trim()) as GitHubPRFile[];
ghFiles.push(...batch);
if (batch.length < 100) break;
page += 1;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/integrations/src/github/pr-diff.ts` around lines 119 - 125, The PR file
listing currently only fetches a single page; modify the logic around the execGh
call (the code that produces filesOut and ghFiles for owner/repo/prNumber) to
paginate: add a page counter (starting at 1), call execGh in a loop with both
per_page=100 and page=<page>, JSON.parse each page's stdout and append results
into a cumulative array (replace the single ghFiles with this accumulator), and
break the loop when the returned batch length is less than 100; ensure you pass
the page param to the same execGh invocation and preserve existing trimming/json
parsing per iteration.

Comment on lines +206 to +207
`repos/${owner}/${repo}/contents/${fetchPath}?ref=${baseSha}`,
]);

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

🧩 Analysis chain

🌐 Web query:

For GitHub REST contents endpoint GET /repos/{owner}/{repo}/contents/{path}, should {path} be URL-encoded, and how should slashes vs reserved characters be handled?

💡 Result:

Yes—treat {path} as a URL path component, so you should percent-encode characters that are not safe in a URL path, but do not percent-encode the / characters that separate directories, because GitHub’s contents endpoint is designed to accept multi-segment paths like notes/hello.txt as actual path hierarchy. This is shown in GitHub’s own examples where nested paths are sent with literal slashes (e.g., .../contents/notes/hello.txt). [1]

How to handle characters:

  • Slashes (/)

    • Keep literal / to separate path segments (directories) for GET /repos/{owner}/{repo}/contents/{path}. Example: docs/README.md → docs/README.md.
    • Only encode a slash as %2F when a given endpoint expects a single path parameter value and a slash would otherwise be misread as a path separator (GitHub’s general REST troubleshooting guidance calls out encoding slashes in path parameter values to avoid misinterpretation). [2] For the contents {path}, those slashes are exactly how you express directories.
  • Reserved / unsafe characters inside a segment

    • Percent-encode them (UTF-8 then %HH), especially: space → %20, # → %23, ? → %3F, % → %25.
    • Practical rule: encode each path segment, then join with /.
      • Example: dir with space/file#1?.txt → dir%20with%20space/file%231%3F.txt.

Also: avoid double-encoding (e.g., don’t turn %20 into %2520). [2]

Sources: GitHub REST “Repository contents” examples (showing contents/notes/hello.txt) [1]; GitHub REST troubleshooting note that path parameters must be URL-encoded and that unencoded slashes can cause misinterpretation [2].


🏁 Script executed:

cat -n libs/integrations/src/github/pr-diff.ts | sed -n '200,215p'

Repository: fum4/openkit

Length of output: 867


🏁 Script executed:

cat -n libs/integrations/src/github/pr-diff.ts | sed -n '240,255p'

Repository: fum4/openkit

Length of output: 769


🏁 Script executed:

# Get context around these lines to understand the function
cat -n libs/integrations/src/github/pr-diff.ts | sed -n '195,260p'

Repository: fum4/openkit

Length of output: 2556


🏁 Script executed:

cat -n libs/integrations/src/github/pr-diff.ts | sed -n '160,200p'

Repository: fum4/openkit

Length of output: 1232


🏁 Script executed:

# Search for URL encoding utilities in the codebase
rg -i "encodeuri|urlencode|percent" --type ts --type tsx -B 2 -A 2 | head -40

Repository: fum4/openkit

Length of output: 83


🏁 Script executed:

# Check the beginning of the file to understand imports
head -50 libs/integrations/src/github/pr-diff.ts

Repository: fum4/openkit

Length of output: 1531


🏁 Script executed:

cat -n libs/integrations/src/github/pr-diff.ts | sed -n '90,160p'

Repository: fum4/openkit

Length of output: 2417


🏁 Script executed:

# Search for any URL encoding utilities being used elsewhere in the codebase
rg "encodeURIComponent|encodeURI|URL" --type js -A 2 -B 2 | head -50

Repository: fum4/openkit

Length of output: 38


🏁 Script executed:

# Check if there's any documentation or usage patterns with special characters
rg "execGh" libs/integrations/src/github/pr-diff.ts -B 2 -A 2

Repository: fum4/openkit

Length of output: 1013


🏁 Script executed:

# Check if there are any other API calls that encode paths
rg "repos.*contents" --type js -B 3 -A 3

Repository: fum4/openkit

Length of output: 38


🏁 Script executed:

# Look for encodeURIComponent usage in the entire codebase
rg "encodeURIComponent" --type js

Repository: fum4/openkit

Length of output: 38


🏁 Script executed:

# Check the gh CLI documentation or behavior regarding URL encoding
web_search "gh cli URL encoding path parameters api contents"

Repository: fum4/openkit

Length of output: 106


🏁 Script executed:

# Also check if there are any test files that might show expected behavior
find . -name "*.test.ts" -o -name "*.spec.ts" | xargs rg "pr-diff|getPrFileContent" 2>/dev/null | head -20

Repository: fum4/openkit

Length of output: 819


🏁 Script executed:

# Check git history or comments around the code for any discussion of encoding
rg "contents.*path|URL.*encod" libs/integrations/src/github/pr-diff.ts -B 3 -A 3

Repository: fum4/openkit

Length of output: 38


🏁 Script executed:

cat -n ./apps/server/src/__test__/pr-diff.test.ts | head -100

Repository: fum4/openkit

Length of output: 3552


🏁 Script executed:

# Search for test cases involving file paths with special characters
rg "getPrFileContent.*path|filePath.*:" ./apps/server/src/__test__/pr-diff.test.ts -B 2 -A 2

Repository: fum4/openkit

Length of output: 38


🏁 Script executed:

# Check if the gh CLI documentation addresses URL encoding in its help
# Let's search for any discussion of special characters or encoding in comments
rg "special.*char|encod|slash|path" libs/integrations/src/github/pr-diff.ts -i

Repository: fum4/openkit

Length of output: 721


🏁 Script executed:

# Let's see the full test to understand what file paths are being tested
cat -n ./apps/server/src/__test__/pr-diff.test.ts | sed -n '100,250p'

Repository: fum4/openkit

Length of output: 5143


🏁 Script executed:

# Check if there's any test case with special characters in file paths
rg "filePath|filename" ./apps/server/src/__test__/pr-diff.test.ts -B 2 -A 2

Repository: fum4/openkit

Length of output: 841


🏁 Script executed:

# See more test cases for getPrFileContent
cat -n ./apps/server/src/__test__/pr-diff.test.ts | sed -n '250,350p'

Repository: fum4/openkit

Length of output: 3491


🏁 Script executed:

# Check if there are any test cases with special characters in paths
grep -n "contents/" ./apps/server/src/__test__/pr-diff.test.ts

Repository: fum4/openkit

Length of output: 406


🏁 Script executed:

# Check gh CLI documentation behavior or search for any encoding patterns
rg "gh api" libs/integrations/src/github/ -A 3 -B 1 | head -30

Repository: fum4/openkit

Length of output: 38


🏁 Script executed:

# Let's check if there's any handling in shared utilities
fd -e ts -e tsx | xargs rg "encodeURI|URL" --type ts 2>/dev/null | head -20

Repository: fum4/openkit

Length of output: 2169


🏁 Script executed:

# Check how the gh CLI is documented to handle special characters in paths
# Let's search for any comments or documentation in the codebase about gh CLI quirks
rg "gh.*api|execGh" libs/integrations -B 5 -A 5 | head -40

Repository: fum4/openkit

Length of output: 2751


🏁 Script executed:

# Check if there's a package.json that might reference gh CLI docs
cat package.json | grep -A 5 -B 5 "gh"

Repository: fum4/openkit

Length of output: 38


URL-encode file path segments in GitHub contents API calls

Lines 206-207 and 247-248 interpolate fetchPath and filePath directly into the API URL without encoding reserved characters. File paths containing spaces, #, ?, %, or other unsafe URL characters will break API requests. Each path segment should be percent-encoded (e.g., "my file.ts" → "my%20file.ts"), while literal / characters between segments must be preserved.

Also applies to: 247-248

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

In `@libs/integrations/src/github/pr-diff.ts` around lines 206 - 207, The GitHub
contents API URLs interpolate raw fetchPath and filePath which can contain
unsafe characters; update the places building
`repos/${owner}/${repo}/contents/${fetchPath}?ref=${baseSha}` and the similar
`filePath` usage to percent-encode each path segment: split the path on '/', run
encodeURIComponent on each segment, then join with '/' so slashes are preserved,
and use that encoded string in the URL interpolation wherever `fetchPath` or
`filePath` are used.

Comment thread libs/integrations/src/github/pr-diff.ts Resolved
- record pre-reset HEAD SHA before git reset --hard in moveToWorktree
  (enables recovery if unpushedCount is wrong)
- use exact stash ref instead of implicit stash@{0} to avoid race conditions
  with concurrent stash operations
- replace empty catch blocks with log.warn in moveToWorktree
- return success: false on non-size fetch errors in getPrFileContent
  (was silently returning empty content as success)
- log warning when PR diff hits 100-file pagination limit
- re-export ROOT_WORKTREE_ID from shared instead of redefining in web-app

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (2)
apps/server/src/manager.ts (2)

1431-1499: ⚠️ Potential issue | 🔴 Critical

This can still discard the commits being “moved”.

createWorktree() only queues runCreateWorktree(), and that async path still creates the new branch from baseRef, not from the current HEAD. So the hard reset below can run before the destination exists at all, and in the normal success path the destination still does not inherit the unpushed commits you just removed from the root. Because the stash callback is attached afterward, a fast create path can also complete before onSuccess is registered, leaving the working-tree changes only in the stash. Register the success/failure callbacks before queuing creation, create this worktree from the current HEAD, and only reset or restore the root inside those callbacks.


748-755: ⚠️ Potential issue | 🟡 Minor

The synthetic root entry still reports the wrong branch.

getWorktreeBranch() only handles worktree-style .git files. On the main repo, .git is a directory, so this usually falls back to this.config.baseBranch whenever the root checkout is actually on some other branch. Use repo-HEAD detection for the root path instead of the worktree parser here.

🤖 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 748 - 755, The synthetic root
WorktreeInfo is using getWorktreeBranch(rootPath) which only handles
worktree-style .git files and falls back to this.config.baseBranch; replace that
call with a repo-HEAD detection for the repo at rootPath (parse the repository
HEAD, e.g. read .git/HEAD or use the existing helper that returns the current
branch from HEAD) so rootBranch reflects the actual checked-out branch instead
of always falling back to this.config.baseBranch; update the construction of
rootEntry (id ROOT_WORKTREE_ID, path rootPath, branch rootBranch) to use the
repo-HEAD result.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@libs/shared/src/worktree-types.ts`:
- Around line 79-80: The sentinel ROOT_WORKTREE_ID ("root") is currently a valid
user name and conflicts with lookups; update the code so the sentinel cannot be
user-supplied by either (a) changing ROOT_WORKTREE_ID to a value that cannot
match the worktree-name regex (e.g. a reserved prefix or non-printable sentinel)
or (b) adding explicit validation in createWorktree and renameWorktree to reject
any attempt to create/rename a worktree to ROOT_WORKTREE_ID; locate references
to ROOT_WORKTREE_ID and the name-validation logic used by
createWorktree/renameWorktree and implement one of these fixes so user-supplied
names can never collide with the synthetic root.

---

Duplicate comments:
In `@apps/server/src/manager.ts`:
- Around line 748-755: The synthetic root WorktreeInfo is using
getWorktreeBranch(rootPath) which only handles worktree-style .git files and
falls back to this.config.baseBranch; replace that call with a repo-HEAD
detection for the repo at rootPath (parse the repository HEAD, e.g. read
.git/HEAD or use the existing helper that returns the current branch from HEAD)
so rootBranch reflects the actual checked-out branch instead of always falling
back to this.config.baseBranch; update the construction of rootEntry (id
ROOT_WORKTREE_ID, path rootPath, branch rootBranch) to use the repo-HEAD result.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 945a8ff1-cfa6-422d-b9d0-31f281c1f2f0

📥 Commits

Reviewing files that changed from the base of the PR and between 50a51b3 and 66c4d54.

📒 Files selected for processing (3)
  • apps/server/src/manager.ts
  • libs/integrations/src/github/github-manager.ts
  • libs/shared/src/worktree-types.ts

Comment on lines +79 to +80
/** Sentinel ID used for the root project entry in the worktree list. */
export const ROOT_WORKTREE_ID = "root";

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

Reserve a non-user-representable root id.

"root" still passes the normal worktree-name regex. That means createWorktree() now treats it as already taken by the synthetic entry, while renameWorktree() can still rename a child worktree to "root", after which id resolution returns the synthetic root first and the real worktree becomes effectively unmanageable. Either pick a sentinel that can never be user-supplied or explicitly reject ROOT_WORKTREE_ID in create/rename flows.

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

In `@libs/shared/src/worktree-types.ts` around lines 79 - 80, The sentinel
ROOT_WORKTREE_ID ("root") is currently a valid user name and conflicts with
lookups; update the code so the sentinel cannot be user-supplied by either (a)
changing ROOT_WORKTREE_ID to a value that cannot match the worktree-name regex
(e.g. a reserved prefix or non-printable sentinel) or (b) adding explicit
validation in createWorktree and renameWorktree to reject any attempt to
create/rename a worktree to ROOT_WORKTREE_ID; locate references to
ROOT_WORKTREE_ID and the name-validation logic used by
createWorktree/renameWorktree and implement one of these fixes so user-supplied
names can never collide with the synthetic root.

fum4 and others added 7 commits March 23, 2026 00:27
…actions

Redesigns DiffFileSidebar to show Staged Changes / Changes sections when
showStagingActions is true, with per-file +/- hover buttons to stage or
unstage files and a Stage-all action on the Changes header.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

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

Caution

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

⚠️ Outside diff range comments (1)
libs/integrations/src/github/git-diff.ts (1)

360-389: ⚠️ Potential issue | 🟠 Major

Use the index as the baseline for unstaged file content.

The unstaged section is built from git diff (working tree vs index), but Lines 367-389 still load modified/deleted/renamed originals from HEAD whenever staged === false. If a file has both staged and unstaged hunks, the viewer shows the combined HEAD → working tree diff instead of only the unstaged delta.

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

In `@libs/integrations/src/github/git-diff.ts` around lines 360 - 389, The switch
currently always loads originals from gitShow(worktreePath, ref, ...) which uses
HEAD; when staged === false you must load originals from the index (the git
index baseline) instead of HEAD so unstaged diffs compare working tree → index.
Update the "modified", "deleted" and "renamed" branches to call
gitShow(worktreePath, "", <path>) for the old/original content whenever staged
=== false (keep using gitShow(worktreePath, ref, <path>) when staged is true or
includeCommitted applies), and keep readNew/readWorkingCopy usage for the new
content as defined by readNew; adjust references to filePath and oldPath
accordingly and set oldContent/newContent as before.
♻️ Duplicate comments (8)
apps/web-app/src/components/detail/DetailPanel.tsx (1)

1233-1257: ⚠️ Potential issue | 🟠 Major

Handle agent discovery failures and clear stale state.

If the IPC call or fetchAgentCliStatus() rejects, this effect throws and leaves the previous installedAgents set in place. The !serverUrl branch has the same stale-state problem. Catch the async work, log/surface the failure, and reset to an empty/null state before returning.

As per coding guidelines, **/*.{ts,tsx,js,jsx}: Treat error handling as a first-class concern. Every catch block, fallback branch, and error callback must do something meaningful: log through logger (log.error()/log.warn()) or surface to user via toast.

🤖 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 1233 - 1257,
The effect in useEffect that discovers agents (calls
window.electronAPI.getInstalledAgents and api.fetchAgentCliStatus) currently
lets rejections leave previous installedAgents state stale; wrap the entire
async body in try/catch, and on any error log it (e.g., log.error or show a
toast) and call setInstalledAgents(new Set()) (or set to null/empty) before
returning; also ensure the early-return branch for !serverUrl clears installed
state instead of returning silently. Keep references to the existing functions
(getInstalledAgents, fetchAgentCliStatus) and the state updater
setInstalledAgents so the catch and the !serverUrl branch consistently reset
state and surface the error.
apps/web-app/src/components/detail/DetailHeader.tsx (1)

403-410: ⚠️ Potential issue | 🟠 Major

Enable move-to-worktree when the root only has unpushed commits.

This flow is described as moving uncommitted changes and unpushed commits, but the button is disabled unless hasUncommitted is true. Root worktrees that are clean locally but ahead of remote can't access a supported workflow.

Suggested change
-                  disabled={isLoading || !worktree.hasUncommitted}
+                  disabled={isLoading || (!worktree.hasUncommitted && !worktree.hasUnpushed)}
                   aria-label="Move changes to worktree"
-                  title="Move uncommitted changes to a new worktree"
+                  title="Move uncommitted changes and unpushed commits to a new worktree"
🤖 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 403 - 410,
The button is currently disabled when only worktree.hasUncommitted is false,
blocking roots that are clean locally but have unpushed commits; update the
disabled prop in the DetailHeader button (the element using isRoot,
onMoveToWorktree and worktree.hasUncommitted) to enable the button when the root
has either uncommitted changes OR unpushed/“ahead” commits (e.g. change
disabled={isLoading || !worktree.hasUncommitted} to disabled={isLoading ||
!(worktree.hasUncommitted || worktree.isAhead || worktree.hasUnpushed)} using
whichever property your worktree model exposes for unpushed/ahead commits, and
adjust any naming to match the actual field).
apps/web-app/src/components/detail/DiffViewerTab.tsx (2)

77-82: ⚠️ Potential issue | 🟠 Major

Don’t cache merged PR metadata forever under only worktree.id.

fetchPrDiffFiles() depends on serverUrl, but the key on Line 78 ignores it. With staleTime: Infinity, the cached localHeadSha also never ages out, so hasPostMergeCommits can stay false after new local commits until this tab is recreated.

🤖 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 77 - 82,
The query key for prDiffQuery currently uses only worktree.id while
fetchPrDiffFiles also depends on serverUrl and the cache is permanent
(staleTime: Infinity), which causes localHeadSha and hasPostMergeCommits to
become stale; update the queryKey to include serverUrl (e.g., ["pr-diff",
worktree.id, serverUrl]) and remove or reduce staleTime so the cache can expire
(or add an appropriate refetch behavior) to ensure fetchPrDiffFiles and derived
values like localHeadSha / hasPostMergeCommits update when new local commits
occur.

215-217: ⚠️ Potential issue | 🟠 Major

Refresh is still hitting the local diff path in merged mode.

When showMergedDiff is true, Lines 215-217 still call fetchFiles(). A manual refresh therefore swaps the merged PR view back to the local diff instead of refreshing the merged data.

🤖 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 215 - 217,
handleRefresh currently always calls fetchFiles(), which forces a local diff
reload and breaks the merged PR view; update handleRefresh to check the
showMergedDiff boolean and call the merged-refresh function when true (e.g., the
existing function that fetches merged diff data) otherwise call fetchFiles();
adjust the useCallback dependency array to include the merged refresh function
reference and ensure the function names showMergedDiff, handleRefresh, and
fetchFiles (and the merged fetch helper) are used to locate and replace the
call.
apps/server/src/manager.ts (1)

1436-1504: ⚠️ Potential issue | 🔴 Critical

moveToWorktree() can still rewrite the root before the destination actually exists.

createWorktree() returns after queueing runCreateWorktree(), but Lines 1452-1476 hard-reset the root immediately. The async create path still branches from baseRef at Lines 1538-1586, so the new worktree never inherits the current HEAD commits. If creation/install/hooks fail later, the root history is already rewritten and the stash is never restored to the root.

🤖 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 1436 - 1504, moveToWorktree
currently resets the root branch immediately after createWorktree returns (which
only queues runCreateWorktree), causing the root to be rewritten before the
destination worktree actually exists; instead, wait for actual creation
completion (or move the reset into the onSuccess path) so the reset runs only
after runCreateWorktree finishes successfully. Concretely: stop calling
execFile("git", ["reset", "--hard", ...]) inside moveToWorktree right after
this.createWorktree(request); either make createWorktree / runCreateWorktree
return a completed success state before proceeding, or attach the reset logic to
the worktreeCallbacks.onSuccess handler for the created worktree id (similar to
how stash application is queued), and ensure the original stashRef is restored
to the root on any eventual failure so the root isn’t left rewritten without
stash restoration. Include references to createWorktree, runCreateWorktree,
moveToWorktree, worktreeCallbacks, and the stash restore/apply logic when
implementing the change.
apps/server/src/routes/github.ts (1)

585-638: ⚠️ Potential issue | 🟡 Minor

Validate status before casting it in /pr-diff/file.

This route still trusts the raw query string and casts it straight into the PR diff status union. Anything outside modified | added | deleted | renamed falls through getPrFileContent() as a modified-file fetch instead of returning a clean 400.

🤖 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 585 - 638, The handler trusts
the raw query param status and casts it into the union passed to
getPrFileContent, so invalid values silently become a "modified" fetch; fix by
explicitly validating status against the allowed set before casting (e.g. check
status is one of "modified"|"added"|"deleted"|"renamed"|"untracked"), and if not
return a 400 JSON error; update the code around the status variable and the call
to getPrFileContent so the cast only happens after this membership check.
apps/web-app/src/hooks/api.ts (2)

500-538: ⚠️ Potential issue | 🟠 Major

Add error logging in catch block.

The catch block at Line 530-537 returns an error object but does not log it. As per coding guidelines, every catch block must do something meaningful: log through the logger or surface to the user via toast.

🛡️ Suggested fix
   } catch (err) {
+    log.error("Failed to fetch PR file content", {
+      domain: "api",
+      worktreeId,
+      filePath,
+      error: err instanceof Error ? err.message : String(err),
+    });
     return {
       success: false,
       oldContent: "",
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/hooks/api.ts` around lines 500 - 538, In
fetchPrDiffFileContent's catch block, add error logging before returning the
error response: log the caught error with its details using the project's logger
(for example processLogger.error or logger.error) or surface it via the UI toast
helper, including context like worktreeId/filePath and the error object/message;
then return the existing error payload unchanged. This ensures
fetchPrDiffFileContent logs failures while preserving the current return
behavior.

466-498: ⚠️ Potential issue | 🟠 Major

Add error logging in catch block.

The catch block at Line 486-497 returns an error object but does not log it. As per coding guidelines, every catch block must do something meaningful: log through the logger or surface to the user via toast.

🛡️ Suggested fix
   } catch (err) {
+    log.error("Failed to fetch PR diff files", {
+      domain: "api",
+      worktreeId,
+      error: err instanceof Error ? err.message : String(err),
+    });
     return {
       success: false,
       files: [],

Note: You'll need to import the logger at the top of the file.

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

In `@apps/web-app/src/hooks/api.ts` around lines 466 - 498, The catch block in
fetchPrDiffFiles swallows errors without logging; import the shared logger at
the top of the file and inside fetchPrDiffFiles' catch, log a descriptive
message (e.g., "fetchPrDiffFiles failed for worktreeId=<...>") along with the
error/stack (err instanceof Error ? err : String(err)) before returning the
existing error response so the failure is recorded for debugging.
🧹 Nitpick comments (3)
apps/web-app/src/components/__test__/CreateCustomTaskModal.test.tsx (1)

1-3: Missing required JSDoc comment at file top.

As per coding guidelines, every source file must have a JSDoc comment explaining its purpose.

📝 Suggested JSDoc
+/**
+ * Unit tests for the CreateCustomTaskModal component, covering form rendering,
+ * validation, label management, submission flow, and error handling.
+ */
 import { render, screen, userEvent, waitFor } from "../../__test__/render";
 import { CreateCustomTaskModal } from "../CreateCustomTaskModal";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/__test__/CreateCustomTaskModal.test.tsx` around
lines 1 - 3, Add a top-of-file JSDoc block to the test file describing its
purpose and contents: a short description that this file contains unit tests for
the CreateCustomTaskModal component (imported as CreateCustomTaskModal) using
the test utilities (render, screen, userEvent, waitFor). Place the JSDoc
immediately above the first import so it satisfies the linter and follows
project JSDoc conventions (brief summary, any relevant tags like `@module` or
`@file` if your style requires them).
apps/server/src/__test__/auto-cleanup.test.ts (1)

53-57: Exercise the real worktree-settings path in this suite.

Stubbing loadWorktreeSettings() to {} globally means none of these cases actually cover the new override-precedence logic in handlePrStateChange; a regression there would still pass. Prefer mocking the fs boundary here, or at least add explicit cases where a per-worktree override beats the global config.

Based on learnings, mock at the boundary (fs, child_process, HTTP), not internal helpers, for improved test isolation.

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

In `@apps/server/src/__test__/auto-cleanup.test.ts` around lines 53 - 57, The
tests currently stub loadWorktreeSettings globally which hides the
override-precedence logic in handlePrStateChange; update the suite to stop
mocking loadWorktreeSettings and instead mock the filesystem boundary (e.g.,
stub fs.readFile/fs.exists or the module that reads the settings file) so the
real loadWorktreeSettings runs, and add at least one explicit test that writes a
global config and a per-worktree override then calls handlePrStateChange to
assert the worktree override wins; keep
deleteWorktreeSettings/updateWorktreeSettings mocked if needed but ensure
handlePrStateChange is exercised against the real loadWorktreeSettings behavior.
apps/web-app/src/components/detail/DetailPanel.tsx (1)

2109-2126: Reuse the shared toggle component here.

This adds a second switch implementation with bespoke markup/colors even though the app already has a standard toggle. Reusing the shared control keeps styling and accessibility consistent with the rest of the UI.

As per coding guidelines, apps/web-app/src/**/*.tsx: For switches/toggles, reuse the app-standard treatment (bg-accent when enabled, neutral off-state styling when disabled).

🤖 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 2109 - 2126,
In DetailPanel replace the bespoke switch markup that manipulates
pushAfterCommit/setPushAfterCommit with the app's shared Toggle/Switch
component: import the shared toggle used across the app, remove the custom
<button> and inner <span> code and render the shared component instead, passing
checked={pushAfterCommit} (or value) and onChange={(v) => setPushAfterCommit(v)}
(or the expected handler signature) and preserve the adjacent label text; this
ensures consistent bg-accent/neutral styling and accessibility with the rest of
the app.
🤖 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/routes/worktrees.ts`:
- Around line 643-662: The PATCH handler at
app.patch("/api/worktrees/:id/settings") must validate the parsed body before
using the "in" operator: ensure await c.req.json() returns a plain object (not
null, array, or primitive), then iterate the allowed keys
("autoCleanupOnMerge","autoCleanupOnClose") and only accept boolean or null
values (map null to undefined in the patch); if the body is not a plain object
or any provided value is not boolean/null, return a 400 JSON error instead of
proceeding to call updateWorktreeSettings(manager.getConfigDir(),
resolved.worktreeId, patch). Ensure you reference the existing variables body,
patch, updateWorktreeSettings, and resolved.worktreeId when implementing the
guard.

In `@apps/web-app/src/components/detail/DetailHeader.tsx`:
- Around line 286-301: The settings fetch/mutation helpers return { success:
boolean, error } but DetailHeader's settingsQuery and settingsMutation treat
failures as falsey, leading to silent wrong UI; update the queryFn (which calls
fetchWorktreeSettings) to throw when the returned object has success === false
(or alternatively have queryFn branch on success===false and call
showPersistentErrorToast/reportPersistentErrorToast with the error and then
throw) so React Query surfaces the error, and update the useMutation setup
(mutationFn calling updateWorktreeSettings) to either throw on success===false
or add onError to call showPersistentErrorToast/reportPersistentErrorToast and
avoid calling queryClient.invalidateQueries on failure (only invalidate in
onSuccess); reference settingsQuery, settingsMutation, fetchWorktreeSettings,
updateWorktreeSettings, queryClient.invalidateQueries,
showPersistentErrorToast/reportPersistentErrorToast, worktree.id and serverUrl
when making the changes.
- Around line 286-290: The query key for settingsQuery (useQuery call that uses
queryKey ["worktree-settings", worktree.id] and queryFn fetchWorktreeSettings)
is too coarse and can collide across projects; update the queryKey to include a
stable project/worktree identifier (e.g., worktree.path or another stable
project id) so it becomes ["worktree-settings", worktree.path, worktree.id] (or
similar), and update any places that invalidate this cache (the invalidation
key) to use the same composite key to ensure settings are scoped per
project/worktree and not shared across servers.

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 45-50: deriveMoveToWorktreeBranch can produce an empty string
(e.g., input "!!!"), so update the modal submit flow to validate the derived
branch name (resolvedBranch) and prevent submitting when it is empty/invalid:
call deriveMoveToWorktreeBranch(name) before enabling the action, ensure the
derived value is non-empty and matches the allowed branch pattern (only a-z0-9
and hyphens, no leading/trailing hyphens, no consecutive hyphens), disable the
submit button and show a validation error until resolvedBranch passes, and apply
this change to the same submit handlers/modals referenced (the places around
resolvedBranch and the submit functions at the other noted occurrences).

In `@apps/web-app/src/components/detail/DiffFileSidebar.tsx`:
- Around line 303-330: The stage/unstage button is hidden until hover, making it
unreachable by keyboard; update the button rendering inside DiffFileSidebar so
its visibility also responds to keyboard focus (add the equivalent of
group-focus-within and focus classes alongside group-hover:flex instead of only
group-hover:flex) and ensure the icon button has an accessible name (add an
aria-label like file.staged ? "Unstage file: {file.path}" : "Stage file:
{file.path}" or similar) and keep Tooltip text in sync; target the button
element and the surrounding group classname (references: showAction, onAction,
file, Tooltip, the button using Plus/Minus) when making these changes.

In `@apps/web-app/src/components/detail/DiffViewerTab.tsx`:
- Around line 313-315: Staged and unstaged rows share the same file.path key so
UI state (expansion, selection, fileRefs) collides; update all places that
derive row ids/keys to use a composite id (e.g. `${staged}:${file.path}`)
instead of file.path alone. Specifically, when building
stagedFiles/unstagedFiles (useMemo), when generating React keys for rows, when
storing/retrieving from fileRefs, and when reading/writing expansion or
selection state variables (e.g., expanded state, selectedFileId, toggle
handlers), switch to the composite id so staged and unstaged copies have unique
ids; apply the same change to the other block referenced (the code handling the
alternate file list around the 495-565 region). Ensure any comparisons or
lookups expecting file.path are updated to accept the composite id or derive the
path portion where needed.
- Around line 255-274: The handlers handleStageFile, handleUnstageFile and
handleStageAll currently ignore the { success, error } result from
stageFiles/unstageFiles/stageAllFiles and thus swallow failures; update each to
await the call, inspect the returned { success, error } (and wrap in try/catch
for thrown errors), call showPersistentErrorToast or reportPersistentErrorToast
with the error when success is false or an exception occurs, and only call
fetchFiles() after a successful operation; reference the functions stageFiles,
unstageFiles, stageAllFiles and the callbacks
handleStageFile/handleUnstageFile/handleStageAll to locate where to add the
error handling and toast reporting.

In `@apps/web-app/src/hooks/api.ts`:
- Around line 4161-4214: In both fetchWorktreeSettings and
updateWorktreeSettings, add error logging inside their catch blocks before
returning: call console.error (or the project's logger if available) with a
clear message and the caught error plus context (include worktreeId and
serverUrl) so the returned error remains the same but the exception is logged
for debugging; locate the catch blocks in functions fetchWorktreeSettings and
updateWorktreeSettings and insert the logging statement just before the existing
return.
- Around line 4216-4271: The catch blocks in stageFiles, unstageFiles, and
stageAllFiles only return error objects and do not log or surface the error;
update each catch to log the error (e.g., call your app logger like logger.error
or show a user toast with the error message) before returning — include the
caught error details (err instanceof Error ? err.message : String(err)) and
context (function name and worktreeId/paths where applicable) so debugging info
is recorded; modify the catch in stageFiles to log the error and
worktreeId/paths, likewise modify unstageFiles and stageAllFiles to log
function-specific context, then return the same error object as before.

In `@docs/superpowers/specs/2026-03-23-staged-unstaged-sidebar-design.md`:
- Around line 9-16: The heading for `getChangedFiles` in
docs/superpowers/specs/2026-03-23-staged-unstaged-sidebar-design.md is at h3
while the surrounding section is h2, so update the heading level to maintain a
proper hierarchy: change the `### `getChangedFiles`` heading to `##
`getChangedFiles`` or insert an intermediate h2 section above it to preserve
document structure; reference the `getChangedFiles` section in git-diff.ts to
ensure the doc heading matches the logical grouping.

In `@libs/shared/src/git.ts`:
- Around line 29-33: The code treats a gitdir target as process-relative which
breaks worktrees; change the assignment of headRefPath (currently using
path.join(gitDirMatch[1], "HEAD")) to resolve the gitdir value relative to the
.git file location by using path.resolve with path.dirname(dotGitPath) and the
captured gitDirMatch[1] before appending "HEAD", ensuring gitContent and
gitDirMatch logic remain unchanged.

---

Outside diff comments:
In `@libs/integrations/src/github/git-diff.ts`:
- Around line 360-389: The switch currently always loads originals from
gitShow(worktreePath, ref, ...) which uses HEAD; when staged === false you must
load originals from the index (the git index baseline) instead of HEAD so
unstaged diffs compare working tree → index. Update the "modified", "deleted"
and "renamed" branches to call gitShow(worktreePath, "", <path>) for the
old/original content whenever staged === false (keep using gitShow(worktreePath,
ref, <path>) when staged is true or includeCommitted applies), and keep
readNew/readWorkingCopy usage for the new content as defined by readNew; adjust
references to filePath and oldPath accordingly and set oldContent/newContent as
before.

---

Duplicate comments:
In `@apps/server/src/manager.ts`:
- Around line 1436-1504: moveToWorktree currently resets the root branch
immediately after createWorktree returns (which only queues runCreateWorktree),
causing the root to be rewritten before the destination worktree actually
exists; instead, wait for actual creation completion (or move the reset into the
onSuccess path) so the reset runs only after runCreateWorktree finishes
successfully. Concretely: stop calling execFile("git", ["reset", "--hard", ...])
inside moveToWorktree right after this.createWorktree(request); either make
createWorktree / runCreateWorktree return a completed success state before
proceeding, or attach the reset logic to the worktreeCallbacks.onSuccess handler
for the created worktree id (similar to how stash application is queued), and
ensure the original stashRef is restored to the root on any eventual failure so
the root isn’t left rewritten without stash restoration. Include references to
createWorktree, runCreateWorktree, moveToWorktree, worktreeCallbacks, and the
stash restore/apply logic when implementing the change.

In `@apps/server/src/routes/github.ts`:
- Around line 585-638: The handler trusts the raw query param status and casts
it into the union passed to getPrFileContent, so invalid values silently become
a "modified" fetch; fix by explicitly validating status against the allowed set
before casting (e.g. check status is one of
"modified"|"added"|"deleted"|"renamed"|"untracked"), and if not return a 400
JSON error; update the code around the status variable and the call to
getPrFileContent so the cast only happens after this membership check.

In `@apps/web-app/src/components/detail/DetailHeader.tsx`:
- Around line 403-410: The button is currently disabled when only
worktree.hasUncommitted is false, blocking roots that are clean locally but have
unpushed commits; update the disabled prop in the DetailHeader button (the
element using isRoot, onMoveToWorktree and worktree.hasUncommitted) to enable
the button when the root has either uncommitted changes OR unpushed/“ahead”
commits (e.g. change disabled={isLoading || !worktree.hasUncommitted} to
disabled={isLoading || !(worktree.hasUncommitted || worktree.isAhead ||
worktree.hasUnpushed)} using whichever property your worktree model exposes for
unpushed/ahead commits, and adjust any naming to match the actual field).

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 1233-1257: The effect in useEffect that discovers agents (calls
window.electronAPI.getInstalledAgents and api.fetchAgentCliStatus) currently
lets rejections leave previous installedAgents state stale; wrap the entire
async body in try/catch, and on any error log it (e.g., log.error or show a
toast) and call setInstalledAgents(new Set()) (or set to null/empty) before
returning; also ensure the early-return branch for !serverUrl clears installed
state instead of returning silently. Keep references to the existing functions
(getInstalledAgents, fetchAgentCliStatus) and the state updater
setInstalledAgents so the catch and the !serverUrl branch consistently reset
state and surface the error.

In `@apps/web-app/src/components/detail/DiffViewerTab.tsx`:
- Around line 77-82: The query key for prDiffQuery currently uses only
worktree.id while fetchPrDiffFiles also depends on serverUrl and the cache is
permanent (staleTime: Infinity), which causes localHeadSha and
hasPostMergeCommits to become stale; update the queryKey to include serverUrl
(e.g., ["pr-diff", worktree.id, serverUrl]) and remove or reduce staleTime so
the cache can expire (or add an appropriate refetch behavior) to ensure
fetchPrDiffFiles and derived values like localHeadSha / hasPostMergeCommits
update when new local commits occur.
- Around line 215-217: handleRefresh currently always calls fetchFiles(), which
forces a local diff reload and breaks the merged PR view; update handleRefresh
to check the showMergedDiff boolean and call the merged-refresh function when
true (e.g., the existing function that fetches merged diff data) otherwise call
fetchFiles(); adjust the useCallback dependency array to include the merged
refresh function reference and ensure the function names showMergedDiff,
handleRefresh, and fetchFiles (and the merged fetch helper) are used to locate
and replace the call.

In `@apps/web-app/src/hooks/api.ts`:
- Around line 500-538: In fetchPrDiffFileContent's catch block, add error
logging before returning the error response: log the caught error with its
details using the project's logger (for example processLogger.error or
logger.error) or surface it via the UI toast helper, including context like
worktreeId/filePath and the error object/message; then return the existing error
payload unchanged. This ensures fetchPrDiffFileContent logs failures while
preserving the current return behavior.
- Around line 466-498: The catch block in fetchPrDiffFiles swallows errors
without logging; import the shared logger at the top of the file and inside
fetchPrDiffFiles' catch, log a descriptive message (e.g., "fetchPrDiffFiles
failed for worktreeId=<...>") along with the error/stack (err instanceof Error ?
err : String(err)) before returning the existing error response so the failure
is recorded for debugging.

---

Nitpick comments:
In `@apps/server/src/__test__/auto-cleanup.test.ts`:
- Around line 53-57: The tests currently stub loadWorktreeSettings globally
which hides the override-precedence logic in handlePrStateChange; update the
suite to stop mocking loadWorktreeSettings and instead mock the filesystem
boundary (e.g., stub fs.readFile/fs.exists or the module that reads the settings
file) so the real loadWorktreeSettings runs, and add at least one explicit test
that writes a global config and a per-worktree override then calls
handlePrStateChange to assert the worktree override wins; keep
deleteWorktreeSettings/updateWorktreeSettings mocked if needed but ensure
handlePrStateChange is exercised against the real loadWorktreeSettings behavior.

In `@apps/web-app/src/components/__test__/CreateCustomTaskModal.test.tsx`:
- Around line 1-3: Add a top-of-file JSDoc block to the test file describing its
purpose and contents: a short description that this file contains unit tests for
the CreateCustomTaskModal component (imported as CreateCustomTaskModal) using
the test utilities (render, screen, userEvent, waitFor). Place the JSDoc
immediately above the first import so it satisfies the linter and follows
project JSDoc conventions (brief summary, any relevant tags like `@module` or
`@file` if your style requires them).

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 2109-2126: In DetailPanel replace the bespoke switch markup that
manipulates pushAfterCommit/setPushAfterCommit with the app's shared
Toggle/Switch component: import the shared toggle used across the app, remove
the custom <button> and inner <span> code and render the shared component
instead, passing checked={pushAfterCommit} (or value) and onChange={(v) =>
setPushAfterCommit(v)} (or the expected handler signature) and preserve the
adjacent label text; this ensures consistent bg-accent/neutral styling and
accessibility with the rest of the app.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8524515c-9395-4307-9081-566eb1ee37dc

📥 Commits

Reviewing files that changed from the base of the PR and between 66c4d54 and 21c7ed7.

📒 Files selected for processing (27)
  • AGENTS.md
  • CLAUDE.md
  • apps/server/src/__test__/auto-cleanup.test.ts
  • apps/server/src/__test__/git-diff.test.ts
  • apps/server/src/__test__/worktree-settings.test.ts
  • apps/server/src/manager.ts
  • apps/server/src/routes/github.ts
  • apps/server/src/routes/worktrees.ts
  • apps/server/src/worktree-settings.ts
  • apps/web-app/src/components/ConfigurationPanel.tsx
  • apps/web-app/src/components/CreateCustomTaskModal.tsx
  • apps/web-app/src/components/__test__/CreateCustomTaskModal.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__/DiffFileSidebar.test.tsx
  • apps/web-app/src/components/detail/__test__/DiffViewerTab.test.tsx
  • apps/web-app/src/hooks/api.ts
  • docs/superpowers/plans/2026-03-23-per-worktree-auto-cleanup.md
  • docs/superpowers/plans/2026-03-23-staged-unstaged-sidebar.md
  • docs/superpowers/specs/2026-03-23-per-worktree-auto-cleanup-design.md
  • docs/superpowers/specs/2026-03-23-staged-unstaged-sidebar-design.md
  • libs/integrations/src/github/git-diff.ts
  • libs/shared/src/git.ts
  • libs/shared/src/worktree-types.ts
✅ Files skipped from review due to trivial changes (5)
  • apps/web-app/src/components/CreateCustomTaskModal.tsx
  • CLAUDE.md
  • AGENTS.md
  • apps/web-app/src/components/ConfigurationPanel.tsx
  • libs/shared/src/worktree-types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/web-app/src/components/detail/test/DiffViewerTab.test.tsx
  • apps/server/src/test/git-diff.test.ts

Comment thread apps/server/src/routes/worktrees.ts Resolved
Comment thread apps/web-app/src/hooks/api.ts Resolved
Comment thread apps/web-app/src/hooks/api.ts Resolved
Comment thread libs/shared/src/git.ts Resolved
@fum4
fum4 merged commit ad0af88 into master Mar 23, 2026
23 checks passed
@fum4
fum4 deleted the fix/various-2 branch March 23, 2026 20:55
@coderabbitai coderabbitai Bot mentioned this pull request Mar 24, 2026

This branch was previously deployed

1 inactive deployment
Preview — 466f99ff Deployed Mar 23, 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