Skip to content

fix(host-service): don't link workspaces to default-branch PRs - #5692

Merged
Kitenite merged 5 commits into
mainfrom
fix/pr-tracking-default-branch-mislink
Jul 15, 2026
Merged

Kitenite merged 5 commits into
mainfrom
fix/pr-tracking-default-branch-mislink

Conversation

@Kitenite

@Kitenite Kitenite commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

Problem

A workspace on branch roshvan/mcp-1703-mcp-surface-area showed 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 off main keeps tracking origin/main until its own branch is pushed (@{push} unconfigured), so the resolved upstream branch is main. performProjectRefresh then builds the key owner/repo#main and links whatever open PR has head=main — here the "sync main into X" PR. Any workspace still tracking origin/main gets glued to a default-branch-headed PR.

The sidebar Review panel reads this authoritative link (git.getPullRequest → workspace.pullRequestId), so the bad link written by PullRequestRuntimeManager is 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>/HEAD symref and cached per project.

  • Fork PRs whose head happens to be named main (e.g. a gh pr checkout rename) still link — the guard is scoped to the base repo.
  • The workspace whose local branch is the default branch still links correctly.
  • upstreamKey case-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 main must still link.

Secondary latent bug (commit 2 — fix(desktop))

useAccessibleV2Workspaces re-derived the workspace→PR link client-side for the workspaces list rows / hover cards using a fuzzy repositoryId::branch map — 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 authoritative pullRequestId.

Fix: fan getByWorkspaces out per host exactly as useDashboardSidebarData does 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 pass
  • bun run typecheck: clean (35/35)
  • bun run lint: exit 0

Open in Stage

Summary 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.

  • Bug Fixes
    • 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 named main still link. Default branch is resolved via shared resolveDefaultBranchName (origin/HEAD).
    • desktop: useAccessibleV2Workspaces now queries pullRequests.getByWorkspaces per host and keys PRs by (repositoryId, prNumber) instead of repositoryId::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.

Review in cubic

Summary by CodeRabbit

  • Bug Fixes
    • Improved pull request linking across workspaces using authoritative host-aware associations instead of branch-based inference.
    • Updated refresh/enrichment so workspace PR matching no longer relies on head branch data.
    • Added a default-branch guard to prevent incorrect links when an upstream tracks the repo default but the workspace’s local branch differs.
    • More reliably clears stale or mismatched pull request links, while preserving correct behavior for forks and local default branches.
  • Tests
    • Added default-branch guard coverage and improved test stubs/fixture parsing for deterministic refresh behavior.

Kitenite added 2 commits July 14, 2026 12:19
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.
@cursor

cursor Bot commented Jul 14, 2026

Copy link
Copy Markdown

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.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Pull request linkage

Layer / File(s) Summary
Default-branch-aware refresh and validation
packages/host-service/src/runtime/pull-requests/pull-requests.ts, packages/host-service/src/runtime/pull-requests/pull-requests.test.ts
Repository identity resolution detects default branches, refresh matching applies a default-branch guard, and tests cover local, upstream, and fork branch scenarios.
Authoritative desktop PR enrichment
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.ts
Workspace PR mappings are fetched from host services and matched using (repositoryId, prNumber) instead of (repositoryId, headBranch).

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
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly matches the main host-service bug fix, though it only covers one part of a broader PR.
Description check ✅ Passed It covers the problem, fix, and testing, but it omits the template's checklist section.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/pr-tracking-default-branch-mislink

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.

❤️ Share

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

@ghost

ghost commented Jul 14, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 3 individual chapters for you:

Title
1 Guard workspace linking on default branches
2 Test default-branch guard in host-service
3 Align desktop workspace list with authoritative links
Open in Stage

Chapters generated by Stage for commit 5920738 on Jul 15, 2026 6:19am UTC.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Ensure 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 when effectiveUpstreamKey suppressed it.
  • packages/host-service/src/runtime/pull-requests/pull-requests.test.ts#L655-L667: give the workspace and head=main PR 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 win

Move the shared query-target utility out of the sidebar subtree.

derivePullRequestQueryTargets now 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

📥 Commits

Reviewing files that changed from the base of the PR and between a225f5a and 0b39653.

📒 Files selected for processing (3)
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspaces/hooks/useAccessibleV2Workspaces/useAccessibleV2Workspaces.ts
  • packages/host-service/src/runtime/pull-requests/pull-requests.test.ts
  • packages/host-service/src/runtime/pull-requests/pull-requests.ts

@github-actions

github-actions Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch

Thank you for your contribution! 🎉

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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
Loading

Re-trigger cubic

@greptile-apps

greptile-apps Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes two related bugs in how workspaces are linked to pull requests. The primary fix (host-service) guards against workspaces that track origin/<default> being incorrectly linked to whatever open PR has head=<default>. The secondary fix (desktop) replaces a client-side repositoryId::headBranch lookup with authoritative per-host polling keyed by the unique (repositoryId, prNumber) pair.

  • pull-requests.ts: Adds effectiveUpstreamKey with a default-branch guard; resolveDefaultBranch reads refs/remotes/<remote>/HEAD and caches per process lifetime; fork PRs whose head happens to be named <default> are explicitly preserved.
  • pull-requests.test.ts: Three mutation-tested cases cover the guard; also fixes routeGh to correctly parse head=owner:branch for fork owners.
  • useAccessibleV2Workspaces.ts: Fans getByWorkspaces out per host, drops the first-match-wins headBranch map, and adds useStableWorkspacePrNumbers to absorb useQueries' per-render identity churn.

Confidence Score: 4/5

Safe 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.

Important Files Changed

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]
Loading
%%{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]
Loading

Comments Outside Diff (1)

  1. packages/host-service/src/runtime/pull-requests/pull-requests.ts, line 668-689 (link)

    P2 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.

    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

Comment on lines +219 to +236
// 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 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).
@Kitenite
Kitenite merged commit 04a8909 into main Jul 15, 2026
19 checks passed

This branch was previously deployed

1 inactive deployment
preview — 59207388 Deployed Jul 15, 2026 by Kitenite via Deploy API #6539
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant