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