TypeScript
fix(web): keep manual panel choices during a turn (#10113)
Theo Brownebccad270466a
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex 820d431db4f..f26f40dd2cd 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -14,7 +14,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"import type { Thread, ThreadShell, TurnDiffSummary } from "../types";import { deriveProviderInstanceEntries, NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";-import type { RightPanelSurface } from "../rightPanelStore";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import {+ type RightPanelSurface,+ pullRequestSurface,+ selectActiveRightPanelSurface,+ useRightPanelStore,+} from "../rightPanelStore";+import {+ selectThreadPreviewMiniPlayer,+ usePreviewMiniPlayerStore,+} from "../previewMiniPlayerStore";import {MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,@@ -39,6 +49,7 @@ import {resolveComposerInteractionMode,resolveComposerProviderSelection,resolveDraftPromotionNavigationTarget,+ observeProactivePanelUserChoice,resolveProactiveTurnDiffAction,resolveThreadMetadataUpdateForNextTurn,resolveSendEnvMode,@@ -95,6 +106,37 @@ describe("agent browser close confirmation", () => {});describe("floating browser preview", () => {+ it("keeps agent preview intent when a user selects its browser tab and then switches away", () => {+ useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });+ usePreviewMiniPlayerStore.setState({ byThreadKey: {} });+ const ref = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-1"));+ const panels = useRightPanelStore.getState();+ const revision = panels.getUserActionRevision(ref);+ usePreviewMiniPlayerStore.getState().open(ref, "agent-tab");+ panels.reconcileBrowserSurfaces(ref, ["agent-tab"]);+ const intent = selectThreadPreviewMiniPlayer(+ usePreviewMiniPlayerStore.getState().byThreadKey,+ ref,+ );+ const isFloating = () =>+ shouldRenderPreviewMiniPlayer(+ selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, ref)+ ?.tabId ?? null,+ selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, ref),+ );++ panels.openProactive(ref, { id: "diff", kind: "diff" }, revision);+ expect(isFloating()).toBe(true);+ panels.activateSurface(ref, "browser:agent-tab");+ expect(isFloating()).toBe(false);+ expect(panels.openProactive(ref, { id: "diff", kind: "diff" }, revision)).toBe(false);+ panels.open(ref, "diff");+ expect(isFloating()).toBe(true);+ expect(+ selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, ref),+ ).toBe(intent);+ });+it("only hides the duplicate while the same browser is rendered in the panel", () => {expect(shouldRenderPreviewMiniPlayer(null, null)).toBe(false);expect(@@ -116,6 +158,90 @@ describe("floating browser preview", () => {});describe("proactive panels", () => {+ it("keeps a manual PR selection made after following a replacement while loading", () => {+ useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });+ const ref = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-1"));+ const panels = useRightPanelStore.getState();+ const oldPr = pullRequestSurface({+ projectId: "project-1",+ repository: "owner/repo",+ number: 1,+ });+ const replacement = pullRequestSurface({ ...oldPr, number: 2 });+ const turnId = TurnId.make("turn-1");+ panels.openPullRequest(ref, oldPr);+ const loading = observeProactivePanelUserChoice(null, {+ threadKey: "env-1:thread-1",+ runningTurnId: turnId,+ userActionRevision: panels.getUserActionRevision(ref),+ });+ expect(panels.openProactive(ref, replacement, loading.userActionRevision)).toBe(true);++ panels.activateSurface(ref, oldPr.id);+ const loaded = observeProactivePanelUserChoice(loading, {+ threadKey: loading.threadKey,+ runningTurnId: turnId,+ userActionRevision: panels.getUserActionRevision(ref),+ });+ expect(panels.openProactive(ref, replacement, loaded.userActionRevision)).toBe(false);+ expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, ref)).toEqual(+ oldPr,+ );+ expect(shouldOpenProactivePullRequest(loaded.targetKey, "owner/repo:2")).toBe(false);+ expect(+ shouldOpenProactiveTurnDiff({+ previousRunningTurnId: loaded.runningTurnId,+ runningTurnId: null,+ settledTurnId: turnId,+ turnCompleted: true,+ }),+ ).toBe(false);+ });++ it.each(["idle", "loading", "observed"] as const)(+ "captures a new turn's choice once with initial state %s",+ (initialState) => {+ useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });+ const ref = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-1"));+ const panels = useRightPanelStore.getState();+ const firstTurn = TurnId.make("turn-1");+ const nextTurn = TurnId.make("turn-2");+ const initial = observeProactivePanelUserChoice(null, {+ threadKey: "env-1:thread-1",+ runningTurnId: initialState === "idle" ? null : firstTurn,+ userActionRevision: panels.getUserActionRevision(ref),+ });+ panels.openFile(ref, "src/first.ts");+ const loadingNextTurn = observeProactivePanelUserChoice(+ {+ ...initial,+ ...(initialState === "observed" ? { runningTurnId: firstTurn, targetKey: null } : {}),+ },+ {+ threadKey: initial.threadKey,+ runningTurnId: nextTurn,+ userActionRevision: panels.getUserActionRevision(ref),+ },+ );+ expect(+ panels.openProactive(ref, { id: "diff", kind: "diff" }, loadingNextTurn.userActionRevision),+ ).toBe(true);++ panels.openFile(ref, "src/second.ts");+ const loaded = observeProactivePanelUserChoice(loadingNextTurn, {+ threadKey: initial.threadKey,+ runningTurnId: nextTurn,+ userActionRevision: panels.getUserActionRevision(ref),+ });+ expect(+ panels.openProactive(ref, { id: "diff", kind: "diff" }, loaded.userActionRevision),+ ).toBe(false);+ expect(+ selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, ref)?.id,+ ).toBe("file:src/second.ts");+ },+ );+it("opens a pull request only after a newly observed link appears", () => {expect(shouldOpenProactivePullRequest(undefined, "project:repo:42")).toBe(false);expect(shouldOpenProactivePullRequest(null, "project:repo:42")).toBe(true);@@ -173,14 +299,12 @@ describe("proactive panels", () => {resolveProactiveTurnDiffAction({checkpoint: changedCheckpoint,isGitRepo: true,- activeSurfaceKind: null,}),).toBe("open");expect(resolveProactiveTurnDiffAction({checkpoint: unchangedCheckpoint,isGitRepo: true,- activeSurfaceKind: null,}),).toBe("ignore");});@@ -199,39 +323,21 @@ describe("proactive panels", () => {resolveProactiveTurnDiffAction({checkpoint: undefined,isGitRepo: true,- activeSurfaceKind: null,}),).toBe("defer");expect(resolveProactiveTurnDiffAction({checkpoint: missingCheckpoint,isGitRepo: true,- activeSurfaceKind: null,}),).toBe("defer");expect(resolveProactiveTurnDiffAction({checkpoint: changedCheckpoint,isGitRepo: undefined,- activeSurfaceKind: null,}),).toBe("defer");});-- it("keeps an active pull request above a completed turn diff", () => {- const changedCheckpoint = {- status: "ready",- files: [{ path: "src/app.ts", kind: "modified", additions: 1, deletions: 0 }],- } satisfies Pick<TurnDiffSummary, "status" | "files">;-- expect(- resolveProactiveTurnDiffAction({- checkpoint: changedCheckpoint,- isGitRepo: true,- activeSurfaceKind: "pull-request",- }),- ).toBe("ignore");- });});describe("toolGroupConsumesUpwardNavigation", () => {diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 1faeb74c986..08043bd1c6d 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -106,6 +106,32 @@ export function shouldOpenProactivePullRequest(return previousTargetKey !== undefined && targetKey !== null && targetKey !== previousTargetKey;}+interface ProactivePanelObservation {+ threadKey: string;+ runningTurnId: TurnId | null | undefined;+ targetKey: string | null | undefined;+ userActionTurnId: TurnId | null;+ userActionRevision: number;+}++/** Capture user intent before loading or metadata writes can defer panel activation. */+export function observeProactivePanelUserChoice(+ previous: ProactivePanelObservation | null,+ input: { threadKey: string; runningTurnId: TurnId | null; userActionRevision: number },+): ProactivePanelObservation {+ const sameThread = previous?.threadKey === input.threadKey;+ const newTurn =+ sameThread && input.runningTurnId !== null && input.runningTurnId !== previous.userActionTurnId;+ return {+ threadKey: input.threadKey,+ runningTurnId: sameThread ? previous.runningTurnId : undefined,+ targetKey: sameThread ? previous.targetKey : undefined,+ userActionTurnId: input.runningTurnId ?? (sameThread ? previous.userActionTurnId : null),+ userActionRevision:+ !sameThread || newTurn ? input.userActionRevision : previous.userActionRevision,+ };+}+export function shouldOpenProactiveTurnDiff(input: {previousRunningTurnId: TurnId | null | undefined;runningTurnId: TurnId | null;@@ -124,9 +150,7 @@ export function shouldOpenProactiveTurnDiff(input: {export function resolveProactiveTurnDiffAction(input: {checkpoint: Pick<TurnDiffSummary, "status" | "files"> | undefined;isGitRepo: boolean | undefined;- activeSurfaceKind: RightPanelSurface["kind"] | null;}): "defer" | "ignore" | "open" {- if (input.activeSurfaceKind === "pull-request") return "ignore";if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer";if (input.isGitRepo === undefined) return "defer";if (diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 3974837f5f2..e63c77c89e7 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -161,6 +161,7 @@ import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";import { useMediaQuery } from "../hooks/useMediaQuery";import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";import {+ pullRequestSurface,selectActiveRightPanel,selectActiveRightPanelSurface,selectThreadRightPanelState,@@ -396,6 +397,7 @@ import {resolveComposerInteractionMode,resolveComposerProviderSelection,resolveDraftHeroState,+ observeProactivePanelUserChoice,resolveProactiveTurnDiffAction,resolveThreadMetadataUpdateForNextTurn,resolveSendEnvMode,@@ -4060,23 +4062,6 @@ export default function ChatView(props: ChatViewProps) {const relinkKey = `${replacementLinkedThreadPullRequest.projectId}:${replacementLinkedThreadPullRequest.repository}#${replacementLinkedThreadPullRequest.number}`;if (threadPrRelinkKeysRef.current.get(activeThreadKey) === relinkKey) return;threadPrRelinkKeysRef.current.set(activeThreadKey, relinkKey);- const openSurface = selectActiveRightPanelSurface(- useRightPanelStore.getState().byThreadKey,- activeThreadRef,- );- if (- openSurface?.kind === "pull-request" &&- persistedLinkedThreadPullRequest !== null &&- openSurface.projectId === persistedLinkedThreadPullRequest.projectId &&- openSurface.repository.toLowerCase() ===- persistedLinkedThreadPullRequest.repository.toLowerCase() &&- openSurface.number === persistedLinkedThreadPullRequest.number- ) {- useRightPanelStore- .getState()- .openPullRequest(activeThreadRef, replacementLinkedThreadPullRequest);- }-threadPrRelinkWriteRef.current = threadPrRelinkWriteRef.current.then(async () => {if (threadPrRelinkKeysRef.current.get(activeThreadKey) !== relinkKey) return;const result = await updateThreadMetadata({@@ -4102,7 +4087,6 @@ export default function ChatView(props: ChatViewProps) {activeThreadKey,activeThreadRef,isServerThread,- persistedLinkedThreadPullRequest,replacementLinkedThreadPullRequest,updateThreadMetadata,]);@@ -4124,29 +4108,47 @@ export default function ChatView(props: ChatViewProps) {},[activeProject, activeProjectRepository, activeThreadRef, supportsPullRequests],);- const proactiveTurnObservationRef = useRef<{- threadKey: string;- runningTurnId: TurnId | null;- } | null>(null);- const proactivePullRequestObservationRef = useRef<{- threadKey: string;- targetKey: string | null;- } | null>(null);+ const proactivePanelObservationRef = useRef<ReturnType<+ typeof observeProactivePanelUserChoice+ > | null>(null);useEffect(() => {if (!isServerThread || activeThreadKey === null || activeThreadRef === null) {- proactiveTurnObservationRef.current = null;+ proactivePanelObservationRef.current = null;return;}- if (!clientSettingsHydrated || threadDetailLoading) {- return;+ const panels = useRightPanelStore.getState();+ const observation = observeProactivePanelUserChoice(proactivePanelObservationRef.current, {+ threadKey: activeThreadKey,+ runningTurnId: activeRunningTurnId,+ userActionRevision: panels.getUserActionRevision(activeThreadRef),+ });+ proactivePanelObservationRef.current = observation;+ const {+ runningTurnId: previousRunningTurnId,+ targetKey: previousTargetKey,+ userActionRevision,+ } = observation;+ const openSurface = selectActiveRightPanelSurface(panels.byThreadKey, activeThreadRef);+ const followSelectedPullRequest =+ replacementLinkedThreadPullRequest !== null &&+ openSurface?.kind === "pull-request" &&+ persistedLinkedThreadPullRequest !== null &&+ openSurface.projectId === persistedLinkedThreadPullRequest.projectId &&+ openSurface.repository.toLowerCase() ===+ persistedLinkedThreadPullRequest.repository.toLowerCase() &&+ openSurface.number === persistedLinkedThreadPullRequest.number;+ // Following the selected linked PR does not open an unrelated panel, so it+ // remains available with proactive panels off. It still respects a later choice.+ if (followSelectedPullRequest && replacementLinkedThreadPullRequest !== null) {+ panels.openProactive(+ activeThreadRef,+ pullRequestSurface(replacementLinkedThreadPullRequest),+ userActionRevision,+ );}+ if (!clientSettingsHydrated || threadDetailLoading) return;- const previousObservation = proactiveTurnObservationRef.current;- const observingSameThread = previousObservation?.threadKey === activeThreadKey;- const previousRunningTurnId = observingSameThread- ? previousObservation.runningTurnId- : undefined;const settledTurnId = latestTurnSettled ? (activeLatestTurn?.turnId ?? null) : null;const newlyCompletedTurnId = shouldOpenProactiveTurnDiff({previousRunningTurnId,@@ -4156,8 +4158,8 @@ export default function ChatView(props: ChatViewProps) {})? settledTurnId: null;- const eligibleCompletion =- settings.proactivePanelsEnabled && !shouldUseRightPanelSheet && newlyCompletedTurnId !== null;+ const proactivePanelsEnabled = settings.proactivePanelsEnabled && !shouldUseRightPanelSheet;+ const eligibleCompletion = proactivePanelsEnabled && newlyCompletedTurnId !== null;const completedCheckpoint = eligibleCompletion? activeThread?.checkpoints.find((checkpoint) => checkpoint.turnId === newlyCompletedTurnId): undefined;@@ -4165,17 +4167,36 @@ export default function ChatView(props: ChatViewProps) {? resolveProactiveTurnDiffAction({checkpoint: completedCheckpoint,isGitRepo: gitStatusQuery.data?.isRepo,- activeSurfaceKind: activeRightPanelSurface?.kind ?? null,}): "ignore";- proactiveTurnObservationRef.current = {- threadKey: activeThreadKey,+ const eligibleLink =+ proactivePanelsEnabled &&+ shouldOpenProactivePullRequest(previousTargetKey, linkedThreadPullRequestKey);+ const shouldDeferLink = eligibleLink && !pullRequestsCapabilityKnown;+ proactivePanelObservationRef.current = {+ ...observation,runningTurnId: diffAction === "defer" ? (previousRunningTurnId ?? null) : activeRunningTurnId,+ targetKey: shouldDeferLink ? (previousTargetKey ?? null) : linkedThreadPullRequestKey,};- if (diffAction !== "open" || newlyCompletedTurnId === null) return;+ if (+ !followSelectedPullRequest &&+ eligibleLink &&+ pullRequestsCapabilityKnown &&+ supportsPullRequests &&+ linkedThreadPullRequest !== null+ ) {+ panels.openProactive(+ activeThreadRef,+ pullRequestSurface(linkedThreadPullRequest),+ userActionRevision,+ );+ }+ if (diffAction !== "open" || newlyCompletedTurnId === null) return;+ if (!panels.openProactive(activeThreadRef, { id: "diff", kind: "diff" }, userActionRevision)) {+ return;+ }useDiffPanelStore.getState().selectTurn(activeThreadRef, newlyCompletedTurnId);- useRightPanelStore.getState().open(activeThreadRef, "diff");onDiffPanelOpen?.();}, [activeThread?.checkpoints,@@ -4184,56 +4205,16 @@ export default function ChatView(props: ChatViewProps) {activeRunningTurnId,activeThreadKey,activeThreadRef,- activeRightPanelSurface?.kind,clientSettingsHydrated,gitStatusQuery.data?.isRepo,isServerThread,latestTurnSettled,- onDiffPanelOpen,- settings.proactivePanelsEnabled,- shouldUseRightPanelSheet,- threadDetailLoading,- ]);-- useEffect(() => {- if (!isServerThread || activeThreadKey === null || activeThreadRef === null) {- proactivePullRequestObservationRef.current = null;- return;- }- if (!clientSettingsHydrated || threadDetailLoading) {- return;- }-- const previousObservation = proactivePullRequestObservationRef.current;- const observingSameThread = previousObservation?.threadKey === activeThreadKey;- const previousTargetKey = observingSameThread ? previousObservation.targetKey : undefined;- const newlyLinkedPullRequest = shouldOpenProactivePullRequest(- previousTargetKey,- linkedThreadPullRequestKey,- );- const eligibleLink =- settings.proactivePanelsEnabled && !shouldUseRightPanelSheet && newlyLinkedPullRequest;- const shouldOpenLink =- eligibleLink &&- pullRequestsCapabilityKnown &&- supportsPullRequests &&- linkedThreadPullRequest !== null;- const shouldDeferLink = eligibleLink && !pullRequestsCapabilityKnown;- proactivePullRequestObservationRef.current = {- threadKey: activeThreadKey,- targetKey: shouldDeferLink ? (previousTargetKey ?? null) : linkedThreadPullRequestKey,- };- if (!shouldOpenLink || linkedThreadPullRequest === null) return;-- useRightPanelStore.getState().openPullRequest(activeThreadRef, linkedThreadPullRequest);- }, [- activeThreadKey,- activeThreadRef,- clientSettingsHydrated,- isServerThread,linkedThreadPullRequest,linkedThreadPullRequestKey,+ onDiffPanelOpen,+ persistedLinkedThreadPullRequest,pullRequestsCapabilityKnown,+ replacementLinkedThreadPullRequest,settings.proactivePanelsEnabled,shouldUseRightPanelSheet,supportsPullRequests,diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.tsindex 7f981f2bcda..4336aa2a35e 100644--- a/apps/web/src/rightPanelStore.test.ts+++ b/apps/web/src/rightPanelStore.test.ts@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";import {migratePersistedRightPanelState,+ pullRequestSurface,pullRequestSurfaceId,selectActiveRightPanel,selectActiveRightPanelSurface,@@ -16,10 +17,114 @@ const refA = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-A"))const refB = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-B"));beforeEach(() => {- useRightPanelStore.setState({ byThreadKey: {} });+ useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });});describe("rightPanelStore", () => {+ const completedDiff = { id: "diff", kind: "diff" } as const;+ const linkedPullRequest = pullRequestSurface({+ projectId: "project-a",+ repository: "pingdotgg/t3code",+ number: 42,+ });++ it.each(["diff-first", "pull-request-first"])(+ "keeps the linked pull request above the completed diff with %s delivery",+ (order) => {+ const store = useRightPanelStore.getState();+ const revision = store.getUserActionRevision(refA);+ const requests =+ order === "diff-first"+ ? [completedDiff, linkedPullRequest]+ : [linkedPullRequest, completedDiff];+ for (const surface of requests) store.openProactive(refA, surface, revision);++ expect(+ selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA),+ ).toEqual(linkedPullRequest);++ store.open(refA, "diff");+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("diff");+ },+ );++ it.each([+ { choice: "file", choose: () => useRightPanelStore.getState().openFile(refA, "src/app.ts") },+ {+ choice: "pull request",+ choose: () =>+ useRightPanelStore.getState().openPullRequest(refA, { ...linkedPullRequest, number: 41 }),+ },+ { choice: "browser", choose: () => useRightPanelStore.getState().openBrowser(refA, "tab-a") },+ {+ choice: "terminal",+ choose: () => useRightPanelStore.getState().openTerminal(refA, "term-1"),+ },+ {+ choice: "same tab",+ choose: () => useRightPanelStore.getState().activateSurface(refA, "diff"),+ },+ { choice: "hide", choose: () => useRightPanelStore.getState().close(refA) },+ { choice: "toggle", choose: () => useRightPanelStore.getState().toggle(refA, "diff") },+ { choice: "close all", choose: () => useRightPanelStore.getState().closeAllSurfaces(refA) },+ {+ choice: "terminal close",+ choose: () => {+ const store = useRightPanelStore.getState();+ store.openTerminal(refA, "term-1");+ store.closeTerminal(refA, "terminal:term-1", "term-1");+ },+ },+ ])("keeps a later $choice choice when automatic requests arrive", ({ choose }) => {+ const store = useRightPanelStore.getState();+ store.open(refA, "diff");+ const revision = store.getUserActionRevision(refA);+ choose();+ const chosen = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);++ expect(store.openProactive(refA, completedDiff, revision)).toBe(false);+ expect(store.openProactive(refA, linkedPullRequest, revision)).toBe(false);+ expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toBe(+ chosen,+ );+ });++ it("allows automatic panels for a later turn after a manual choice", () => {+ const store = useRightPanelStore.getState();+ const firstTurnRevision = store.getUserActionRevision(refA);+ store.openFile(refA, "src/app.ts");+ expect(store.openProactive(refA, completedDiff, firstTurnRevision)).toBe(false);++ const nextTurnRevision = store.getUserActionRevision(refA);+ expect(store.openProactive(refA, completedDiff, nextTurnRevision)).toBe(true);+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("diff");+ });++ it("keeps manual choices scoped to their thread and environment", () => {+ const otherEnvironment = scopeThreadRef("env-2" as EnvironmentId, refA.threadId);+ const store = useRightPanelStore.getState();+ const revision = store.getUserActionRevision(refA);+ store.openFile(refB, "src/app.ts");+ store.openFile(otherEnvironment, "src/app.ts");++ expect(store.openProactive(refA, completedDiff, revision)).toBe(true);+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refB)).toBe("file");+ expect(+ selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, otherEnvironment),+ ).toBe("file");+ });++ it("does not treat resource reconciliation as a manual choice", () => {+ const store = useRightPanelStore.getState();+ store.openFile(refA, "src/app.ts");+ const revision = store.getUserActionRevision(refA);+ store.reconcileBrowserSurfaces(refA, ["agent-browser"]);+ store.reconcileFileSurfaces(refA, false);++ expect(store.openProactive(refA, completedDiff, revision)).toBe(true);+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("diff");+ });+it("drops the legacy singleton terminal surface during migration", () => {expect(migratePersistedRightPanelState({diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.tsindex 1173cae3ef3..acf673b042b 100644--- a/apps/web/src/rightPanelStore.ts+++ b/apps/web/src/rightPanelStore.ts@@ -88,6 +88,18 @@ export interface ThreadRightPanelState {interface RightPanelStoreState {byThreadKey: Record<string, ThreadRightPanelState>;+ /** Session-only count of user panel choices per thread. Automatic updates do not advance it. */+ userActionRevisionByThreadKey: Record<string, number>;+ getUserActionRevision: (ref: ScopedThreadRef) => number;+ /**+ * Open a surface on behalf of the app, not the user. Refused when the user+ * made a panel choice after `expectedUserActionRevision` was read.+ */+ openProactive: (+ ref: ScopedThreadRef,+ surface: Extract<RightPanelSurface, { kind: "diff" | "pull-request" }>,+ expectedUserActionRevision: number,+ ) => boolean;open: (ref: ScopedThreadRef,kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,@@ -193,7 +205,7 @@ export function pullRequestSurfaceId(target: {return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${encodeURIComponent(target.repository)}:${target.number}`;}-function pullRequestSurface(target: {+export function pullRequestSurface(target: {environmentId?: string;projectId: string;repository: string;@@ -237,6 +249,29 @@ const updateThread = (return { ...byThreadKey, [threadKey]: next };};+// Every store action is a user choice unless it goes through `automaticUpdate`.+// Only `openProactive` and resource reconciliation are automatic, so a new+// action counts as a user choice by default.+const automaticUpdate = (+ state: RightPanelStoreState,+ threadKey: string,+ updater: (current: ThreadRightPanelState) => ThreadRightPanelState,+): Partial<RightPanelStoreState> => ({+ byThreadKey: updateThread(state.byThreadKey, threadKey, updater),+});++const userAction = (+ state: RightPanelStoreState,+ threadKey: string,+ updater: (current: ThreadRightPanelState) => ThreadRightPanelState,+): Partial<RightPanelStoreState> => ({+ byThreadKey: updateThread(state.byThreadKey, threadKey, updater),+ userActionRevisionByThreadKey: {+ ...state.userActionRevisionByThreadKey,+ [threadKey]: (state.userActionRevisionByThreadKey[threadKey] ?? 0) + 1,+ },+});+function normalizeRevealLine(line: number | undefined): number | null {if (line === undefined || !Number.isFinite(line)) return null;return Math.max(1, Math.trunc(line));@@ -359,37 +394,62 @@ export function migratePersistedRightPanelState(persistedState: unknown): {export const useRightPanelStore = create<RightPanelStoreState>()(persist(- (set) => ({+ (set, get) => ({byThreadKey: {},+ userActionRevisionByThreadKey: {},+ getUserActionRevision: (ref) =>+ get().userActionRevisionByThreadKey[scopedThreadKey(ref)] ?? 0,+ openProactive: (ref, surface, expectedUserActionRevision) => {+ let opened = false;+ set((state) => {+ const threadKey = scopedThreadKey(ref);+ if (+ (state.userActionRevisionByThreadKey[threadKey] ?? 0) !== expectedUserActionRevision+ ) {+ return state;+ }+ // A linked PR takes priority over a completed-turn diff. Manual actions+ // always apply, and later user choices reject both proactive requests.+ if (+ surface.kind === "diff" &&+ selectActiveRightPanel(state.byThreadKey, ref) === "pull-request"+ ) {+ return state;+ }+ opened = true;+ return automaticUpdate(state, threadKey, (current) => upsertSurface(current, surface));+ });+ return opened;+ },open: (ref, kind) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {if (kind === "preview") {const existing = current.surfaces.find((surface) => surface.kind === "preview");return upsertSurface(current, existing ?? browserSurface(null));}return upsertSurface(current, singletonSurface(kind));}),- })),+ ),openBrowser: (ref, tabId) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {const surface = browserSurface(tabId);const withoutPlaceholder = tabId? current.surfaces.filter((entry) => entry.id !== "browser:new"): current.surfaces;return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);}),- })),+ ),openPullRequest: (ref, target) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {return upsertSurface(current, pullRequestSurface(target));}),- })),+ ),openFile: (ref, relativePath, line) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {const withoutStandaloneExplorer = current.surfaces.filter((surface) => surface.kind !== "files",);@@ -413,10 +473,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(: [...withoutStandaloneExplorer, surface],};}),- })),+ ),openAttachment: (ref, attachment) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {const withoutStandaloneExplorer = current.surfaces.filter((surface) => surface.kind !== "files",);@@ -425,16 +485,16 @@ export const useRightPanelStore = create<RightPanelStoreState>()(attachmentSurface(attachment),);}),- })),+ ),openTerminal: (ref, terminalId) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) =>upsertSurface(current, terminalSurface(terminalId)),),- })),+ ),splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => ({...current,isOpen: true,activeSurfaceId: surfaceId,@@ -451,10 +511,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(};}),})),- })),+ ),activateTerminal: (ref, surfaceId, terminalId) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => ({...current,activeSurfaceId: surfaceId,surfaces: current.surfaces.map((surface) =>@@ -465,10 +525,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(: surface,),})),- })),+ ),closeTerminal: (ref, surfaceId, terminalId) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {const surface = current.surfaces.find((entry) => entry.id === surfaceId && entry.kind === "terminal",);@@ -504,18 +564,18 @@ export const useRightPanelStore = create<RightPanelStoreState>()(),};}),- })),+ ),activateSurface: (ref, surfaceId) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) =>current.surfaces.some((surface) => surface.id === surfaceId)? { ...current, isOpen: true, activeSurfaceId: surfaceId }: current,),- })),+ ),closeSurface: (ref, surfaceId) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);if (index < 0) return current;const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);@@ -530,10 +590,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(activeSurfaceId: fallback?.id ?? null,};}),- })),+ ),closeOtherSurfaces: (ref, surfaceId) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {const surface = current.surfaces.find((entry) => entry.id === surfaceId);if (!surface || current.surfaces.length === 1) return current;return {@@ -543,10 +603,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(activeSurfaceId: surface.id,};}),- })),+ ),closeSurfacesToRight: (ref, surfaceId) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);if (index < 0 || index === current.surfaces.length - 1) return current;const surfaces = current.surfaces.slice(0, index + 1);@@ -559,18 +619,18 @@ export const useRightPanelStore = create<RightPanelStoreState>()(activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,};}),- })),+ ),closeAllSurfaces: (ref) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) =>current.surfaces.length === 0? current: { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },),- })),+ ),reconcileBrowserSurfaces: (ref, tabIds) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ automaticUpdate(state, scopedThreadKey(ref), (current) => {const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");const existingBrowser = current.surfaces.filter(@@ -596,10 +656,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(: (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),};}),- })),+ ),reconcileFileSurfaces: (ref, workspaceAvailable) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ automaticUpdate(state, scopedThreadKey(ref), (current) => {if (workspaceAvailable) return current;const surfaces = current.surfaces.filter((surface) =>@@ -619,29 +679,29 @@ export const useRightPanelStore = create<RightPanelStoreState>()(: (surfaces.at(-1)?.id ?? null),};}),- })),+ ),show: (ref) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) =>current.isOpen ? current : { ...current, isOpen: true },),- })),+ ),close: (ref) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) =>current.isOpen ? { ...current, isOpen: false } : current,),- })),+ ),toggleVisibility: (ref) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => ({...current,isOpen: !current.isOpen,})),- })),+ ),toggle: (ref, kind) =>- set((state) => ({- byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {const active = current.surfaces.find((surface) => surface.id === current.activeSurfaceId,);@@ -654,13 +714,20 @@ export const useRightPanelStore = create<RightPanelStoreState>()(}return upsertSurface(current, singletonSurface(kind));}),- })),+ ),removeThread: (ref) =>set((state) => {const threadKey = scopedThreadKey(ref);- if (!(threadKey in state.byThreadKey)) return state;+ if (+ !(threadKey in state.byThreadKey) &&+ !(threadKey in state.userActionRevisionByThreadKey)+ ) {+ return state;+ }const { [threadKey]: _removed, ...rest } = state.byThreadKey;- return { byThreadKey: rest };+ const { [threadKey]: _revision, ...userActionRevisionByThreadKey } =+ state.userActionRevisionByThreadKey;+ return { byThreadKey: rest, userActionRevisionByThreadKey };}),}),{