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

rightPanelStore.ts

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