← reports

#6771 · PR visibility changes React hook order

BugPriority: LowEffort: Lowui · github · confirmed-reproGitHub issue

2026-10-31 · trusted main 916d684ac23d0b0de82c09cfc7553a50287d2188

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

The GitHub PR Status plugin changes the sequence of React hooks when its show setting finishes loading or is toggled. Its visibility hook skips the thread-context hook while the setting is unavailable or disabled, then calls it after the setting becomes enabled. A focused test of the actual plugin hook emits React's hook-order warning on unchanged trusted main. The same agent repeated that failure in a second clean checkout. Calling the context hook unconditionally removes the warning without changing which PR segment is visible.

2. Claims vs findings

ClaimFindingEvidence
Settings resolution changes the hook order.VerifiedBoth fresh test processes report useRef becoming useContext at hook position 1 after settings resolve.
The defect is in the upstream GitHub PR visibility path.VerifiedOnly upstream main plus a newly authored regression test was executed; no downstream plugins or runtime data were used.
The compiler emits specific memo-cache size mismatches.UnverifiedThe focused reproduction does not run the React Compiler. It proves the underlying hook-order defect, not the reported cache sizes.
The problem is limited to console warnings.Verified only in this harnessAll visibility assertions complete; the test fails on the unexpected console error. Broader production impact was not measured.

3. Environment

4. Minimal reproduction

  1. Clone the public repository and select the trusted base:
    git clone --branch main https://github.com/get-bb/bb.git bb-repro
    cd bb-repro
    git checkout 916d684ac23d0b0de82c09cfc7553a50287d2188
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk
  2. Save the regression-only patch below as regression.diff, then apply and run it:
    git apply regression.diff
    pnpm exec turbo run test --force --filter=bb-plugin-bb--github-pr-status -- ui/PullRequestContextSegment.test.tsx -t 'keeps hook order stable as settings load and toggle'
  3. The test mounts the real visibility hook with settings initially unavailable, enables it, disables it, then enables it again. It checks false → true → false → true visibility and the absence of React errors. The existing SDK context stub is upgraded to call real React useContext, matching the production hook's primitive.

Expected: the regression passes without a console error. Actual on unchanged production code: exit 1; visibility assertions pass, but the final no-console-error assertion fails:

React has detected a change in the order of Hooks called by TestComponent.

   Previous render            Next render
   ------------------------------------------------------
1. useRef                     useContext

expected "error" to not be called at all, but actually been called 1 times

Test Files  1 failed (1)
     Tests  1 failed | 23 skipped (24)
Complete regression patch, including its test and hook-aware fixture
diff --git a/plugins/github-pr-status/ui/PullRequestContextSegment.test.tsx b/plugins/github-pr-status/ui/PullRequestContextSegment.test.tsx
index 88ed86f84d..72059b87d3 100644
--- a/plugins/github-pr-status/ui/PullRequestContextSegment.test.tsx
+++ b/plugins/github-pr-status/ui/PullRequestContextSegment.test.tsx
@@ -24,20 +24,26 @@ const sdk = vi.hoisted(() => ({
   threadContextKind: "banner" as "banner" | "card",
 }));
 
-vi.mock("@get-bb/plugin-sdk/app", () => ({
-  experimental_useRpcKeyedQuery: () => ({
-    data: sdk.rows,
-    error: null,
-    refetch: async () => {},
-  }),
-  experimental_useRpcMutation: () => ({
-    mutate: sdk.mutate,
-    isPending: sdk.isPending,
-  }),
-  useBbNavigate: () => ({ openUrl: () => false }),
-  useSettings: () => ({ values: sdk.settings, isLoading: false }),
-  experimental_useThreadContextKind: () => sdk.threadContextKind,
-}));
+vi.mock("@get-bb/plugin-sdk/app", async () => {
+  const { createContext, useContext } = await import("react");
+  const threadContext = createContext(sdk);
+  return {
+    experimental_useRpcKeyedQuery: () => ({
+      data: sdk.rows,
+      error: null,
+      refetch: async () => {},
+    }),
+    experimental_useRpcMutation: () => ({
+      mutate: sdk.mutate,
+      isPending: sdk.isPending,
+    }),
+    useBbNavigate: () => ({ openUrl: () => false }),
+    useSettings: () => ({ values: sdk.settings, isLoading: false }),
+    experimental_useThreadContextKind: function useThreadContextKind() {
+      return useContext(threadContext).threadContextKind;
+    },
+  };
+});
 
 vi.mock("sonner", () => ({
   toast: { loading: vi.fn(), success: vi.fn(), error: vi.fn() },
@@ -104,6 +110,7 @@ function renderPart(
 
 afterEach(() => {
   cleanup();
+  vi.restoreAllMocks();
   sdk.rows = {};
   sdk.settings = { showPullRequest: true };
   sdk.isPending = false;
@@ -113,6 +120,33 @@ afterEach(() => {
 });
 
 describe("pull request context segment", () => {
+  it("keeps hook order stable as settings load and toggle", () => {
+    show(PULL_REQUEST);
+    sdk.settings = undefined;
+    const errors = vi.spyOn(console, "error");
+    const { result, rerender } = renderHook(() =>
+      usePullRequestSegmentVisible({
+        threadId: "thr_1",
+        projectId: "proj_1",
+        environment: { id: "env_1" },
+      }),
+    );
+    expect(result.current).toBe(false);
+
+    sdk.settings = { showPullRequest: true };
+    rerender();
+    expect(result.current).toBe(true);
+
+    sdk.settings = { showPullRequest: false };
+    rerender();
+    expect(result.current).toBe(false);
+
+    sdk.settings = { showPullRequest: true };
+    rerender();
+    expect(result.current).toBe(true);
+    expect(errors).not.toHaveBeenCalled();
+  });
+
   it("shows only when the thread's environment has a pull request", () => {
     show(PULL_REQUEST);
     const input = { threadId: "thr_1", projectId: "proj_1" };

5. Root cause

The visibility hook combines the setting and a hook invocation using a short-circuiting expression. When the setting is unavailable or false, React never sees the context read. When it becomes true, React sees an extra context hook before the existing query lifecycle hooks.

const enabled = useSettings().values?.[SHOW_PULL_REQUEST_SETTING] === true;
const show = enabled && experimental_useThreadContextKind() === "banner";
return useThreadPullRequest(show ? input.environment : null) !== null;

The actual context-kind implementation calls usePaneState, which calls React useContext. The core Visibility component invokes the registered plugin hook in its own render, explaining why a live warning can name Visibility rather than the plugin function.

Existing tests mount separate instances with different setting values, but never rerender the same instance across settings changes. Their former context stub was a plain value getter, so it could not expose a React hook-order violation.

6. Proposed fix and proof

Read context kind unconditionally and apply the boolean gate only to its result. Retain the current query gating so disabled or card-mode segments do not request an environment PR. The production repair is two added lines and one deleted line. Including the regression test and fixture update, the change is 65 text lines across two files in one existing plugin subsystem, with no dependencies, generated files, persistence changes, public contracts, or release changes.

const enabled = useSettings().values?.[SHOW_PULL_REQUEST_SETTING] === true;
const contextKind = experimental_useThreadContextKind();
const show = enabled && contextKind === "banner";

After that repair, the focused test passes. The final complete plugin suite passes 183 tests in 10 files, along with typechecking and lint:

pnpm exec turbo run test typecheck lint --filter=bb-plugin-bb--github-pr-status

Test Files  10 passed (10)
     Tests  183 passed (183)
     Tasks: 10 successful, 10 total

pnpm exec oxfmt --check plugins/github-pr-status/ui/PullRequestContextSegment.tsx plugins/github-pr-status/ui/PullRequestContextSegment.test.tsx
git diff --check
git diff --numstat origin/main

7. Verification: second clean checkout

The same agent created a second, distinct clean temporary checkout detached at the trusted base. After a new frozen install and SDK preparation, only the regression-test changes were applied; the production file stayed byte-for-byte at main. The reproduction command in section 4 was repeated with --force, forcing actual execution rather than a Turbo cache replay. It again exited 1 with exactly one React hook-order error and the same failing no-console-error assertion. This is a repeat check by the same agent, not independent verification. No report correction was needed after that second run.

8. Related issues and PRs

No open PR linked to this issue was present in GitHub's connected/cross-referenced issue events or the scoped open-PR search before the fix. A scoped search for the plugin found no duplicate of this hook-order defect. No linked PR code was checked out or executed.

9. Appendix and limits