Open History to see the last commit
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 { scopedThreadKey } from "@t3tools/client-runtime/environment";
11import type { ScopedThreadRef } from "@t3tools/contracts";
12import { create } from "zustand";
13import { createJSONStorage, persist } from "zustand/middleware";
14
15import { resolveStorage } from "./lib/storage";
16
17export const RIGHT_PANEL_KINDS = [
18 "diff",
19 "files",
20 "file",
21 "preview",
22 "terminal",
23 "pull-request",
24 "agents",
25] as const;
26export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
27
28export type RightPanelSurface =
29 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
30 | { id: "browser:new"; kind: "preview"; resourceId: null }
31 | {
32 id: `terminal:${string}`;
33 kind: "terminal";
34 resourceId: string;
35 terminalIds: string[];
36 activeTerminalId: string;
37 splitDirection?: "horizontal" | "vertical";
38 }
39 | { id: "diff"; kind: "diff" }
40 | { id: "files"; kind: "files" }
41 | {
42 id: `file:${string}`;
43 kind: "file";
44 relativePath: string;
45 revealLine: number | null;
46 revealRequestId: number;
47 }
48 | {
49 /**
50 * A change request opened beside a thread or in the pull-request list's shared panel.
51 * The reference lives in the id so several pull requests can remain open as peer tabs.
52 */
53 id: `pull-request:${string}`;
54 kind: "pull-request";
55 /**
56 * Which server the change request was read from. The list spans every connected one, so
57 * two of them can hold the same project id; a panel beside a thread leaves this out and
58 * takes the environment from its own ref.
59 */
60 environmentId?: string;
61 projectId: string;
62 repository: string;
63 number: number;
64 }
65 | { id: "agents"; kind: "agents" };
66
67const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
68// v9 removed the "plan" surface kind (plans render inline in the transcript).
69// v10 keys pull-request surfaces by reference instead of a singleton tab.
70// v11 stops persisting the pull-request list's shared panel, so a restart opens the page fresh.
71const RIGHT_PANEL_STORAGE_VERSION = 11;
72
73/**
74 * The pull-request list's shared panel (see PULL_REQUESTS_PANEL_ID in the route) is session
75 * state: reopening the app should show the list, not last session's tabs and detail fetches.
76 */
77const isPullRequestsPanelKey = (threadKey: string) => threadKey.endsWith(":pull-requests-panel");
78
79export interface ThreadRightPanelState {
80 isOpen: boolean;
81 activeSurfaceId: string | null;
82 surfaces: RightPanelSurface[];
83}
84
85interface RightPanelStoreState {
86 byThreadKey: Record<string, ThreadRightPanelState>;
87 open: (
88 ref: ScopedThreadRef,
89 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
90 ) => void;
91 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
92 openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
93 openPullRequest: (
94 ref: ScopedThreadRef,
95 target: { environmentId?: string; projectId: string; repository: string; number: number },
96 ) => void;
97 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
98 splitTerminal: (
99 ref: ScopedThreadRef,
100 surfaceId: string,
101 terminalId: string,
102 direction?: "horizontal" | "vertical",
103 ) => void;
104 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
105 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
106 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
107 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
108 closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
109 closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
110 closeAllSurfaces: (ref: ScopedThreadRef) => void;
111 reconcileBrowserSurfaces: (ref: ScopedThreadRef, tabIds: readonly string[]) => void;
112 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
113 show: (ref: ScopedThreadRef) => void;
114 close: (ref: ScopedThreadRef) => void;
115 toggleVisibility: (ref: ScopedThreadRef) => void;
116 toggle: (
117 ref: ScopedThreadRef,
118 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
119 ) => void;
120 removeThread: (ref: ScopedThreadRef) => void;
121}
122
123const EMPTY_THREAD_STATE: ThreadRightPanelState = {
124 isOpen: false,
125 activeSurfaceId: null,
126 surfaces: [],
127};
128
129const singletonSurface = (
130 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request">,
131): RightPanelSurface => {
132 switch (kind) {
133 case "diff":
134 return { id: "diff", kind };
135 case "files":
136 return { id: "files", kind };
137 case "agents":
138 return { id: "agents", kind };
139 }
140};
141
142const browserSurface = (tabId: string | null): RightPanelSurface =>
143 tabId
144 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
145 : { id: "browser:new", kind: "preview", resourceId: null };
146
147const fileSurface = (
148 relativePath: string,
149 revealLine: number | null,
150 revealRequestId: number,
151): RightPanelSurface => ({
152 id: `file:${relativePath}`,
153 kind: "file",
154 relativePath,
155 revealLine,
156 revealRequestId,
157});
158
159const terminalSurface = (terminalId: string): RightPanelSurface => ({
160 id: `terminal:${terminalId}`,
161 kind: "terminal",
162 resourceId: terminalId,
163 terminalIds: [terminalId],
164 activeTerminalId: terminalId,
165});
166
167export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-request" }>;
168
169export function pullRequestSurfaceId(target: {
170 environmentId?: string;
171 projectId: string;
172 repository: string;
173 number: number;
174}): PullRequestSurface["id"] {
175 // The environment leads the id where there is one, so the same change request read from two
176 // servers is two tabs rather than one tab that changes its mind about which server it is on.
177 const scope =
178 target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
179 return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${encodeURIComponent(target.repository)}:${target.number}`;
180}
181
182export function pullRequestSurface(target: {
183 environmentId?: string;
184 projectId: string;
185 repository: string;
186 number: number;
187}): PullRequestSurface {
188 return {
189 id: pullRequestSurfaceId(target),
190 kind: "pull-request",
191 ...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
192 projectId: target.projectId,
193 repository: target.repository,
194 number: target.number,
195 };
196}
197
198/**
199 * A pull-request tab's status map with one entry set. Keyed by the surface the panel is showing
200 * rather than by a key rebuilt from the status, so the tab is found again whether or not that
201 * surface was opened with an environment on it. Returns the same map when the tab's own fields
202 * have not changed, so a caller can skip a re-render.
203 */
204export function updatePullRequestTabStatus<Status extends { state: unknown; isDraft: boolean }>(
205 statuses: Readonly<Record<string, Status>>,
206 surfaceId: string,
207 status: Status,
208): Readonly<Record<string, Status>> {
209 return statuses[surfaceId]?.state === status.state &&
210 statuses[surfaceId]?.isDraft === status.isDraft
211 ? statuses
212 : { ...statuses, [surfaceId]: status };
213}
214
215const upsertSurface = (
216 current: ThreadRightPanelState,
217 surface: RightPanelSurface,
218 activate = true,
219): ThreadRightPanelState => ({
220 isOpen: true,
221 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
222 ? current.surfaces
223 : [...current.surfaces, surface],
224 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
225});
226
227const updateThread = (
228 byThreadKey: Record<string, ThreadRightPanelState>,
229 threadKey: string,
230 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
231): Record<string, ThreadRightPanelState> => {
232 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
233 const next = updater(current);
234 if (!next.isOpen && next.activeSurfaceId === null && next.surfaces.length === 0) {
235 if (!(threadKey in byThreadKey)) return byThreadKey;
236 const { [threadKey]: _removed, ...rest } = byThreadKey;
237 return rest;
238 }
239 if (next === current) return byThreadKey;
240 return { ...byThreadKey, [threadKey]: next };
241};
242
243function normalizeRevealLine(line: number | undefined): number | null {
244 if (line === undefined || !Number.isFinite(line)) return null;
245 return Math.max(1, Math.trunc(line));
246}
247
248export function migratePersistedRightPanelState(persistedState: unknown): {
249 byThreadKey: Record<string, ThreadRightPanelState>;
250} {
251 if (!persistedState || typeof persistedState !== "object") {
252 return { byThreadKey: {} };
253 }
254 const byThreadKey =
255 "byThreadKey" in persistedState &&
256 persistedState.byThreadKey &&
257 typeof persistedState.byThreadKey === "object"
258 ? Object.fromEntries(
259 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>)
260 .filter(([threadKey]) => !isPullRequestsPanelKey(threadKey))
261 .map(([threadKey, threadState]) => {
262 const validThreadState =
263 threadState && typeof threadState === "object" ? threadState : null;
264 const surfaces = Array.isArray(validThreadState?.surfaces)
265 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
266 // Dropped surface kind: plans now render inline in the
267 // transcript (v9).
268 if ((surface as { kind?: string }).kind === "plan") return [];
269 if (surface.kind === "file") {
270 const revealLine =
271 typeof surface.revealLine === "number" &&
272 Number.isFinite(surface.revealLine)
273 ? Math.max(1, Math.trunc(surface.revealLine))
274 : null;
275 const revealRequestId =
276 typeof surface.revealRequestId === "number" &&
277 Number.isSafeInteger(surface.revealRequestId) &&
278 surface.revealRequestId >= 0
279 ? surface.revealRequestId
280 : 0;
281 return [{ ...surface, revealLine, revealRequestId }];
282 }
283 if (surface.kind === "pull-request") {
284 if (
285 typeof surface.projectId !== "string" ||
286 typeof surface.repository !== "string" ||
287 typeof surface.number !== "number" ||
288 !Number.isSafeInteger(surface.number) ||
289 surface.number < 1
290 ) {
291 return [];
292 }
293 const { environmentId, ...rest } = surface;
294 // Anything else stored under that name is not an environment.
295 return [
296 pullRequestSurface({
297 ...rest,
298 ...(typeof environmentId === "string" ? { environmentId } : {}),
299 }),
300 ];
301 }
302 if (surface.kind !== "terminal") return [surface];
303 if (
304 !("resourceId" in surface) ||
305 typeof surface.resourceId !== "string" ||
306 surface.id !== `terminal:${surface.resourceId}`
307 ) {
308 return [];
309 }
310 const terminalIds =
311 "terminalIds" in surface && Array.isArray(surface.terminalIds)
312 ? [
313 ...new Set(
314 surface.terminalIds.filter(
315 (terminalId): terminalId is string =>
316 typeof terminalId === "string",
317 ),
318 ),
319 ]
320 : [surface.resourceId];
321 const activeTerminalId =
322 "activeTerminalId" in surface &&
323 typeof surface.activeTerminalId === "string" &&
324 terminalIds.includes(surface.activeTerminalId)
325 ? surface.activeTerminalId
326 : (terminalIds[0] ?? surface.resourceId);
327 return [
328 {
329 ...surface,
330 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
331 activeTerminalId,
332 },
333 ];
334 })
335 : [];
336 const rawActiveSurfaceId = validThreadState?.activeSurfaceId;
337 const persistedActiveSurfaceId = surfaces.some(
338 (surface) => surface.id === rawActiveSurfaceId,
339 )
340 ? (rawActiveSurfaceId ?? null)
341 : rawActiveSurfaceId === "pull-request"
342 ? (surfaces.find((surface) => surface.kind === "pull-request")?.id ?? null)
343 : null;
344 // A migration that dropped every surface (e.g. plan-only panels
345 // in v9) must not reopen an empty panel.
346 const isOpen =
347 surfaces.length > 0 &&
348 (typeof validThreadState?.isOpen === "boolean"
349 ? validThreadState.isOpen
350 : persistedActiveSurfaceId !== null);
351 // An open panel needs an active surface: if migration dropped
352 // the persisted one (e.g. plan was active), fall back to the
353 // first survivor instead of rendering an open empty panel.
354 const activeSurfaceId =
355 persistedActiveSurfaceId ?? (isOpen ? (surfaces[0]?.id ?? null) : null);
356 return [threadKey, { isOpen, surfaces, activeSurfaceId }];
357 }),
358 )
359 : {};
360 return { byThreadKey };
361}
362
363export const useRightPanelStore = create<RightPanelStoreState>()(
364 persist(
365 (set) => ({
366 byThreadKey: {},
367 open: (ref, kind) =>
368 set((state) => ({
369 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
370 if (kind === "preview") {
371 const existing = current.surfaces.find((surface) => surface.kind === "preview");
372 return upsertSurface(current, existing ?? browserSurface(null));
373 }
374 return upsertSurface(current, singletonSurface(kind));
375 }),
376 })),
377 openBrowser: (ref, tabId) =>
378 set((state) => ({
379 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
380 const surface = browserSurface(tabId);
381 const withoutPlaceholder = tabId
382 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
383 : current.surfaces;
384 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
385 }),
386 })),
387 openPullRequest: (ref, target) =>
388 set((state) => ({
389 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
390 return upsertSurface(current, pullRequestSurface(target));
391 }),
392 })),
393 openFile: (ref, relativePath, line) =>
394 set((state) => ({
395 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
396 const withoutStandaloneExplorer = current.surfaces.filter(
397 (surface) => surface.kind !== "files",
398 );
399 const surfaceId = `file:${relativePath}` as const;
400 const existing = withoutStandaloneExplorer.find(
401 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
402 surface.id === surfaceId && surface.kind === "file",
403 );
404 const surface = fileSurface(
405 relativePath,
406 normalizeRevealLine(line),
407 (existing?.revealRequestId ?? 0) + 1,
408 );
409 return {
410 isOpen: true,
411 activeSurfaceId: surface.id,
412 surfaces: existing
413 ? withoutStandaloneExplorer.map((entry) =>
414 entry.id === surface.id ? surface : entry,
415 )
416 : [...withoutStandaloneExplorer, surface],
417 };
418 }),
419 })),
420 openTerminal: (ref, terminalId) =>
421 set((state) => ({
422 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
423 upsertSurface(current, terminalSurface(terminalId)),
424 ),
425 })),
426 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
427 set((state) => ({
428 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
429 ...current,
430 isOpen: true,
431 activeSurfaceId: surfaceId,
432 surfaces: current.surfaces.map((surface) => {
433 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
434 const { splitDirection: _splitDirection, ...baseSurface } = surface;
435 return {
436 ...baseSurface,
437 terminalIds: surface.terminalIds.includes(terminalId)
438 ? surface.terminalIds
439 : [...surface.terminalIds, terminalId],
440 activeTerminalId: terminalId,
441 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
442 };
443 }),
444 })),
445 })),
446 activateTerminal: (ref, surfaceId, terminalId) =>
447 set((state) => ({
448 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
449 ...current,
450 activeSurfaceId: surfaceId,
451 surfaces: current.surfaces.map((surface) =>
452 surface.id === surfaceId &&
453 surface.kind === "terminal" &&
454 surface.terminalIds.includes(terminalId)
455 ? { ...surface, activeTerminalId: terminalId }
456 : surface,
457 ),
458 })),
459 })),
460 closeTerminal: (ref, surfaceId, terminalId) =>
461 set((state) => ({
462 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
463 const surface = current.surfaces.find(
464 (entry) => entry.id === surfaceId && entry.kind === "terminal",
465 );
466 if (!surface || surface.kind !== "terminal") return current;
467 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
468 if (terminalIds.length === 0) {
469 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
470 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
471 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
472 return {
473 ...current,
474 isOpen: surfaces.length > 0 && current.isOpen,
475 surfaces,
476 activeSurfaceId:
477 current.activeSurfaceId === surfaceId
478 ? (fallback?.id ?? null)
479 : current.activeSurfaceId,
480 };
481 }
482 return {
483 ...current,
484 surfaces: current.surfaces.map((entry) =>
485 entry.id === surfaceId && entry.kind === "terminal"
486 ? {
487 ...entry,
488 terminalIds,
489 activeTerminalId:
490 entry.activeTerminalId === terminalId
491 ? (terminalIds.at(-1) ?? terminalIds[0]!)
492 : entry.activeTerminalId,
493 }
494 : entry,
495 ),
496 };
497 }),
498 })),
499 activateSurface: (ref, surfaceId) =>
500 set((state) => ({
501 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
502 current.surfaces.some((surface) => surface.id === surfaceId)
503 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
504 : current,
505 ),
506 })),
507 closeSurface: (ref, surfaceId) =>
508 set((state) => ({
509 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
510 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
511 if (index < 0) return current;
512 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
513 if (current.activeSurfaceId !== surfaceId) {
514 return { ...current, isOpen: surfaces.length > 0 && current.isOpen, surfaces };
515 }
516 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
517 return {
518 ...current,
519 isOpen: surfaces.length > 0 && current.isOpen,
520 surfaces,
521 activeSurfaceId: fallback?.id ?? null,
522 };
523 }),
524 })),
525 closeOtherSurfaces: (ref, surfaceId) =>
526 set((state) => ({
527 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
528 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
529 if (!surface || current.surfaces.length === 1) return current;
530 return {
531 ...current,
532 isOpen: true,
533 surfaces: [surface],
534 activeSurfaceId: surface.id,
535 };
536 }),
537 })),
538 closeSurfacesToRight: (ref, surfaceId) =>
539 set((state) => ({
540 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
541 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
542 if (index < 0 || index === current.surfaces.length - 1) return current;
543 const surfaces = current.surfaces.slice(0, index + 1);
544 const activeStillExists = surfaces.some(
545 (surface) => surface.id === current.activeSurfaceId,
546 );
547 return {
548 ...current,
549 surfaces,
550 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
551 };
552 }),
553 })),
554 closeAllSurfaces: (ref) =>
555 set((state) => ({
556 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
557 current.surfaces.length === 0
558 ? current
559 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
560 ),
561 })),
562 reconcileBrowserSurfaces: (ref, tabIds) =>
563 set((state) => ({
564 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
565 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
566 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
567 const existingBrowser = current.surfaces.filter(
568 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
569 surface.kind === "preview" &&
570 surface.id !== "browser:new" &&
571 validIds.has(surface.id),
572 );
573 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
574 const added = tabIds
575 .filter((tabId) => !knownIds.has(`browser:${tabId}`))
576 .map((tabId) => browserSurface(tabId));
577 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
578 const activeStillExists = surfaces.some(
579 (surface) => surface.id === current.activeSurfaceId,
580 );
581 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
582 return {
583 ...current,
584 surfaces,
585 activeSurfaceId: activeStillExists
586 ? current.activeSurfaceId
587 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
588 };
589 }),
590 })),
591 reconcileFileSurfaces: (ref, workspaceAvailable) =>
592 set((state) => ({
593 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
594 if (workspaceAvailable) return current;
595 const surfaces = current.surfaces.filter(
596 (surface) => surface.kind !== "files" && surface.kind !== "file",
597 );
598 if (surfaces.length === current.surfaces.length) return current;
599 const activeStillExists = surfaces.some(
600 (surface) => surface.id === current.activeSurfaceId,
601 );
602 return {
603 ...current,
604 isOpen: surfaces.length > 0 ? current.isOpen : false,
605 surfaces,
606 activeSurfaceId: activeStillExists
607 ? current.activeSurfaceId
608 : (surfaces.at(-1)?.id ?? null),
609 };
610 }),
611 })),
612 show: (ref) =>
613 set((state) => ({
614 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
615 current.isOpen ? current : { ...current, isOpen: true },
616 ),
617 })),
618 close: (ref) =>
619 set((state) => ({
620 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
621 current.isOpen ? { ...current, isOpen: false } : current,
622 ),
623 })),
624 toggleVisibility: (ref) =>
625 set((state) => ({
626 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
627 ...current,
628 isOpen: !current.isOpen,
629 })),
630 })),
631 toggle: (ref, kind) =>
632 set((state) => ({
633 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
634 const active = current.surfaces.find(
635 (surface) => surface.id === current.activeSurfaceId,
636 );
637 if (current.isOpen && active?.kind === kind) {
638 return { ...current, isOpen: false };
639 }
640 if (kind === "preview") {
641 const existing = current.surfaces.find((surface) => surface.kind === "preview");
642 return upsertSurface(current, existing ?? browserSurface(null));
643 }
644 return upsertSurface(current, singletonSurface(kind));
645 }),
646 })),
647 removeThread: (ref) =>
648 set((state) => {
649 const threadKey = scopedThreadKey(ref);
650 if (!(threadKey in state.byThreadKey)) return state;
651 const { [threadKey]: _removed, ...rest } = state.byThreadKey;
652 return { byThreadKey: rest };
653 }),
654 }),
655 {
656 name: RIGHT_PANEL_STORAGE_KEY,
657 version: RIGHT_PANEL_STORAGE_VERSION,
658 storage: createJSONStorage(() =>
659 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
660 ),
661 partialize: (state) => ({
662 byThreadKey: Object.fromEntries(
663 Object.entries(state.byThreadKey).filter(
664 ([threadKey]) => !isPullRequestsPanelKey(threadKey),
665 ),
666 ),
667 }),
668 migrate: migratePersistedRightPanelState,
669 },
670 ),
671);
672
673export function selectThreadRightPanelState(
674 byThreadKey: Record<string, ThreadRightPanelState>,
675 ref: ScopedThreadRef | null | undefined,
676): ThreadRightPanelState {
677 if (!ref) return EMPTY_THREAD_STATE;
678 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
679}
680
681export function selectActiveRightPanel(
682 byThreadKey: Record<string, ThreadRightPanelState>,
683 ref: ScopedThreadRef | null | undefined,
684): RightPanelKind | null {
685 const state = selectThreadRightPanelState(byThreadKey, ref);
686 if (!state.isOpen) return null;
687 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
688}
689
690export function selectActiveRightPanelSurface(
691 byThreadKey: Record<string, ThreadRightPanelState>,
692 ref: ScopedThreadRef | null | undefined,
693): RightPanelSurface | null {
694 const state = selectThreadRightPanelState(byThreadKey, ref);
695 if (!state.isOpen) return null;
696 return selectSelectedRightPanelSurface(byThreadKey, ref);
697}
698
699/** The selected surface even while the panel is hidden, so a layout control can restore it. */
700export function selectSelectedRightPanelSurface(
701 byThreadKey: Record<string, ThreadRightPanelState>,
702 ref: ScopedThreadRef | null | undefined,
703): RightPanelSurface | null {
704 const state = selectThreadRightPanelState(byThreadKey, ref);
705 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
706}