Repository navigation
fix(host-service): don't link workspaces to default-branch PRs - #5692
Conversation
A workspace branched off the repo's default branch keeps tracking origin/<default> until its own branch is pushed, so resolveWorkspaceUpstream resolves its upstream branch to <default>. performProjectRefresh then keyed on owner/repo#<default> and linked whatever open PR had head=<default> (e.g. a "sync main into X" PR) — a PR unrelated to the workspace. Guard link assignment: a workspace may only key on the base repo's default branch when its local branch actually is that default branch. Fork PRs whose head happens to be named <default> (e.g. a gh pr checkout rename) still link, and the case-sensitivity of upstreamKey is preserved.
The v2 workspaces list re-derived each workspace's PR client-side from a fuzzy repositoryId::branch map with first-match-wins on a non-unique key, no head-SHA check, and no fork/owner qualifier. Two PRs sharing a head branch (e.g. `main` or `patch-1`) across forks mistracked, and the list could visibly disagree with the sidebar, which reads the authoritative workspace.pullRequestId. Fan getByWorkspaces out per host exactly as useDashboardSidebarData does to get the authoritative PR number per workspace, then key the rich PR row by the unique (repositoryId, prNumber). The sidebar and the list now agree.
|
Bugbot is not enabled for your account, so this pull request was not reviewed. Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs. |
📝 WalkthroughWalkthroughThe host service now detects repository default branches and guards pull-request refresh matching. The desktop workspace hook obtains authoritative workspace-to-PR mappings and resolves pull-request summaries by repository and PR number. ChangesPull request linkage
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant WorkspaceHook
participant HostServiceClient
participant PullRequestRuntimeManager
participant Git
WorkspaceHook->>HostServiceClient: query PRs by workspace IDs
HostServiceClient->>PullRequestRuntimeManager: refresh workspace PR links
PullRequestRuntimeManager->>Git: resolve repository default branch
Git-->>PullRequestRuntimeManager: default branch
PullRequestRuntimeManager-->>HostServiceClient: authoritative workspace-to-PR mappings
HostServiceClient-->>WorkspaceHook: PR numbers
WorkspaceHook->>WorkspaceHook: resolve summaries by repository and PR number
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Ready to review this PR? Stage has broken it down into 3 individual chapters for you:
Chapters generated by Stage for commit 5920738 on Jul 15, 2026 6:19am UTC. |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/host-service/src/runtime/pull-requests/pull-requests.ts (1)
669-680: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winEnsure the default-branch guard wins even when the SHAs match.
A non-default local branch can share the default branch's current SHA. The guarded key becomes
null, but the existing SHA fallback then preserves the exact mislink this change intends to clear.
packages/host-service/src/runtime/pull-requests/pull-requests.ts#L669-L680: preserve SHA-linked PRs only when the raw upstream key is genuinely absent, not wheneffectiveUpstreamKeysuppressed it.packages/host-service/src/runtime/pull-requests/pull-requests.test.ts#L655-L667: give the workspace andhead=mainPR the same SHA so the regression test covers this branch.Proposed fix
for (const workspace of projectWorkspaces) { + const upstreamBranch = workspace.upstreamBranch ?? workspace.branch; + const rawKey = upstreamKey( + workspace.upstreamOwner, + workspace.upstreamRepo, + upstreamBranch, + ); const key = this.effectiveUpstreamKey(workspace, repo); if (!key) { if ( + !rawKey && this.pullRequestHeadMatches( workspace.pullRequestId, workspace.headSha,- headSha: "workspace-sha", + headSha: "main-sha",🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/host-service/src/runtime/pull-requests/pull-requests.ts` around lines 669 - 680, The default-branch guard must take precedence over SHA matching: in the pull-request checkout logic around effectiveUpstreamKey and pullRequestHeadMatches, only retain the explicit PR link when the raw upstream key is genuinely absent, not when effectiveUpstreamKey suppressed it. Update the regression case in packages/host-service/src/runtime/pull-requests/pull-requests.test.ts at lines 655-667 so the workspace and head=main PR use the same SHA, covering the guarded-key path.
🧹 Nitpick comments (1)
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.ts (1)
10-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMove the shared query-target utility out of the sidebar subtree.
derivePullRequestQueryTargetsnow serves both sidebar and v2-workspaces, so this import couples sibling features. Promote it to their highest shared dashboard location and update both consumers.As per coding guidelines, co-locate code by usage and promote code used multiple times to the highest shared parent.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.ts` at line 10, Move derivePullRequestQueryTargets from the DashboardSidebar subtree to the highest shared dashboard location used by both sidebar and v2-workspaces, then update imports in both consumers to reference the promoted utility. Preserve the utility’s behavior and remove the old sidebar-specific location.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@packages/host-service/src/runtime/pull-requests/pull-requests.ts`:
- Around line 669-680: The default-branch guard must take precedence over SHA
matching: in the pull-request checkout logic around effectiveUpstreamKey and
pullRequestHeadMatches, only retain the explicit PR link when the raw upstream
key is genuinely absent, not when effectiveUpstreamKey suppressed it. Update the
regression case in
packages/host-service/src/runtime/pull-requests/pull-requests.test.ts at lines
655-667 so the workspace and head=main PR use the same SHA, covering the
guarded-key path.
---
Nitpick comments:
In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.ts`:
- Line 10: Move derivePullRequestQueryTargets from the DashboardSidebar subtree
to the highest shared dashboard location used by both sidebar and v2-workspaces,
then update imports in both consumers to reference the promoted utility.
Preserve the utility’s behavior and remove the old sidebar-specific location.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: e5cb4a3f-8cbe-415a-b72b-df2bd3486bbe
📒 Files selected for processing (3)
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.tspackages/host-service/src/runtime/pull-requests/pull-requests.test.tspackages/host-service/src/runtime/pull-requests/pull-requests.ts
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
Thank you for your contribution! 🎉 |
There was a problem hiding this comment.
No issues found across 3 files
Architecture diagram
sequenceDiagram
participant UI as Workspace List Component
participant Hook as useAccessibleV2Workspaces
participant HostClient as Host Service Client
participant PRManager as PullRequestRuntimeManager
participant DB as Host SQLite
participant Git as Git CLI
Note over UI,Git: Desktop Workspace List Flow
UI->>Hook: render workspace list
Hook->>DB: query workspaces (live)
DB-->>Hook: workspace rows
Hook->>DB: query PR rows (live)
DB-->>Hook: PR rows (including repositoryId, prNumber)
Hook->>HostClient: NEW: per host, getByWorkspaces (via useQueries)
HostClient-->>Hook: { workspaceId, pullRequest } entries
Hook->>Hook: build prNumberByWorkspaceId map from authoritative responses
Hook->>Hook: build prByRepoNumber map from local PR rows (key: repoId::prNumber)
Hook->>Hook: enrich workspaces: for each workspace, look up prNumber, then find PR by (repoId, prNumber)
Note right of Hook: CHANGED: no longer uses repositoryId::branch matching
Hook-->>UI: enriched workspace list with correct PR links
Note over PRManager,DB: Host-Service Refresh Flow (when link is recalculated)
PRManager->>DB: query workspaces for project
DB-->>PRManager: workspace rows
PRManager->>Git: NEW: resolveDefaultBranch() → git symbolic-ref refs/remotes/origin/HEAD
Git-->>PRManager: default branch (e.g. "main")
PRManager->>PRManager: effectiveUpstreamKey(workspace, repo)
alt upstreamBranch == defaultBranch && localBranch != defaultBranch && upstream is base repo
PRManager->>PRManager: return null → workspace gets no PR link
else
PRManager->>PRManager: compute upstreamKey from upstreamOwner/repo/branch
end
PRManager->>GitHub: fetch PRs by head ref (using gh)
GitHub-->>PRManager: PR nodes
PRManager->>DB: update workspace.pullRequestId with matched PR or null
Greptile SummaryThis PR fixes two related bugs in how workspaces are linked to pull requests. The primary fix (host-service) guards against workspaces that track
Confidence Score: 4/5Safe to merge — the guard correctly prevents default-branch mislinks for the primary bug scenario, tests were mutation-verified, and the desktop change replaces a demonstrably wrong lookup with an authoritative one. One unaddressed edge case: a workspace sitting at the exact same commit as main's tip and already carrying the bad PR link could have that link retained through the pullRequestHeadMatches fallback path. The React useRef-in-useMemo pattern in useStableWorkspacePrNumbers works today but relies on implementation details. The !key branch in performProjectRefresh now serves two distinct semantics (PR-checkout retain vs. default-branch guard clear) without distinguishing them.
|
| Filename | Overview |
|---|---|
| packages/host-service/src/runtime/pull-requests/pull-requests.ts | Adds effectiveUpstreamKey guard that returns null when a workspace tracks the default branch but its local branch differs. One edge case: the guard reuses the PR-checkout null-key path, which retains a bad link if workspace.headSha equals the default-branch PR's headSha. |
| packages/host-service/src/runtime/pull-requests/pull-requests.test.ts | Three new mutation-tested cases cover the default-branch guard. Also fixes routeGh to use indexOf(':') instead of a hardcoded base-owner prefix, correctly handling fork-owner query args. |
| apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.ts | Replaces the client-side repositoryId::headBranch map with authoritative per-host getByWorkspaces polling keyed by unique (repositoryId, prNumber). Adds useStableWorkspacePrNumbers which mutates useRef inside useMemo, a minor React anti-pattern. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[performProjectRefresh] --> B[getProjectRepository]
B --> C[resolveDefaultBranch\ngit symbolic-ref --short\nrefs/remotes/remote/HEAD]
C --> D{Cached?}
D -->|Yes| E[Return cached branch]
D -->|No| F[Query git, cache result]
B --> G[NormalizedRepoIdentity + defaultBranch]
G --> H[effectiveUpstreamKey per workspace]
H --> I{upstreamBranch == defaultBranch AND local != defaultBranch AND same base repo?}
I -->|Yes - guard fires| J[return null]
I -->|No| K[return upstreamKey owner/repo#branch]
J --> L{pullRequestHeadMatches? workspace.headSha == PR.headSha}
L -->|Yes - edge case| M[Retain bad link]
L -->|No| N[Clear pullRequestId]
K --> O[Fetch GitHub PRs for key]
O --> P[Write pullRequestId to workspace]
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
A[performProjectRefresh] --> B[getProjectRepository]
B --> C[resolveDefaultBranch\ngit symbolic-ref --short\nrefs/remotes/remote/HEAD]
C --> D{Cached?}
D -->|Yes| E[Return cached branch]
D -->|No| F[Query git, cache result]
B --> G[NormalizedRepoIdentity + defaultBranch]
G --> H[effectiveUpstreamKey per workspace]
H --> I{upstreamBranch == defaultBranch AND local != defaultBranch AND same base repo?}
I -->|Yes - guard fires| J[return null]
I -->|No| K[return upstreamKey owner/repo#branch]
J --> L{pullRequestHeadMatches? workspace.headSha == PR.headSha}
L -->|Yes - edge case| M[Retain bad link]
L -->|No| N[Clear pullRequestId]
K --> O[Fetch GitHub PRs for key]
O --> P[Write pullRequestId to workspace]
Comments Outside Diff (1)
-
packages/host-service/src/runtime/pull-requests/pull-requests.ts, line 668-689 (link)Guard falls into the PR-checkout retain path — bad link can survive a headSha coincidence
When
effectiveUpstreamKeyreturnsnulldue to the new default-branch guard, the workspace falls into the block originally designed for "PR checkouts recovered from archived refs." That block callspullRequestHeadMatches(workspace.pullRequestId, workspace.headSha)and keeps the link if it returnstrue. If a workspace whose local branch is not the default branch happens to sit at the exact same commit as the tip of the default branch (freshly branched, no own commits yet), and the bad PR'sheadShamatches, the incorrect link is silently retained instead of being cleared. The primary scenario in the bug report would not hit this, but the edge case is reachable and the guard-triggered!keypath carries no comment distinguishing it from the original PR-checkout case.Prompt To Fix With AI
This is a comment left during a code review. Path: packages/host-service/src/runtime/pull-requests/pull-requests.ts Line: 668-689 Comment: **Guard falls into the PR-checkout retain path — bad link can survive a headSha coincidence** When `effectiveUpstreamKey` returns `null` due to the new default-branch guard, the workspace falls into the block originally designed for "PR checkouts recovered from archived refs." That block calls `pullRequestHeadMatches(workspace.pullRequestId, workspace.headSha)` and keeps the link if it returns `true`. If a workspace whose local branch is _not_ the default branch happens to sit at the exact same commit as the tip of the default branch (freshly branched, no own commits yet), and the bad PR's `headSha` matches, the incorrect link is silently retained instead of being cleared. The primary scenario in the bug report would not hit this, but the edge case is reachable and the guard-triggered `!key` path carries no comment distinguishing it from the original PR-checkout case. How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 2
packages/host-service/src/runtime/pull-requests/pull-requests.ts:668-689
**Guard falls into the PR-checkout retain path — bad link can survive a headSha coincidence**
When `effectiveUpstreamKey` returns `null` due to the new default-branch guard, the workspace falls into the block originally designed for "PR checkouts recovered from archived refs." That block calls `pullRequestHeadMatches(workspace.pullRequestId, workspace.headSha)` and keeps the link if it returns `true`. If a workspace whose local branch is _not_ the default branch happens to sit at the exact same commit as the tip of the default branch (freshly branched, no own commits yet), and the bad PR's `headSha` matches, the incorrect link is silently retained instead of being cleared. The primary scenario in the bug report would not hit this, but the edge case is reachable and the guard-triggered `!key` path carries no comment distinguishing it from the original PR-checkout case.
### Issue 2 of 2
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.ts:219-236
**`useRef` mutation inside `useMemo` violates React's purity contract**
`previousRef.current` is written inside the `useMemo` callback. React treats memos as pure and may invoke the callback multiple times with the same deps in concurrent mode. The fingerprint check recovers correctly today, but this relies on implementation details about when React replays side effects. A cleaner pattern moves the fingerprint tracking into a `useRef` updated unconditionally, with a separate `useMemo` that reads from the ref.
Reviews (1): Last reviewed commit: "fix(desktop): track workspace PRs by aut..." | Re-trigger Greptile
| // The `useQueries` result array gets a fresh identity every render, so memoize | ||
| // the derived workspace→PR-number map on its content to keep `enriched` stable. | ||
| function useStableWorkspacePrNumbers( | ||
| entries: [string, number][], | ||
| ): Map<string, number> { | ||
| const previousRef = useRef<{ | ||
| fingerprint: string; | ||
| map: Map<string, number>; | ||
| } | null>(null); | ||
| return useMemo(() => { | ||
| const sorted = [...entries].sort(([a], [b]) => a.localeCompare(b)); | ||
| const fingerprint = JSON.stringify(sorted); | ||
| if (previousRef.current?.fingerprint === fingerprint) { | ||
| return previousRef.current.map; | ||
| } | ||
| const map = new Map(sorted); | ||
| previousRef.current = { fingerprint, map }; | ||
| return map; |
There was a problem hiding this comment.
useRef mutation inside useMemo violates React's purity contract
previousRef.current is written inside the useMemo callback. React treats memos as pure and may invoke the callback multiple times with the same deps in concurrent mode. The fingerprint check recovers correctly today, but this relies on implementation details about when React replays side effects. A cleaner pattern moves the fingerprint tracking into a useRef updated unconditionally, with a separate useMemo that reads from the ref.
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.ts
Line: 219-236
Comment:
**`useRef` mutation inside `useMemo` violates React's purity contract**
`previousRef.current` is written inside the `useMemo` callback. React treats memos as pure and may invoke the callback multiple times with the same deps in concurrent mode. The fingerprint check recovers correctly today, but this relies on implementation details about when React replays side effects. A cleaner pattern moves the fingerprint tracking into a `useRef` updated unconditionally, with a separate `useMemo` that reads from the ref.
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
…guard The default-branch guard resolved origin/HEAD with its own inline symref parsing + a bespoke cache. Delegate to the shared resolveDefaultBranchName (runtime/git/refs) — the same origin/HEAD symref used by git status and branch search — so PR linking, git status, and workspace creation all agree on the default branch. Drops the duplicated parsing and the redundant cache (a local symref per refresh is cheap and matches how the rest of the codebase calls this helper).
Problem
A workspace on branch
roshvan/mcp-1703-mcp-surface-areashowed PR #1522 "chore: sync main into feat/signal-pages" (head branch =main) in its right-sidebar Review panel — a PR unrelated to the workspace. A reviewer even flagged it: "Wrong direction — head=main can't be up-to-date with feat/signal-pages".Root cause (primary — what renders)
resolveWorkspaceUpstream()keys the PR match on the branch's tracked remote merge ref (branch.<name>.merge) rather than the local branch name. A workspace branched offmainkeeps trackingorigin/mainuntil its own branch is pushed (@{push}unconfigured), so the resolved upstream branch ismain.performProjectRefreshthen builds the keyowner/repo#mainand links whatever open PR hashead=main— here the "sync main into X" PR. Any workspace still trackingorigin/maingets glued to a default-branch-headed PR.The sidebar Review panel reads this authoritative link (
git.getPullRequest→workspace.pullRequestId), so the bad link written byPullRequestRuntimeManageris exactly what shows on screen.Fix (commit 1 —
fix(host-service))Guard link assignment: a workspace may only key on the base repo's default branch when its local branch actually is that default branch. When the resolved upstream branch equals the repo default but the local branch differs (and the upstream is the base repo), treat it as "no upstream PR". The default branch is derived from the
refs/remotes/<remote>/HEADsymref and cached per project.main(e.g. agh pr checkoutrename) still link — the guard is scoped to the base repo.upstreamKeycase-sensitivity is preserved.Unit tests added; each was verified to fail without the guard (mutation-tested): the origin/main-tracking workspace must not link to the head=main PR, the default-branch workspace must still link, and a fork PR head-named
mainmust still link.Secondary latent bug (commit 2 —
fix(desktop))useAccessibleV2Workspacesre-derived the workspace→PR link client-side for the workspaces list rows / hover cards using a fuzzyrepositoryId::branchmap — no head-SHA verification, no fork/owner qualifier, first-match-wins on a non-unique key. Two PRs sharing a head branch (main,patch-1) across forks mistracked, and the list could visibly disagree with the sidebar, which reads the authoritativepullRequestId.Fix: fan
getByWorkspacesout per host exactly asuseDashboardSidebarDatadoes to obtain the authoritative PR number per workspace, then key the rich collection row by the unique(repositoryId, prNumber)pair instead of the branch. The list and the sidebar now agree.Testing
bun test(host-service pull-requests): 27 passbun run typecheck: clean (35/35)bun run lint: exit 0Summary by cubic
Prevents workspaces from linking to default-branch-headed PRs (e.g., “sync main into X”), and switches the v2 workspaces list to the host’s authoritative workspace→PR link so the list and sidebar always agree.
host-service: Add a default-branch guard when deriving the workspace upstream key; only link on the base repo’s default branch if the local branch is that branch. Fork PRs with head namedmainstill link. Default branch is resolved via sharedresolveDefaultBranchName(origin/HEAD).desktop:useAccessibleV2Workspacesnow queriespullRequests.getByWorkspacesper host and keys PRs by(repositoryId, prNumber)instead ofrepositoryId::branch, fixing fork branch-name collisions and keeping the list in sync with the sidebar. Also stabilizes the PR-number map to reduce unnecessary re-renders.Written for commit 5920738. Summary will update on new commits.
Summary by CodeRabbit