Repository navigation
various improvements - #95
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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
Sequence DiagramssequenceDiagram
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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
There was a problem hiding this comment.
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 | 🟠 MajorAdd 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 | 🟡 MinorAdd 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 fromtheme.ts. The file already importstexttokens 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-rootendpoint correctly:
- Validates required
branchparameter- 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_IDis already defined inlibs/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 inDiffFileSection.tsx, but the actual implementation removed the loading state and simplified the approach (using onlyfetchingReffor 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: ReuseToggleSwitchfor “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
📒 Files selected for processing (35)
apps/desktop-app/src/main.tsapps/desktop-app/src/preload.cjsapps/desktop-app/src/preload.tsapps/desktop-app/src/project-manager.tsapps/e2e/src/fixtures.tsapps/server/src/__test__/git-diff.test.tsapps/server/src/__test__/pr-diff.test.tsapps/server/src/manager.tsapps/server/src/routes/github.tsapps/server/src/routes/worktrees.tsapps/web-app/src/App.tsxapps/web-app/src/components/ActivityPage.tsxapps/web-app/src/components/WorktreeItem.tsxapps/web-app/src/components/WorktreeList.tsxapps/web-app/src/components/detail/DetailHeader.tsxapps/web-app/src/components/detail/DetailPanel.tsxapps/web-app/src/components/detail/DiffFileSection.tsxapps/web-app/src/components/detail/DiffViewerTab.tsxapps/web-app/src/components/detail/LogsViewer.tsxapps/web-app/src/components/detail/__test__/DiffViewerTab.test.tsxapps/web-app/src/env.d.tsapps/web-app/src/errorToasts.tsxapps/web-app/src/hooks/api.tsapps/web-app/src/hooks/useApi.tsapps/web-app/src/types.tsdocs/ELECTRON.mddocs/superpowers/plans/2026-03-20-merged-pr-diff-view.mddocs/superpowers/plans/2026-03-20-worktree-auto-cleanup.mddocs/superpowers/specs/2026-03-20-merged-pr-diff-view-design.mddocs/superpowers/specs/2026-03-20-worktree-auto-cleanup-design.mdlibs/integrations/src/github/git-diff.tslibs/integrations/src/github/github-manager.tslibs/integrations/src/github/index.tslibs/integrations/src/github/pr-diff.tslibs/shared/src/worktree-types.ts
| - [ ] **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 |
There was a problem hiding this comment.
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.
| const { stdout: filesOut } = await execGh([ | ||
| "api", | ||
| `repos/${owner}/${repo}/pulls/${prNumber}/files?per_page=100`, | ||
| ]); | ||
|
|
||
| const ghFiles = JSON.parse(filesOut.trim()) as GitHubPRFile[]; | ||
|
|
There was a problem hiding this comment.
🧩 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. Maxper_page: 100. Defaultpage: 1. [1] - Paging mechanism: Use query parameters
?per_page=…&page=…, and follow the HTTPLinkresponse header URLs (withrel="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 -5Repository: 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.tsRepository: 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.
| 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.
| `repos/${owner}/${repo}/contents/${fetchPath}?ref=${baseSha}`, | ||
| ]); |
There was a problem hiding this comment.
🧩 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) forGET /repos/{owner}/{repo}/contents/{path}. Example:docs/README.md→docs/README.md. - Only encode a slash as
%2Fwhen 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.
- Keep literal
-
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.
- Example:
- Percent-encode them (UTF-8 then
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 -40Repository: 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.tsRepository: 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 -50Repository: 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 2Repository: 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 3Repository: fum4/openkit
Length of output: 38
🏁 Script executed:
# Look for encodeURIComponent usage in the entire codebase
rg "encodeURIComponent" --type jsRepository: 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 -20Repository: 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 3Repository: fum4/openkit
Length of output: 38
🏁 Script executed:
cat -n ./apps/server/src/__test__/pr-diff.test.ts | head -100Repository: 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 2Repository: 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 -iRepository: 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 2Repository: 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.tsRepository: 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 -30Repository: 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 -20Repository: 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 -40Repository: 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.
- 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
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
apps/server/src/manager.ts (2)
1431-1499:⚠️ Potential issue | 🔴 CriticalThis can still discard the commits being “moved”.
createWorktree()only queuesrunCreateWorktree(), and that async path still creates the new branch frombaseRef, not from the currentHEAD. 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 beforeonSuccessis registered, leaving the working-tree changes only in the stash. Register the success/failure callbacks before queuing creation, create this worktree from the currentHEAD, and only reset or restore the root inside those callbacks.
748-755:⚠️ Potential issue | 🟡 MinorThe synthetic root entry still reports the wrong branch.
getWorktreeBranch()only handles worktree-style.gitfiles. On the main repo,.gitis a directory, so this usually falls back tothis.config.baseBranchwhenever 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
📒 Files selected for processing (3)
apps/server/src/manager.tslibs/integrations/src/github/github-manager.tslibs/shared/src/worktree-types.ts
| /** Sentinel ID used for the root project entry in the worktree list. */ | ||
| export const ROOT_WORKTREE_ID = "root"; |
There was a problem hiding this comment.
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.
…ides Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…d API Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…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]>
There was a problem hiding this comment.
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 | 🟠 MajorUse 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 fromHEADwheneverstaged === false. If a file has both staged and unstaged hunks, the viewer shows the combinedHEAD → working treediff 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 | 🟠 MajorHandle agent discovery failures and clear stale state.
If the IPC call or
fetchAgentCliStatus()rejects, this effect throws and leaves the previousinstalledAgentsset in place. The!serverUrlbranch 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 | 🟠 MajorEnable 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
hasUncommittedis 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 | 🟠 MajorDon’t cache merged PR metadata forever under only
worktree.id.
fetchPrDiffFiles()depends onserverUrl, but the key on Line 78 ignores it. WithstaleTime: Infinity, the cachedlocalHeadShaalso never ages out, sohasPostMergeCommitscan 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 | 🟠 MajorRefresh is still hitting the local diff path in merged mode.
When
showMergedDiffis true, Lines 215-217 still callfetchFiles(). 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 queueingrunCreateWorktree(), but Lines 1452-1476 hard-reset the root immediately. The async create path still branches frombaseRefat Lines 1538-1586, so the new worktree never inherits the currentHEADcommits. 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 | 🟡 MinorValidate
statusbefore 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 | renamedfalls throughgetPrFileContent()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 | 🟠 MajorAdd 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 | 🟠 MajorAdd 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 inhandlePrStateChange; 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
📒 Files selected for processing (27)
AGENTS.mdCLAUDE.mdapps/server/src/__test__/auto-cleanup.test.tsapps/server/src/__test__/git-diff.test.tsapps/server/src/__test__/worktree-settings.test.tsapps/server/src/manager.tsapps/server/src/routes/github.tsapps/server/src/routes/worktrees.tsapps/server/src/worktree-settings.tsapps/web-app/src/components/ConfigurationPanel.tsxapps/web-app/src/components/CreateCustomTaskModal.tsxapps/web-app/src/components/__test__/CreateCustomTaskModal.test.tsxapps/web-app/src/components/detail/DetailHeader.tsxapps/web-app/src/components/detail/DetailPanel.tsxapps/web-app/src/components/detail/DiffFileSection.tsxapps/web-app/src/components/detail/DiffFileSidebar.tsxapps/web-app/src/components/detail/DiffViewerTab.tsxapps/web-app/src/components/detail/__test__/DiffFileSidebar.test.tsxapps/web-app/src/components/detail/__test__/DiffViewerTab.test.tsxapps/web-app/src/hooks/api.tsdocs/superpowers/plans/2026-03-23-per-worktree-auto-cleanup.mddocs/superpowers/plans/2026-03-23-staged-unstaged-sidebar.mddocs/superpowers/specs/2026-03-23-per-worktree-auto-cleanup-design.mddocs/superpowers/specs/2026-03-23-staged-unstaged-sidebar-design.mdlibs/integrations/src/github/git-diff.tslibs/shared/src/git.tslibs/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
Summary by CodeRabbit
New Features
Improvements
Tests
Documentation