Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

rightPanelStore.ts

1,156 lines45.4 KB

1/**
2 * Thread-scoped right-panel surface state.
3 *
4 * This is intentionally a shallow workspace model: it owns an ordered set of
5 * surface descriptors and the active surface, while each feature continues to
6 * own its durable resource state. Browser surfaces point at preview tab ids,
7 * terminal surfaces point at terminal session ids, file surfaces point at
8 * workspace paths, and diff/files remain singleton surfaces.
9 */
10import {
11 parseScopedThreadKey,
12 scopedThreadKey,
13 scopeThreadRef,
14} from "@t3tools/client-runtime/environment";
15import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
16import { create } from "zustand";
17import { createJSONStorage, persist } from "zustand/middleware";
18​
19import { useClosedViewStore } from "./closedViewStore";
20import { resolveStorage } from "./lib/storage";
21import type { ThreadPanelPresentation } from "./rightPanelLayout";
22import type { ChatFileAttachment } from "./types";
23​
24const RIGHT_PANEL_KINDS = [
25 "diff",
26 "files",
27 "file",
28 "preview",
29 "device",
30 "terminal",
31 "pull-request",
32 "pull-requests",
33] as const;
34export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
35​
36export interface DeviceTabTarget {
37 hostId: string;
38 deviceId: string;
39 platform: "ios" | "android";
40 name: string;
42​
43export type RightPanelSurface =
44 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
45 | { id: "browser:new"; kind: "preview"; resourceId: null }
46 | { id: "device" | `device:${string}`; kind: "device"; target?: DeviceTabTarget; title?: string }
47 | {
48 id: `terminal:${string}`;
49 kind: "terminal";
50 resourceId: string;
51 terminalIds: string[];
52 activeTerminalId: string;
53 splitDirection?: "horizontal" | "vertical";
54 }
55 | { id: "diff"; kind: "diff" }
56 | { id: "files"; kind: "files" }
57 | {
58 id: `file:${string}` | `attachment:${string}`;
59 kind: "file";
60 /** Workspace-relative, or absolute for a host file outside the workspace. */
61 relativePath: string;
62 revealLine: number | null;
63 revealRequestId: number;
64 /** Present when the file lives in the thread's attachment store rather
65 than at a workspace or host path. */
66 attachment?: ChatFileAttachment;
67 }
68 | {
69 /**
70 * A change request opened beside a thread or in the pull-request list's shared panel.
71 * The reference lives in the id so several pull requests can remain open as peer tabs.
72 */
73 id: `pull-request:${string}`;
74 kind: "pull-request";
75 /**
76 * Which server the change request was read from. The list spans every connected one, so
77 * two of them can hold the same project id; a panel beside a thread leaves this out and
78 * takes the environment from its own ref.
79 */
80 environmentId?: string;
81 projectId: string;
82 host?: string;
83 repository: string;
84 number: number;
85 url?: string;
86 }
87 /** The thread's linked pull requests, one singleton tab beside any number of `pull-request` tabs. */
88 | { id: "pull-requests"; kind: "pull-requests" };
89​
90const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
91// v9 removed the "plan" surface kind (plans render inline in the transcript).
92// v10 keys pull-request surfaces by reference instead of a singleton tab.
93// v11 stops persisting the pull-request list's shared panel, so a restart opens the page fresh.
94// v12 adds the device surface.
95// v14 removes the agents surface; lineage lives in the thread title bar.
96const RIGHT_PANEL_STORAGE_VERSION = 14;
97​
98/** A fixed workspace-level ref: each PR surface carries its own real environment. */
99export const PULL_REQUESTS_PANEL_REF = scopeThreadRef(
100 EnvironmentId.make("pull-requests-panel"),
101 ThreadId.make("pull-requests-panel"),
102);
103​
104/**
105 * The pull-request list's shared panel is session
106 * state: reopening the app should show the list, not last session's tabs and detail fetches.
107 */
108const isPullRequestsPanelKey = (threadKey: string) => threadKey.endsWith(":pull-requests-panel");
109​
110export interface ThreadRightPanelState {
111 isOpen: boolean;
112 activeSurfaceId: string | null;
113 surfaces: RightPanelSurface[];
114 dismissedDeviceSurfaceIds?: string[];
115 /** Kept with the thread so the layout survives a ChatView remount or a reload. */
116 maximized?: true;
118​
119export interface ThreadPanelVisibility {
120 inlineOpen: boolean;
121 popoverOpen: boolean;
123​
124interface RightPanelStoreState {
125 byThreadKey: Record<string, ThreadRightPanelState>;
126 /**
127 * A thread whose right panel should open maximized the next time it shows,
128 * such as one started for a link the OS opened. Its view consumes it once.
129 */
130 pendingMaximizeThreadKey: string | null;
131 requestMaximize: (ref: ScopedThreadRef) => void;
132 consumeMaximizeRequest: (ref: ScopedThreadRef) => boolean;
133 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
134 /** Session-only count of user panel choices per thread. Automatic updates do not advance it. */
135 userActionRevisionByThreadKey: Record<string, number>;
136 closeRevisionByThreadKey: Record<string, number>;
137 getUserActionRevision: (ref: ScopedThreadRef) => number;
138 /**
139 * Open a surface on behalf of the app, not the user. Refused when the user
140 * made a panel choice after `expectedUserActionRevision` was read.
141 */
142 openProactive: (
143 ref: ScopedThreadRef,
144 surface: Extract<RightPanelSurface, { kind: "diff" | "pull-request" | "pull-requests" }>,
145 expectedUserActionRevision: number,
146 ) => boolean;
147 open: (
148 ref: ScopedThreadRef,
149 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
150 ) => void;
151 openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void;
152 renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;
153 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
154 openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
155 openAttachment: (ref: ScopedThreadRef, attachment: ChatFileAttachment) => void;
156 openPullRequest: (
157 ref: ScopedThreadRef,
158 target: {
159 environmentId?: string;
160 projectId: string;
161 host?: string;
162 repository: string;
163 number: number;
164 url?: string;
165 },
166 ) => void;
167 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
168 splitTerminal: (
169 ref: ScopedThreadRef,
170 surfaceId: string,
171 terminalId: string,
172 direction?: "horizontal" | "vertical",
173 ) => void;
174 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
175 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
176 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
177 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
178 closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
179 closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
180 closeAllSurfaces: (ref: ScopedThreadRef) => void;
181 moveSurface: (ref: ScopedThreadRef, surfaceId: string, toIndex: number) => void;
182 reconcileBrowserSurfaces: (
183 ref: ScopedThreadRef,
184 tabIds: readonly string[],
185 hiddenTabIds?: ReadonlySet<string>,
186 ) => void;
187 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
188 show: (ref: ScopedThreadRef) => void;
189 close: (ref: ScopedThreadRef) => void;
190 setMaximized: (ref: ScopedThreadRef, maximized: boolean) => void;
191 toggleVisibility: (ref: ScopedThreadRef) => void;
192 toggle: (
193 ref: ScopedThreadRef,
194 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
195 ) => void;
196 setThreadPanelOpen: (
197 ref: ScopedThreadRef,
198 presentation: ThreadPanelPresentation,
199 open: boolean,
200 ) => void;
201 toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
202 removeThread: (ref: ScopedThreadRef) => void;
204​
205const EMPTY_THREAD_STATE: ThreadRightPanelState = {
206 isOpen: false,
207 activeSurfaceId: null,
208 surfaces: [],
209};
210​
211const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
212 inlineOpen: true,
213 popoverOpen: false,
214};
215​
216const singletonSurface = (
217 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request">,
218): RightPanelSurface => {
219 switch (kind) {
220 case "diff":
221 return { id: "diff", kind };
222 case "files":
223 return { id: "files", kind };
224 case "pull-requests":
225 return { id: "pull-requests", kind };
226 case "device":
227 return { id: "device", kind };
228 }
229};
230​
231const browserSurface = (tabId: string | null): RightPanelSurface =>
232 tabId
233 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
234 : { id: "browser:new", kind: "preview", resourceId: null };
235​
236const fileSurface = (
237 relativePath: string,
238 revealLine: number | null,
239 revealRequestId: number,
240): RightPanelSurface => ({
241 id: `file:${relativePath}`,
242 kind: "file",
243 relativePath,
244 revealLine,
245 revealRequestId,
246});
247​
248const attachmentSurface = (attachment: ChatFileAttachment): RightPanelSurface => ({
249 id: `attachment:${attachment.id}`,
250 kind: "file",
251 relativePath: attachment.name,
252 revealLine: null,
253 revealRequestId: 0,
254 attachment,
255});
256​
257const terminalSurface = (terminalId: string): RightPanelSurface => ({
258 id: `terminal:${terminalId}`,
259 kind: "terminal",
260 resourceId: terminalId,
261 terminalIds: [terminalId],
262 activeTerminalId: terminalId,
263});
264​
265export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-request" }>;
266​
267export function pullRequestSurfaceId(target: {
268 environmentId?: string;
269 projectId: string;
270 host?: string;
271 repository: string;
272 number: number;
273}): PullRequestSurface["id"] {
274 // The environment leads the id where there is one, so the same change request read from two
275 // servers is two tabs rather than one tab that changes its mind about which server it is on.
276 const scope =
277 target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
278 const host = target.host === undefined ? "" : `${encodeURIComponent(target.host.toLowerCase())}:`;
279 return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${host}${encodeURIComponent(target.repository)}:${target.number}`;
281​
282export function pullRequestSurface(target: {
283 environmentId?: string;
284 projectId: string;
285 host?: string;
286 repository: string;
287 number: number;
288 url?: string;
289}): PullRequestSurface {
290 return {
291 id: pullRequestSurfaceId(target),
292 kind: "pull-request",
293 ...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
294 projectId: target.projectId,
295 ...(typeof target.host === "string" ? { host: target.host.toLowerCase() } : {}),
296 repository: target.repository,
297 number: target.number,
298 ...(typeof target.url === "string" ? { url: target.url } : {}),
299 };
301​
302const upsertSurface = (
303 current: ThreadRightPanelState,
304 surface: RightPanelSurface,
305 activate = true,
306): ThreadRightPanelState => ({
307 ...current,
308 isOpen: true,
309 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
310 ? current.surfaces
311 : [...current.surfaces, surface],
312 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
313});
314​
315const updateThreadStateMap = (
316 byThreadKey: Record<string, ThreadRightPanelState>,
317 threadKey: string,
318 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
319): Record<string, ThreadRightPanelState> => {
320 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
321 const next = updater(current);
322 if (
323 !next.isOpen &&
324 next.activeSurfaceId === null &&
325 next.surfaces.length === 0 &&
326 !next.dismissedDeviceSurfaceIds?.length
327 ) {
328 if (!(threadKey in byThreadKey)) return byThreadKey;
329 const { [threadKey]: _removed, ...rest } = byThreadKey;
330 return rest;
331 }
332 if (next === current) return byThreadKey;
333 return { ...byThreadKey, [threadKey]: next };
334};
335​
336const updateThreadPanelVisibilityMap = (
337 byThreadKey: Record<string, ThreadPanelVisibility>,
338 threadKey: string,
339 updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
340): Record<string, ThreadPanelVisibility> => {
341 const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
342 const next = updater(current);
343 if (next.inlineOpen && !next.popoverOpen) {
344 if (!(threadKey in byThreadKey)) return byThreadKey;
345 const { [threadKey]: _removed, ...rest } = byThreadKey;
346 return rest;
347 }
348 if (next === current) return byThreadKey;
349 return { ...byThreadKey, [threadKey]: next };
350};
351​
352type RightPanelStoreData = Pick<
353 RightPanelStoreState,
354 "byThreadKey" | "threadPanelVisibilityByThreadKey"
355>;
356​
357/**
358 * Applies a real right-panel mutation and its thread-panel transition atomically.
359 * This is the only path real panel actions use, so visibility never has to be
360 * reconciled after the fact in React.
361 */
362const updateThread = (
363 state: RightPanelStoreData,
364 threadKey: string,
365 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
366): RightPanelStoreData => {
367 const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
368 const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
369 const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
370 let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
371​
372 if (!current.isOpen && next.isOpen) {
373 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
374 threadPanelVisibilityByThreadKey,
375 threadKey,
376 (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
377 );
378 } else if (current.isOpen && !next.isOpen) {
379 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
380 threadPanelVisibilityByThreadKey,
381 threadKey,
382 (visibility) =>
383 visibility.popoverOpen && !visibility.inlineOpen
384 ? { ...visibility, inlineOpen: true }
385 : visibility,
386 );
387 }
388​
389 return { byThreadKey, threadPanelVisibilityByThreadKey };
390};
391​
392// Every store action is a user choice unless it goes through `automaticUpdate`.
393// Only `openProactive` and resource reconciliation are automatic, so a new
394// action counts as a user choice by default.
395const automaticUpdate = (
396 state: RightPanelStoreState,
397 threadKey: string,
398 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
399): Partial<RightPanelStoreState> => ({
400 ...updateThread(state, threadKey, updater),
401});
402​
403const userAction = (
404 state: RightPanelStoreState,
405 threadKey: string,
406 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
407 closesView = false,
408): Partial<RightPanelStoreState> => ({
409 ...updateThread(state, threadKey, (current) => {
410 const next = updater(current);
411 if (next === current) return current;
412 const removedDevices = current.surfaces.filter(
413 (surface) =>
414 surface.kind === "device" && !next.surfaces.some((entry) => entry.id === surface.id),
415 );
416 if (removedDevices.length === 0) return next;
417 return {
418 ...next,
419 dismissedDeviceSurfaceIds: [
420 ...new Set([
421 ...(next.dismissedDeviceSurfaceIds ?? []),
422 ...removedDevices.map((surface) => surface.id),
423 ]),
424 ],
425 };
426 }),
427 userActionRevisionByThreadKey: {
428 ...state.userActionRevisionByThreadKey,
429 [threadKey]: (state.userActionRevisionByThreadKey[threadKey] ?? 0) + 1,
430 },
431 ...(closesView
432 ? {
433 closeRevisionByThreadKey: {
434 ...state.closeRevisionByThreadKey,
435 [threadKey]: (state.closeRevisionByThreadKey[threadKey] ?? 0) + 1,
436 },
437 }
438 : {}),
439});
440​
441const closeAction = (
442 state: RightPanelStoreState,
443 threadKey: string,
444 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
445): Partial<RightPanelStoreState> => userAction(state, threadKey, updater, true);
446​
447function normalizeRevealLine(line: number | undefined): number | null {
448 if (line === undefined || !Number.isFinite(line)) return null;
449 return Math.max(1, Math.trunc(line));
451​
452export function migratePersistedRightPanelState(persistedState: unknown): {
453 byThreadKey: Record<string, ThreadRightPanelState>;
454 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
455} {
456 if (!persistedState || typeof persistedState !== "object") {
457 return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
458 }
459 const byThreadKey =
460 "byThreadKey" in persistedState &&
461 persistedState.byThreadKey &&
462 typeof persistedState.byThreadKey === "object"
463 ? Object.fromEntries(
464 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>)
465 .filter(([threadKey]) => !isPullRequestsPanelKey(threadKey))
466 .map(([threadKey, threadState]) => {
467 const validThreadState =
468 threadState && typeof threadState === "object" ? threadState : null;
469 const surfaces = Array.isArray(validThreadState?.surfaces)
470 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
471 // Removed surfaces: plans render inline, agents in thread lineage.
472 const kind = (surface as { kind?: string }).kind;
473 if (kind === "plan" || kind === "agents") return [];
474 if (surface.kind === "file") {
475 const revealLine =
476 typeof surface.revealLine === "number" &&
477 Number.isFinite(surface.revealLine)
478 ? Math.max(1, Math.trunc(surface.revealLine))
479 : null;
480 const revealRequestId =
481 typeof surface.revealRequestId === "number" &&
482 Number.isSafeInteger(surface.revealRequestId) &&
483 surface.revealRequestId >= 0
484 ? surface.revealRequestId
485 : 0;
486 return [{ ...surface, revealLine, revealRequestId }];
487 }
488 if (surface.kind === "pull-request") {
489 if (
490 typeof surface.projectId !== "string" ||
491 typeof surface.repository !== "string" ||
492 typeof surface.number !== "number" ||
493 !Number.isSafeInteger(surface.number) ||
494 surface.number < 1
495 ) {
496 return [];
497 }
498 const { environmentId, ...rest } = surface;
499 // Anything else stored under that name is not an environment.
500 return [
501 pullRequestSurface({
502 ...rest,
503 ...(typeof environmentId === "string" ? { environmentId } : {}),
504 }),
505 ];
506 }
507 if (surface.kind !== "terminal") return [surface];
508 if (
509 !("resourceId" in surface) ||
510 typeof surface.resourceId !== "string" ||
511 surface.id !== `terminal:${surface.resourceId}`
512 ) {
513 return [];
514 }
515 const terminalIds =
516 "terminalIds" in surface && Array.isArray(surface.terminalIds)
517 ? [
518 ...new Set(
519 surface.terminalIds.filter(
520 (terminalId): terminalId is string =>
521 typeof terminalId === "string",
522 ),
523 ),
524 ]
525 : [surface.resourceId];
526 const activeTerminalId =
527 "activeTerminalId" in surface &&
528 typeof surface.activeTerminalId === "string" &&
529 terminalIds.includes(surface.activeTerminalId)
530 ? surface.activeTerminalId
531 : (terminalIds[0] ?? surface.resourceId);
532 return [
533 {
534 ...surface,
535 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
536 activeTerminalId,
537 },
538 ];
539 })
540 : [];
541 const rawActiveSurfaceId = validThreadState?.activeSurfaceId;
542 const persistedActiveSurfaceId = surfaces.some(
543 (surface) => surface.id === rawActiveSurfaceId,
544 )
545 ? (rawActiveSurfaceId ?? null)
546 : rawActiveSurfaceId === "pull-request"
547 ? (surfaces.find((surface) => surface.kind === "pull-request")?.id ?? null)
548 : null;
549 // A migration that dropped every surface (e.g. plan-only panels
550 // in v9) must not reopen an empty panel.
551 const isOpen =
552 surfaces.length > 0 &&
553 (typeof validThreadState?.isOpen === "boolean"
554 ? validThreadState.isOpen
555 : persistedActiveSurfaceId !== null);
556 // An open panel needs an active surface: if migration dropped
557 // the persisted one (e.g. plan was active), fall back to the
558 // first survivor instead of rendering an open empty panel. Removed
559 // agents selections also keep a survivor ready while the panel is closed.
560 const activeSurfaceId =
561 persistedActiveSurfaceId ??
562 (isOpen || rawActiveSurfaceId === "agents" ? (surfaces[0]?.id ?? null) : null);
563 return [
564 threadKey,
565 {
566 isOpen,
567 surfaces,
568 activeSurfaceId,
569 ...(Array.isArray(validThreadState?.dismissedDeviceSurfaceIds)
570 ? {
571 dismissedDeviceSurfaceIds:
572 validThreadState.dismissedDeviceSurfaceIds.filter(
573 (id): id is string => typeof id === "string",
574 ),
575 }
576 : {}),
577 ...(validThreadState?.maximized === true ? { maximized: true as const } : {}),
578 },
579 ];
580 }),
581 )
582 : {};
583 const threadPanelVisibilityByThreadKey =
584 "threadPanelVisibilityByThreadKey" in persistedState &&
585 persistedState.threadPanelVisibilityByThreadKey &&
586 typeof persistedState.threadPanelVisibilityByThreadKey === "object"
587 ? Object.fromEntries(
588 Object.entries(
589 persistedState.threadPanelVisibilityByThreadKey as Record<string, unknown>,
590 ).flatMap(([threadKey, value]) => {
591 if (!value || typeof value !== "object" || !("inlineOpen" in value)) return [];
592 return value.inlineOpen === false
593 ? [[threadKey, { inlineOpen: false, popoverOpen: false }]]
594 : [];
595 }),
596 )
597 : {};
598 return { byThreadKey, threadPanelVisibilityByThreadKey };
600​
601export const useRightPanelStore = create<RightPanelStoreState>()(
602 persist(
603 (set, get) => ({
604 byThreadKey: {},
605 pendingMaximizeThreadKey: null,
606 requestMaximize: (ref) => set({ pendingMaximizeThreadKey: scopedThreadKey(ref) }),
607 consumeMaximizeRequest: (ref) => {
608 if (get().pendingMaximizeThreadKey !== scopedThreadKey(ref)) return false;
609 set({ pendingMaximizeThreadKey: null });
610 return true;
611 },
612 threadPanelVisibilityByThreadKey: {},
613 userActionRevisionByThreadKey: {},
614 closeRevisionByThreadKey: {},
615 getUserActionRevision: (ref) =>
616 get().userActionRevisionByThreadKey[scopedThreadKey(ref)] ?? 0,
617 openProactive: (ref, surface, expectedUserActionRevision) => {
618 let opened = false;
619 set((state) => {
620 const threadKey = scopedThreadKey(ref);
621 if (
622 (state.userActionRevisionByThreadKey[threadKey] ?? 0) !== expectedUserActionRevision
623 ) {
624 return state;
625 }
626 // A linked PR takes priority over a completed-turn diff. Manual actions
627 // always apply, and later user choices reject both proactive requests.
628 if (
629 surface.kind === "diff" &&
630 (selectActiveRightPanel(state.byThreadKey, ref) === "pull-request" ||
631 selectActiveRightPanel(state.byThreadKey, ref) === "pull-requests")
632 ) {
633 return state;
634 }
635 opened = true;
636 return automaticUpdate(state, threadKey, (current) => upsertSurface(current, surface));
637 });
638 return opened;
639 },
640 open: (ref, kind) =>
641 set((state) =>
642 userAction(state, scopedThreadKey(ref), (current) => {
643 if (kind === "preview") {
644 const existing = current.surfaces.find((surface) => surface.kind === "preview");
645 return upsertSurface(current, existing ?? browserSurface(null));
646 }
647 return upsertSurface(current, singletonSurface(kind));
648 }),
649 ),
650 openDevice: (ref, target, automatic = false) =>
651 set((state) =>
652 (automatic ? automaticUpdate : userAction)(state, scopedThreadKey(ref), (current) => {
653 const id =
654 `device:${encodeURIComponent(target.hostId)}:${encodeURIComponent(target.deviceId)}` as const;
655 if (automatic && current.dismissedDeviceSurfaceIds?.includes(id)) return current;
656 const surface: RightPanelSurface = { id, kind: "device", target };
657 const existing = current.surfaces.find((entry) => entry.id === id);
658 const surfaces = existing
659 ? current.surfaces.filter((entry) => entry.id !== "device")
660 : current.surfaces.map((entry) => (entry.id === "device" ? surface : entry));
661 return upsertSurface(
662 {
663 ...current,
664 surfaces,
665 dismissedDeviceSurfaceIds: (current.dismissedDeviceSurfaceIds ?? []).filter(
666 (entry) => entry !== id,
667 ),
668 },
669 existing ?? surface,
670 );
671 }),
672 ),
673 renameDevice: (ref, surfaceId, title) =>
674 set((state) =>
675 userAction(state, scopedThreadKey(ref), (current) => ({
676 ...current,
677 surfaces: current.surfaces.map((surface) =>
678 surface.id === surfaceId && surface.kind === "device"
679 ? { ...surface, title: title.trim() || surface.target?.name || "Device" }
680 : surface,
681 ),
682 })),
683 ),
684 openBrowser: (ref, tabId) =>
685 set((state) =>
686 userAction(state, scopedThreadKey(ref), (current) => {
687 const surface = browserSurface(tabId);
688 const withoutPlaceholder = tabId
689 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
690 : current.surfaces;
691 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
692 }),
693 ),
694 openPullRequest: (ref, target) =>
695 set((state) =>
696 userAction(state, scopedThreadKey(ref), (current) => {
697 const surface = pullRequestSurface(target);
698 const next = upsertSurface(current, surface);
699 return target.url
700 ? {
701 ...next,
702 surfaces: next.surfaces.map((entry) =>
703 entry.id === surface.id ? surface : entry,
704 ),
705 }
706 : next;
707 }),
708 ),
709 openFile: (ref, requestedPath, line) =>
710 set((state) =>
711 userAction(state, scopedThreadKey(ref), (current) => {
712 if (requestedPath === ".") {
713 return upsertSurface(current, singletonSurface("files"));
714 }
715 // Workspace entry paths use '/', including on Windows.
716 const relativePath = /^[A-Za-z]:\/+$/.test(requestedPath)
717 ? requestedPath
718 : requestedPath.replace(/\/+$/, "") || requestedPath;
719 const withoutStandaloneExplorer = current.surfaces.filter(
720 (surface) => surface.kind !== "files",
721 );
722 const surfaceId = `file:${relativePath}` as const;
723 const existing = withoutStandaloneExplorer.find(
724 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
725 surface.id === surfaceId && surface.kind === "file",
726 );
727 const surface = fileSurface(
728 relativePath,
729 normalizeRevealLine(line),
730 (existing?.revealRequestId ?? 0) + 1,
731 );
732 return {
733 ...current,
734 isOpen: true,
735 activeSurfaceId: surface.id,
736 surfaces: existing
737 ? withoutStandaloneExplorer.map((entry) =>
738 entry.id === surface.id ? surface : entry,
739 )
740 : [...withoutStandaloneExplorer, surface],
741 };
742 }),
743 ),
744 openAttachment: (ref, attachment) =>
745 set((state) =>
746 userAction(state, scopedThreadKey(ref), (current) => {
747 const withoutStandaloneExplorer = current.surfaces.filter(
748 (surface) => surface.kind !== "files",
749 );
750 return upsertSurface(
751 { ...current, surfaces: withoutStandaloneExplorer },
752 attachmentSurface(attachment),
753 );
754 }),
755 ),
756 openTerminal: (ref, terminalId) =>
757 set((state) =>
758 userAction(state, scopedThreadKey(ref), (current) =>
759 upsertSurface(current, terminalSurface(terminalId)),
760 ),
761 ),
762 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
763 set((state) =>
764 userAction(state, scopedThreadKey(ref), (current) => ({
765 ...current,
766 isOpen: true,
767 activeSurfaceId: surfaceId,
768 surfaces: current.surfaces.map((surface) => {
769 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
770 const { splitDirection: _splitDirection, ...baseSurface } = surface;
771 return {
772 ...baseSurface,
773 terminalIds: surface.terminalIds.includes(terminalId)
774 ? surface.terminalIds
775 : [...surface.terminalIds, terminalId],
776 activeTerminalId: terminalId,
777 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
778 };
779 }),
780 })),
781 ),
782 activateTerminal: (ref, surfaceId, terminalId) =>
783 set((state) =>
784 userAction(state, scopedThreadKey(ref), (current) => ({
785 ...current,
786 activeSurfaceId: surfaceId,
787 surfaces: current.surfaces.map((surface) =>
788 surface.id === surfaceId &&
789 surface.kind === "terminal" &&
790 surface.terminalIds.includes(terminalId)
791 ? { ...surface, activeTerminalId: terminalId }
792 : surface,
793 ),
794 })),
795 ),
796 closeTerminal: (ref, surfaceId, terminalId) =>
797 set((state) =>
798 closeAction(state, scopedThreadKey(ref), (current) => {
799 const surface = current.surfaces.find(
800 (entry) => entry.id === surfaceId && entry.kind === "terminal",
801 );
802 if (!surface || surface.kind !== "terminal") return current;
803 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
804 if (terminalIds.length === 0) {
805 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
806 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
807 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
808 return {
809 ...current,
810 isOpen: surfaces.length > 0 && current.isOpen,
811 surfaces,
812 activeSurfaceId:
813 current.activeSurfaceId === surfaceId
814 ? (fallback?.id ?? null)
815 : current.activeSurfaceId,
816 };
817 }
818 return {
819 ...current,
820 surfaces: current.surfaces.map((entry) =>
821 entry.id === surfaceId && entry.kind === "terminal"
822 ? {
823 ...entry,
824 terminalIds,
825 activeTerminalId:
826 entry.activeTerminalId === terminalId
827 ? (terminalIds.at(-1) ?? terminalIds[0]!)
828 : entry.activeTerminalId,
829 }
830 : entry,
831 ),
832 };
833 }),
834 ),
835 activateSurface: (ref, surfaceId) =>
836 set((state) =>
837 userAction(state, scopedThreadKey(ref), (current) =>
838 current.surfaces.some((surface) => surface.id === surfaceId)
839 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
840 : current,
841 ),
842 ),
843 closeSurface: (ref, surfaceId) =>
844 set((state) =>
845 closeAction(state, scopedThreadKey(ref), (current) => {
846 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
847 if (index < 0) return current;
848 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
849 const next = {
850 ...current,
851 isOpen: surfaces.length > 0 && current.isOpen,
852 surfaces,
853 };
854 if (current.activeSurfaceId !== surfaceId) {
855 return next;
856 }
857 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
858 return {
859 ...next,
860 activeSurfaceId: fallback?.id ?? null,
861 };
862 }),
863 ),
864 closeOtherSurfaces: (ref, surfaceId) =>
865 set((state) =>
866 closeAction(state, scopedThreadKey(ref), (current) => {
867 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
868 if (!surface || current.surfaces.length === 1) return current;
869 return {
870 ...current,
871 isOpen: true,
872 surfaces: [surface],
873 activeSurfaceId: surface.id,
874 };
875 }),
876 ),
877 closeSurfacesToRight: (ref, surfaceId) =>
878 set((state) =>
879 closeAction(state, scopedThreadKey(ref), (current) => {
880 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
881 if (index < 0 || index === current.surfaces.length - 1) return current;
882 const surfaces = current.surfaces.slice(0, index + 1);
883 const activeStillExists = surfaces.some(
884 (surface) => surface.id === current.activeSurfaceId,
885 );
886 return {
887 ...current,
888 surfaces,
889 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
890 };
891 }),
892 ),
893 closeAllSurfaces: (ref) =>
894 set((state) =>
895 closeAction(state, scopedThreadKey(ref), (current) =>
896 current.surfaces.length === 0
897 ? current
898 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
899 ),
900 ),
901 // Reordering is not a choice about what the panel shows, so it leaves the
902 // user-action revision alone and proactive opens still apply.
903 moveSurface: (ref, surfaceId, toIndex) =>
904 set((state) =>
905 updateThread(state, scopedThreadKey(ref), (current) => {
906 const fromIndex = current.surfaces.findIndex((surface) => surface.id === surfaceId);
907 if (fromIndex < 0 || fromIndex === toIndex) return current;
908 const surfaces = [...current.surfaces];
909 surfaces.splice(toIndex, 0, ...surfaces.splice(fromIndex, 1));
910 return { ...current, surfaces };
911 }),
912 ),
913 reconcileBrowserSurfaces: (ref, tabIds, hiddenTabIds) =>
914 set((state) =>
915 automaticUpdate(state, scopedThreadKey(ref), (current) => {
916 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
917 // Filtered in place so browser tabs keep the order the user dragged them into.
918 const kept = current.surfaces.filter(
919 (surface) =>
920 surface.kind !== "preview" ||
921 (surface.id !== "browser:new" && validIds.has(surface.id)),
922 );
923 const knownIds = new Set(kept.map((surface) => surface.id));
924 const added = tabIds
925 .filter((tabId) => !knownIds.has(`browser:${tabId}`) && !hiddenTabIds?.has(tabId))
926 .map((tabId) => browserSurface(tabId));
927 const surfaces = [...kept, ...added];
928 const activeStillExists = surfaces.some(
929 (surface) => surface.id === current.activeSurfaceId,
930 );
931 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
932 return {
933 ...current,
934 surfaces,
935 activeSurfaceId: activeStillExists
936 ? current.activeSurfaceId
937 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
938 };
939 }),
940 ),
941 reconcileFileSurfaces: (ref, workspaceAvailable) =>
942 set((state) =>
943 automaticUpdate(state, scopedThreadKey(ref), (current) => {
944 if (workspaceAvailable) return current;
945 const surfaces = current.surfaces.filter(
946 (surface) =>
947 surface.kind !== "files" &&
948 (surface.kind !== "file" || surface.attachment !== undefined),
949 );
950 if (surfaces.length === current.surfaces.length) return current;
951 const activeStillExists = surfaces.some(
952 (surface) => surface.id === current.activeSurfaceId,
953 );
954 return {
955 ...current,
956 isOpen: surfaces.length > 0 ? current.isOpen : false,
957 surfaces,
958 activeSurfaceId: activeStillExists
959 ? current.activeSurfaceId
960 : (surfaces.at(-1)?.id ?? null),
961 };
962 }),
963 ),
964 show: (ref) =>
965 set((state) =>
966 userAction(state, scopedThreadKey(ref), (current) =>
967 current.isOpen ? current : { ...current, isOpen: true },
968 ),
969 ),
970 close: (ref) =>
971 set((state) =>
972 userAction(state, scopedThreadKey(ref), (current) =>
973 current.isOpen ? { ...current, isOpen: false } : current,
974 ),
975 ),
976 // Layout only: it changes no surface, so proactive panels still apply.
977 setMaximized: (ref, maximized) =>
978 set((state) =>
979 automaticUpdate(state, scopedThreadKey(ref), (current) => {
980 if ((current.maximized ?? false) === maximized) return current;
981 const { maximized: _maximized, ...rest } = current;
982 return maximized ? { ...rest, maximized: true } : rest;
983 }),
984 ),
985 toggleVisibility: (ref) =>
986 set((state) =>
987 userAction(state, scopedThreadKey(ref), (current) => ({
988 ...current,
989 isOpen: !current.isOpen,
990 })),
991 ),
992 toggle: (ref, kind) =>
993 set((state) =>
994 userAction(state, scopedThreadKey(ref), (current) => {
995 const active = current.surfaces.find(
996 (surface) => surface.id === current.activeSurfaceId,
997 );
998 if (current.isOpen && active?.kind === kind) {
999 return { ...current, isOpen: false };
1001 if (kind === "preview") {
1002 const existing = current.surfaces.find((surface) => surface.kind === "preview");
1003 return upsertSurface(current, existing ?? browserSurface(null));
1005 return upsertSurface(current, singletonSurface(kind));
1006 }),
1007 ),
1008 setThreadPanelOpen: (ref, presentation, open) =>
1009 set((state) => ({
1010 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
1011 state.threadPanelVisibilityByThreadKey,
1012 scopedThreadKey(ref),
1013 (visibility) => {
1014 const key = presentation === "inline" ? "inlineOpen" : "popoverOpen";
1015 return visibility[key] === open ? visibility : { ...visibility, [key]: open };
1016 },
1017 ),
1018 })),
1019 toggleThreadPanel: (ref, presentation) =>
1020 set((state) => ({
1021 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
1022 state.threadPanelVisibilityByThreadKey,
1023 scopedThreadKey(ref),
1024 (visibility) =>
1025 presentation === "inline"
1026 ? { ...visibility, inlineOpen: !visibility.inlineOpen }
1027 : { ...visibility, popoverOpen: !visibility.popoverOpen },
1028 ),
1029 })),
1030 removeThread: (ref) =>
1031 set((state) => {
1032 const threadKey = scopedThreadKey(ref);
1033 if (
1034 !(threadKey in state.byThreadKey) &&
1035 !(threadKey in state.threadPanelVisibilityByThreadKey) &&
1036 !(threadKey in state.userActionRevisionByThreadKey) &&
1037 !(threadKey in state.closeRevisionByThreadKey)
1038 ) {
1039 return state;
1041 const { [threadKey]: _removed, ...byThreadKey } = state.byThreadKey;
1042 const { [threadKey]: _visibility, ...threadPanelVisibilityByThreadKey } =
1043 state.threadPanelVisibilityByThreadKey;
1044 const { [threadKey]: _revision, ...userActionRevisionByThreadKey } =
1045 state.userActionRevisionByThreadKey;
1046 const { [threadKey]: _closeRevision, ...closeRevisionByThreadKey } =
1047 state.closeRevisionByThreadKey;
1048 return {
1049 byThreadKey,
1050 threadPanelVisibilityByThreadKey,
1051 userActionRevisionByThreadKey,
1052 closeRevisionByThreadKey,
1053 };
1054 }),
1055 }),
1057 name: RIGHT_PANEL_STORAGE_KEY,
1058 version: RIGHT_PANEL_STORAGE_VERSION,
1059 storage: createJSONStorage(() =>
1060 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
1061 ),
1062 partialize: (state) => ({
1063 byThreadKey: Object.fromEntries(
1064 Object.entries(state.byThreadKey).filter(
1065 ([threadKey]) => !isPullRequestsPanelKey(threadKey),
1066 ),
1067 ),
1068 threadPanelVisibilityByThreadKey: Object.fromEntries(
1069 Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
1070 ([threadKey, visibility]) =>
1071 visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
1072 ),
1073 ),
1074 }),
1075 migrate: migratePersistedRightPanelState,
1076 },
1077 ),
1079​
1080useRightPanelStore.subscribe((next, previous) => {
1081 if (next.closeRevisionByThreadKey === previous.closeRevisionByThreadKey) return;
1082 for (const [threadKey, revision] of Object.entries(next.closeRevisionByThreadKey)) {
1083 if (revision === previous.closeRevisionByThreadKey[threadKey]) continue;
1084 const threadRef = parseScopedThreadKey(threadKey);
1085 if (!threadRef) continue;
1086 const before = previous.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
1087 const after = next.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
1088 const removed = before.surfaces.filter(
1089 (surface) => !after.surfaces.some((entry) => entry.id === surface.id),
1090 );
1091 const closedInOrder = [
1092 ...removed.filter((surface) => surface.id !== before.activeSurfaceId),
1093 ...removed.filter((surface) => surface.id === before.activeSurfaceId),
1094 ];
1095 for (const surface of closedInOrder) {
1096 if (
1097 surface.kind === "terminal" ||
1098 (surface.kind === "preview" && surface.resourceId !== null)
1100 continue;
1101 useClosedViewStore.getState().remember({ kind: "panel-tab", threadRef, surface });
1104});
1105​
1106export function selectThreadRightPanelState(
1107 byThreadKey: Record<string, ThreadRightPanelState>,
1108 ref: ScopedThreadRef | null | undefined,
1109): ThreadRightPanelState {
1110 if (!ref) return EMPTY_THREAD_STATE;
1111 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
1113​
1114export function selectThreadPanelVisibility(
1115 byThreadKey: Record<string, ThreadPanelVisibility>,
1116 ref: ScopedThreadRef | null | undefined,
1117): ThreadPanelVisibility {
1118 if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY;
1119 return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
1121​
1122export function selectThreadPanelOpen(
1123 byThreadKey: Record<string, ThreadPanelVisibility>,
1124 ref: ScopedThreadRef | null | undefined,
1125 presentation: ThreadPanelPresentation,
1126): boolean {
1127 const visibility = selectThreadPanelVisibility(byThreadKey, ref);
1128 return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
1130​
1131export function selectActiveRightPanel(
1132 byThreadKey: Record<string, ThreadRightPanelState>,
1133 ref: ScopedThreadRef | null | undefined,
1134): RightPanelKind | null {
1135 const state = selectThreadRightPanelState(byThreadKey, ref);
1136 if (!state.isOpen) return null;
1137 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
1139​
1140export function selectActiveRightPanelSurface(
1141 byThreadKey: Record<string, ThreadRightPanelState>,
1142 ref: ScopedThreadRef | null | undefined,
1143): RightPanelSurface | null {
1144 const state = selectThreadRightPanelState(byThreadKey, ref);
1145 if (!state.isOpen) return null;
1146 return selectSelectedRightPanelSurface(byThreadKey, ref);
1148​
1149/** The selected surface even while the panel is hidden, so a layout control can restore it. */
1150export function selectSelectedRightPanelSurface(
1151 byThreadKey: Record<string, ThreadRightPanelState>,
1152 ref: ScopedThreadRef | null | undefined,
1153): RightPanelSurface | null {
1154 const state = selectThreadRightPanelState(byThreadKey, ref);
1155 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;