TypeScript
fix(web): remember the pull request tab when switching threads (#18823)
SamuelBarnholdtadda1db10ca1
diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsxindex d8f512726de..1940a0bf80a 100644--- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx+++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx@@ -130,7 +130,7 @@ export function RightPanelSurfaceContent(props: {<PullRequestDetailPanelgetShortcutContext={props.getShortcutContext}shortcutsEnabled={visible && props.activeSurfaceId === surface.id}- key={`${surface.host ?? ""}:${surface.repository}#${surface.number}`}+ key={`${scopedThreadKey(threadRef)}:${surface.id}`}environmentId={props.environmentId}onSelectPullRequest={(reference) => {useRightPanelStore.getState().openPullRequest(threadRef, {@@ -147,6 +147,10 @@ export function RightPanelSurfaceContent(props: {repository: surface.repository,number: surface.number,}}+ initialTab={surface.detailTab ?? "summary"}+ onTabChange={(tab) => {+ useRightPanelStore.getState().setPullRequestDetailTab(threadRef, surface.id, tab);+ }}context={pullRequestPanelContext({projectId: pullRequest.projectId,diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsxindex 4e847e9cc7c..45cff9bc6c3 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx@@ -15,6 +15,8 @@ import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { page, userEvent } from "vite-plus/test/browser";import { DraftId, useComposerDraftStore } from "~/composerDraftStore";+import { selectActiveRightPanelSurface, useRightPanelStore } from "~/rightPanelStore";+import { RightPanelSurfaceContent } from "../chat/RightPanelSurfaceContent";import "~/index.css";@@ -259,6 +261,7 @@ beforeEach(() => {vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);currentDetail = detail;useComposerDraftStore.setState({ draftsByThreadKey: {} });+ useRightPanelStore.setState({ byThreadKey: {} });usePullRequestReviewStore.setState({ drafts: {}, summaries: {} });hostCommand.mockReset();newThread@@ -542,6 +545,94 @@ it("folds the title only for the active tab's own scroller", async () => {await vi.waitFor(() => expect(titleFold()).toBe(true));});+it("restores the selected PR tab when switching threads and remounting the right panel", async () => {+ const otherThread = { ...threadRef, threadId: ThreadId.make("thread-2") };+ useRightPanelStore.getState().openPullRequest(threadRef, surface);+ useRightPanelStore.getState().openPullRequest(otherThread, surface);+ const codeTab = () => page.getByRole("button", { name: "Expand all files", exact: true });+ const container = document.createElement("div");+ container.className = "flex h-[700px] w-[900px]";+ document.body.append(container);+ const root = createRoot(container);+ roots.push(root);+ const show = (ref: ScopedThreadRef) => {+ const selected = selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, ref);+ return act(async () => {+ root.render(+ <RightPanelSurfaceContent+ surface={selected}+ activeSurfaceId={selected?.id ?? null}+ threadRef={ref}+ environmentId={ref.environmentId}+ visible+ composerDraftTarget={ref}+ keybindings={[]}+ configuredPreviewUrls={[]}+ workspaceMutationId={null}+ getShortcutContext={shortcutContext}+ onSendAnnotation={() => {}}+ onCloseSurface={() => {}}+ terminal={{+ launchContext: null,+ focusRequestId: 0,+ keybindings: [],+ onAddTerminalContext: () => {},+ onSplitTerminal: () => {},+ onSplitTerminalVertical: () => {},+ onNewTerminal: () => {},+ onActiveTerminalChange: () => {},+ onCloseTerminal: () => {},+ }}+ pullRequest={{+ capabilityKnown: true,+ supported: true,+ projectId: detail.projectId,+ pullRequests: [],+ linkedPullRequest: null,+ branchPullRequest: null,+ onBack: undefined,+ }}+ files={{+ projectName: null,+ workspaceRoot: undefined,+ availableEditors: [],+ pendingSurfaceIds: new Set(),+ onOpenFile: () => {},+ onPendingChange: () => {},+ }}+ />,+ );+ });+ };++ await show(threadRef);+ await expect.element(page.getByTestId("summary-scroller")).toBeVisible();+ await tab("Code").click();+ await expect.element(codeTab()).toBeVisible();+ await show(otherThread);+ await expect.element(page.getByTestId("summary-scroller")).toBeVisible();+ await show(threadRef);+ await expect.element(codeTab()).toBeVisible();++ useRightPanelStore+ .getState()+ .openPullRequest(threadRef, { ...surface, projectId: "other-project" });+ await show(threadRef);+ await expect.element(page.getByTestId("summary-scroller")).toBeVisible();+ useRightPanelStore.getState().openPullRequest(threadRef, surface);+ await show(threadRef);+ await expect.element(codeTab()).toBeVisible();++ await act(async () => root.render(null));+ useRightPanelStore.getState().openPullRequest(threadRef, { ...surface, url: detail.url });+ await show(threadRef);+ await expect.element(codeTab()).toBeVisible();+ await tab("Summary").click();+ await show(otherThread);+ await show(threadRef);+ await expect.element(page.getByTestId("summary-scroller")).toBeVisible();+});+it("stays collapsed at the bottom after native scroll clamping and reopens at the top", async () => {await render();const title = page.getByRole("heading", { level: 1, name: "Test pull request" });diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 2bb75bcada8..b7980dd0c8f 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -65,7 +65,7 @@ import {} from "react";import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";-import { useRightPanelStore } from "~/rightPanelStore";+import { type PullRequestDetailTab, useRightPanelStore } from "~/rightPanelStore";import { useEnvironmentSettings } from "~/hooks/useSettings";import { useNewThreadHandler } from "~/hooks/useHandleNewThread";import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";@@ -196,8 +196,6 @@ import { guideRunKey, useGuideRunStore } from "./guide/guideRunStore";import { useReviewGuideWriter } from "./guide/useReviewGuideWriter";import { useInlineActionConfirm } from "./useInlineActionConfirm";-type DetailTab = "summary" | "guide" | "timeline" | "code";-const ACTION_FAILURE_LABELS: Record<PullRequestAction, string> = {merge: "Could not merge this pull request",ready: "Could not mark this ready for review",@@ -237,7 +235,7 @@ const ACTION_FAILURE_HINTS: Record<PullRequestAction, string> = {const UPDATE_BRANCH_REBASE_FAILURE_HINT ="The host refused it. A rebase stops at the first commit that does not apply cleanly; updating with a merge commit may still work.";-const TABS: ReadonlyArray<{ value: DetailTab; label: string }> = [+const TABS: ReadonlyArray<{ value: PullRequestDetailTab; label: string }> = [{ value: "summary", label: "Summary" },{ value: "guide", label: "Guide" },{ value: "timeline", label: "Timeline" },@@ -587,6 +585,8 @@ export function PullRequestDetailPanel({onBack,onSelectPullRequest,onGuideShown,+ initialTab = "summary",+ onTabChange,}: {environmentId: EnvironmentId;shortcutsEnabled: boolean;@@ -602,6 +602,8 @@ export function PullRequestDetailPanel({composerDraftTarget?: ScopedThreadRef | DraftId;onBack?: (() => void) | undefined;onGuideShown?: (() => void) | undefined;+ initialTab?: PullRequestDetailTab;+ onTabChange?: ((tab: PullRequestDetailTab) => void) | undefined;}) {const environmentConfigs = useServerConfigs();const projects = useProjects();@@ -634,7 +636,11 @@ export function PullRequestDetailPanel({: null;const [threadPickerOpen, setThreadPickerOpen] = useState(false);const [openReviewRequest, setOpenReviewRequest] = useState(0);- const [tab, setTab] = useState<DetailTab>("summary");+ const [tab, setTab] = useState<PullRequestDetailTab>(initialTab);+ const selectTab = (next: PullRequestDetailTab) => {+ setTab(next);+ onTabChange?.(next);+ };const [timelineOrder, setTimelineOrder] = useState<"newest" | "oldest">("newest");const [codeCommitScope, setCodeCommitScope] = useState<{readonly pullRequestKey: string;@@ -647,7 +653,7 @@ export function PullRequestDetailPanel({};const openCommit = (oid: string) => {selectCodeCommit(oid);- setTab("code");+ selectTab("code");};const [codeRevealRequest, setCodeRevealRequest] = useState<{readonly path: string;@@ -657,32 +663,36 @@ export function PullRequestDetailPanel({selectCodeCommit(null);setCodeRevealRequest((previous) => ({ path, nonce: (previous?.nonce ?? 0) + 1 }));void loadCodeTab();- setTab("code");+ selectTab("code");};const guideOpenRequested = useGuideRunStore((state) => state.openRequestKey === guideRunKey(environmentId, reference),);if (guideOpenRequested && tab !== "guide") setTab("guide");useEffect(() => {- if (guideOpenRequested) useGuideRunStore.getState().requestOpen(null);- }, [guideOpenRequested]);+ if (!guideOpenRequested) return;+ useGuideRunStore.getState().requestOpen(null);+ onTabChange?.("guide");+ }, [guideOpenRequested, onTabChange]);const tabScopeKey = `${environmentId}:${pullRequestKey}`;const [tabMountState, setTabMountState] = useState(() => ({key: tabScopeKey,- tabs: new Set<DetailTab>(["summary"]),+ tabs: new Set<PullRequestDetailTab>([tab]),}));// A previously visited Code tab must not fetch diffs for every later PR while hidden.const mountedTabs =- tabMountState.key === tabScopeKey ? tabMountState.tabs : new Set<DetailTab>([tab]);+ tabMountState.key === tabScopeKey ? tabMountState.tabs : new Set<PullRequestDetailTab>([tab]);if (tabMountState.key !== tabScopeKey) {setTabMountState({ key: tabScopeKey, tabs: new Set([tab]) });} else if (!tabMountState.tabs.has(tab)) {setTabMountState({ key: tabScopeKey, tabs: new Set(tabMountState.tabs).add(tab) });}// Each tab restores the condensed state its own scrolling left behind.- const [condensedByTab, setCondensedByTab] = useState<Partial<Record<DetailTab, boolean>>>({});+ const [condensedByTab, setCondensedByTab] = useState<+ Partial<Record<PullRequestDetailTab, boolean>>+ >({});const condensed = condensedByTab[tab] ?? false;- const scrollerByTab = useRef<Partial<Record<DetailTab, HTMLDivElement | null>>>({});+ const scrollerByTab = useRef<Partial<Record<PullRequestDetailTab, HTMLDivElement | null>>>({});// Fresh ref callbacks would detach and reattach every scroller on each render.const [scrollerRefs] = useState(() => ({summary: (node: HTMLDivElement | null) => {@@ -700,7 +710,7 @@ export function PullRequestDetailPanel({// Save the target before collapse: the browser may clamp scrollTop as the viewport grows,// so applying a delta afterward would compensate twice.const compensationRef = useRef<{- tab: DetailTab;+ tab: PullRequestDetailTab;scroller: HTMLDivElement;target: number;} | null>(null);@@ -1043,7 +1053,7 @@ export function PullRequestDetailPanel({});const writeGuide = () => {void guideWriter.write();- if (guideWriter.data?.guide == null) setTab("guide");+ if (guideWriter.data?.guide == null) selectTab("guide");};const writeTaskToComposer = (target: ScopedThreadRef | DraftId, task: ThreadTask) => {@@ -1439,6 +1449,7 @@ export function PullRequestDetailPanel({(item.value !== "code" || detail === null || detail.capabilities.diff) &&(item.value !== "guide" || reviewGuidesEnabled),);+ // Keep unavailable-tab fallbacks out of the saved selection.if (!visibleTabs.some((item) => item.value === tab)) setTab("summary");const can = (action: PullRequestAction) =>detail?.capabilities.actions.includes(action) === true &&@@ -2605,7 +2616,7 @@ export function PullRequestDetailPanel({<PullRequestDetailTabBartabs={visibleTabs}value={tab}- onValueChange={setTab}+ onValueChange={selectTab}onTabIntent={(item) => {if (item === "code") void loadCodeTab();}}diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.tsindex 300f0e4f252..ccc91aadd18 100644--- a/apps/web/src/rightPanelStore.test.ts+++ b/apps/web/src/rightPanelStore.test.ts@@ -3,6 +3,7 @@ import { type EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";import { beforeEach, describe, expect, it } from "vite-plus/test";import { useClosedViewStore } from "./closedViewStore";+import { reopenClosedView } from "./reopenClosedView";import {migratePersistedRightPanelState,pullRequestSurface,@@ -1245,6 +1246,62 @@ describe("rightPanelStore", () => {expect(state.surfaces[1]).not.toHaveProperty("url");});+ it("restores each environment, thread and PR surface's detail tab after reload and URL reopen", async () => {+ const pr = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 };+ const otherPr = { ...pr, projectId: "project-b" };+ const otherEnvironment = scopeThreadRef("env-2" as EnvironmentId, refA.threadId);+ const selections = [+ [refA, pr, "code"],+ [refB, pr, "guide"],+ [otherEnvironment, pr, "timeline"],+ [refA, otherPr, "summary"],+ ] as const;+ const store = useRightPanelStore.getState();+ for (const [ref, reference, tab] of selections) {+ store.openPullRequest(ref, reference);+ store.setPullRequestDetailTab(ref, pullRequestSurfaceId(reference), "guide");+ store.setPullRequestDetailTab(ref, pullRequestSurfaceId(reference), tab);+ }++ store.openPullRequest(refA, pr);+ const revision = store.getUserActionRevision(refA);+ store.setPullRequestDetailTab(refA, pullRequestSurfaceId(pr), "timeline");+ expect(store.openProactive(refA, linkedPullRequest, revision)).toBe(true);+ expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual(+ linkedPullRequest,+ );+ store.setPullRequestDetailTab(refA, pullRequestSurfaceId(pr), "code");++ const { storage, name } = useRightPanelStore.persist.getOptions();+ const saved = await storage!.getItem(name!);+ expect(saved).not.toBeNull();+ useRightPanelStore.setState({ byThreadKey: {} });+ await storage!.setItem(name!, saved!);+ await useRightPanelStore.persist.rehydrate();++ for (const [ref, reference, tab] of selections) {+ store.openPullRequest(ref, {+ ...reference,+ url: `https://github.com/${reference.repository}/pull/${reference.number}`,+ });+ const active = selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, ref);+ expect(active?.id).toBe(pullRequestSurfaceId(reference));+ expect(active?.kind === "pull-request" && (active.detailTab ?? "summary")).toBe(tab);+ store.closeSurface(ref, active!.id);+ await reopenClosedView(useClosedViewStore.getState().entries[0]!, {+ workspaceAvailable: true,+ openPreview: () => {+ throw new Error("A PR tab must not create a browser session");+ },+ });+ const reopened = selectActiveRightPanelSurface(+ useRightPanelStore.getState().byThreadKey,+ ref,+ );+ expect(reopened?.kind === "pull-request" && (reopened.detailTab ?? "summary")).toBe(tab);+ }+ });+it("keeps matching repository and number on different hosts as separate tabs", () => {const first = { projectId: "project-a", repository: "acme/api", number: 7, host: "github.com" };const second = { ...first, host: "github.example.com" };diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.tsindex 8fceb2f4da9..85e34b88895 100644--- a/apps/web/src/rightPanelStore.ts+++ b/apps/web/src/rightPanelStore.ts@@ -24,6 +24,8 @@ const RIGHT_PANEL_KINDS = [] as const;export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];+export type PullRequestDetailTab = "summary" | "guide" | "timeline" | "code";+export interface DeviceTabTarget {hostId: string;deviceId: string;@@ -76,6 +78,7 @@ export type RightPanelSurface =repository: string;number: number;url?: string;+ detailTab?: PullRequestDetailTab;}| { id: "pull-requests"; kind: "pull-requests" };@@ -155,8 +158,14 @@ interface RightPanelStoreState {repository: string;number: number;url?: string;+ detailTab?: PullRequestDetailTab;},) => void;+ setPullRequestDetailTab: (+ ref: ScopedThreadRef,+ surfaceId: string,+ detailTab: PullRequestDetailTab,+ ) => void;openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;splitTerminal: (ref: ScopedThreadRef,@@ -277,6 +286,7 @@ export function pullRequestSurface(target: {repository: string;number: number;url?: string;+ detailTab?: PullRequestDetailTab;}): PullRequestSurface {return {id: pullRequestSurfaceId(target),@@ -287,6 +297,7 @@ export function pullRequestSurface(target: {repository: target.repository,number: target.number,...(typeof target.url === "string" ? { url: target.url } : {}),+ ...(target.detailTab === undefined ? {} : { detailTab: target.detailTab }),};}@@ -704,12 +715,31 @@ export const useRightPanelStore = create<RightPanelStoreState>()(? {...next,surfaces: next.surfaces.map((entry) =>- entry.id === surface.id ? surface : entry,+ entry.id === surface.id && entry.kind === "pull-request"+ ? { ...entry, ...surface }+ : entry,),}: next;}),),+ setPullRequestDetailTab: (ref, surfaceId, detailTab) =>+ set((state) => {+ const threadKey = scopedThreadKey(ref);+ const existing = state.byThreadKey[threadKey]?.surfaces.find(+ (surface) => surface.id === surfaceId,+ );+ if (existing?.kind !== "pull-request" || (existing.detailTab ?? "summary") === detailTab)+ return state;+ return automaticUpdate(state, threadKey, (current) => ({+ ...current,+ surfaces: current.surfaces.map((surface) =>+ surface.id === surfaceId && surface.kind === "pull-request"+ ? { ...surface, detailTab }+ : surface,+ ),+ }));+ }),openFile: (ref, requestedPath, line) =>set((state) =>userAction(state, scopedThreadKey(ref), (current) => {