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";
16import type { ThreadPanelPresentation } from "./rightPanelLayout";
17
18export const RIGHT_PANEL_KINDS = [
19 "diff",
20 "files",
21 "file",
22 "preview",
23 "terminal",
24 "pull-request",
25 "agents",
26] as const;
27export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
28
29export type RightPanelSurface =
30 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
31 | { id: "browser:new"; kind: "preview"; resourceId: null }
32 | {
33 id: `terminal:${string}`;
34 kind: "terminal";
35 resourceId: string;
36 terminalIds: string[];
37 activeTerminalId: string;
38 splitDirection?: "horizontal" | "vertical";
39 }
40 | { id: "diff"; kind: "diff" }
41 | { id: "files"; kind: "files" }
42 | {
43 id: `file:${string}`;
44 kind: "file";
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 projectId: string;
57 repository: string;
58 number: number;
59 }
60 | { id: "agents"; kind: "agents" };
61
62const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
63// v9 removed the "plan" surface kind (plans render inline in the transcript).
64// v10 keys pull-request surfaces by reference instead of a singleton tab.
65// v11 stops persisting the pull-request list's shared panel, so a restart opens the page fresh.
66const RIGHT_PANEL_STORAGE_VERSION = 11;
67
68/**
69 * The pull-request list's shared panel (see PULL_REQUESTS_PANEL_ID in the route) is session
70 * state: reopening the app should show the list, not last session's tabs and detail fetches.
71 */
72const isPullRequestsPanelKey = (threadKey: string) => threadKey.endsWith(":pull-requests-panel");
73
74export interface ThreadRightPanelState {
75 isOpen: boolean;
76 activeSurfaceId: string | null;
77 surfaces: RightPanelSurface[];
78}
79
80export interface ThreadPanelVisibility {
81 inlineOpen: boolean;
82 popoverOpen: boolean;
83}
84
85interface RightPanelStoreState {
86 byThreadKey: Record<string, ThreadRightPanelState>;
87 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
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: { 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 setThreadPanelOpen: (
122 ref: ScopedThreadRef,
123 presentation: ThreadPanelPresentation,
124 open: boolean,
125 ) => void;
126 toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
127 removeThread: (ref: ScopedThreadRef) => void;
128}
129
130const EMPTY_THREAD_STATE: ThreadRightPanelState = {
131 isOpen: false,
132 activeSurfaceId: null,
133 surfaces: [],
134};
135
136const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
137 inlineOpen: true,
138 popoverOpen: false,
139};
140
141const singletonSurface = (
142 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request">,
143): RightPanelSurface => {
144 switch (kind) {
145 case "diff":
146 return { id: "diff", kind };
147 case "files":
148 return { id: "files", kind };
149 case "agents":
150 return { id: "agents", kind };
151 }
152};
153
154const browserSurface = (tabId: string | null): RightPanelSurface =>
155 tabId
156 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
157 : { id: "browser:new", kind: "preview", resourceId: null };
158
159const fileSurface = (
160 relativePath: string,
161 revealLine: number | null,
162 revealRequestId: number,
163): RightPanelSurface => ({
164 id: `file:${relativePath}`,
165 kind: "file",
166 relativePath,
167 revealLine,
168 revealRequestId,
169});
170
171const terminalSurface = (terminalId: string): RightPanelSurface => ({
172 id: `terminal:${terminalId}`,
173 kind: "terminal",
174 resourceId: terminalId,
175 terminalIds: [terminalId],
176 activeTerminalId: terminalId,
177});
178
179export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-request" }>;
180
181export function pullRequestSurfaceId(target: {
182 projectId: string;
183 repository: string;
184 number: number;
185}): PullRequestSurface["id"] {
186 return `pull-request:${encodeURIComponent(target.projectId)}:${encodeURIComponent(target.repository)}:${target.number}`;
187}
188
189export function pullRequestSurface(target: {
190 projectId: string;
191 repository: string;
192 number: number;
193}): PullRequestSurface {
194 return {
195 id: pullRequestSurfaceId(target),
196 kind: "pull-request",
197 projectId: target.projectId,
198 repository: target.repository,
199 number: target.number,
200 };
201}
202
203const upsertSurface = (
204 current: ThreadRightPanelState,
205 surface: RightPanelSurface,
206 activate = true,
207): ThreadRightPanelState => ({
208 isOpen: true,
209 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
210 ? current.surfaces
211 : [...current.surfaces, surface],
212 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
213});
214
215const updateThreadStateMap = (
216 byThreadKey: Record<string, ThreadRightPanelState>,
217 threadKey: string,
218 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
219): Record<string, ThreadRightPanelState> => {
220 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
221 const next = updater(current);
222 if (!next.isOpen && next.activeSurfaceId === null && next.surfaces.length === 0) {
223 if (!(threadKey in byThreadKey)) return byThreadKey;
224 const { [threadKey]: _removed, ...rest } = byThreadKey;
225 return rest;
226 }
227 if (next === current) return byThreadKey;
228 return { ...byThreadKey, [threadKey]: next };
229};
230
231const updateThreadPanelVisibilityMap = (
232 byThreadKey: Record<string, ThreadPanelVisibility>,
233 threadKey: string,
234 updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
235): Record<string, ThreadPanelVisibility> => {
236 const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
237 const next = updater(current);
238 if (next.inlineOpen && !next.popoverOpen) {
239 if (!(threadKey in byThreadKey)) return byThreadKey;
240 const { [threadKey]: _removed, ...rest } = byThreadKey;
241 return rest;
242 }
243 if (next === current) return byThreadKey;
244 return { ...byThreadKey, [threadKey]: next };
245};
246
247type RightPanelStoreData = Pick<
248 RightPanelStoreState,
249 "byThreadKey" | "threadPanelVisibilityByThreadKey"
250>;
251
252/**
253 * Applies a real right-panel mutation and its thread-panel transition atomically.
254 * This is the only path real panel actions use, so visibility never has to be
255 * reconciled after the fact in React.
256 */
257const updateThread = (
258 state: RightPanelStoreData,
259 ref: ScopedThreadRef,
260 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
261): RightPanelStoreData => {
262 const threadKey = scopedThreadKey(ref);
263 const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
264 const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
265 const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
266 let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
267
268 if (!current.isOpen && next.isOpen) {
269 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
270 threadPanelVisibilityByThreadKey,
271 threadKey,
272 (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
273 );
274 } else if (current.isOpen && !next.isOpen) {
275 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
276 threadPanelVisibilityByThreadKey,
277 threadKey,
278 (visibility) =>
279 visibility.popoverOpen && !visibility.inlineOpen
280 ? { ...visibility, inlineOpen: true }
281 : visibility,
282 );
283 }
284
285 return { byThreadKey, threadPanelVisibilityByThreadKey };
286};
287
288function normalizeRevealLine(line: number | undefined): number | null {
289 if (line === undefined || !Number.isFinite(line)) return null;
290 return Math.max(1, Math.trunc(line));
291}
292
293export function migratePersistedRightPanelState(persistedState: unknown): {
294 byThreadKey: Record<string, ThreadRightPanelState>;
295 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
296} {
297 if (!persistedState || typeof persistedState !== "object") {
298 return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
299 }
300 const byThreadKey =
301 "byThreadKey" in persistedState &&
302 persistedState.byThreadKey &&
303 typeof persistedState.byThreadKey === "object"
304 ? Object.fromEntries(
305 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>)
306 .filter(([threadKey]) => !isPullRequestsPanelKey(threadKey))
307 .map(([threadKey, threadState]) => {
308 const validThreadState =
309 threadState && typeof threadState === "object" ? threadState : null;
310 const surfaces = Array.isArray(validThreadState?.surfaces)
311 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
312 // Dropped surface kind: plans now render inline in the
313 // transcript (v9).
314 if ((surface as { kind?: string }).kind === "plan") return [];
315 if (surface.kind === "file") {
316 const revealLine =
317 typeof surface.revealLine === "number" &&
318 Number.isFinite(surface.revealLine)
319 ? Math.max(1, Math.trunc(surface.revealLine))
320 : null;
321 const revealRequestId =
322 typeof surface.revealRequestId === "number" &&
323 Number.isSafeInteger(surface.revealRequestId) &&
324 surface.revealRequestId >= 0
325 ? surface.revealRequestId
326 : 0;
327 return [{ ...surface, revealLine, revealRequestId }];
328 }
329 if (surface.kind === "pull-request") {
330 if (
331 typeof surface.projectId !== "string" ||
332 typeof surface.repository !== "string" ||
333 typeof surface.number !== "number" ||
334 !Number.isSafeInteger(surface.number) ||
335 surface.number < 1
336 ) {
337 return [];
338 }
339 return [pullRequestSurface(surface)];
340 }
341 if (surface.kind !== "terminal") return [surface];
342 if (
343 !("resourceId" in surface) ||
344 typeof surface.resourceId !== "string" ||
345 surface.id !== `terminal:${surface.resourceId}`
346 ) {
347 return [];
348 }
349 const terminalIds =
350 "terminalIds" in surface && Array.isArray(surface.terminalIds)
351 ? [
352 ...new Set(
353 surface.terminalIds.filter(
354 (terminalId): terminalId is string =>
355 typeof terminalId === "string",
356 ),
357 ),
358 ]
359 : [surface.resourceId];
360 const activeTerminalId =
361 "activeTerminalId" in surface &&
362 typeof surface.activeTerminalId === "string" &&
363 terminalIds.includes(surface.activeTerminalId)
364 ? surface.activeTerminalId
365 : (terminalIds[0] ?? surface.resourceId);
366 return [
367 {
368 ...surface,
369 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
370 activeTerminalId,
371 },
372 ];
373 })
374 : [];
375 const rawActiveSurfaceId = validThreadState?.activeSurfaceId;
376 const persistedActiveSurfaceId = surfaces.some(
377 (surface) => surface.id === rawActiveSurfaceId,
378 )
379 ? (rawActiveSurfaceId ?? null)
380 : rawActiveSurfaceId === "pull-request"
381 ? (surfaces.find((surface) => surface.kind === "pull-request")?.id ?? null)
382 : null;
383 // A migration that dropped every surface (e.g. plan-only panels
384 // in v9) must not reopen an empty panel.
385 const isOpen =
386 surfaces.length > 0 &&
387 (typeof validThreadState?.isOpen === "boolean"
388 ? validThreadState.isOpen
389 : persistedActiveSurfaceId !== null);
390 // An open panel needs an active surface: if migration dropped
391 // the persisted one (e.g. plan was active), fall back to the
392 // first survivor instead of rendering an open empty panel.
393 const activeSurfaceId =
394 persistedActiveSurfaceId ?? (isOpen ? (surfaces[0]?.id ?? null) : null);
395 return [threadKey, { isOpen, surfaces, activeSurfaceId }];
396 }),
397 )
398 : {};
399 const threadPanelVisibilityByThreadKey =
400 "threadPanelVisibilityByThreadKey" in persistedState &&
401 persistedState.threadPanelVisibilityByThreadKey &&
402 typeof persistedState.threadPanelVisibilityByThreadKey === "object"
403 ? Object.fromEntries(
404 Object.entries(
405 persistedState.threadPanelVisibilityByThreadKey as Record<string, unknown>,
406 ).flatMap(([threadKey, value]) => {
407 if (!value || typeof value !== "object" || !("inlineOpen" in value)) return [];
408 return value.inlineOpen === false
409 ? [[threadKey, { inlineOpen: false, popoverOpen: false }]]
410 : [];
411 }),
412 )
413 : {};
414 return { byThreadKey, threadPanelVisibilityByThreadKey };
415}
416
417export const useRightPanelStore = create<RightPanelStoreState>()(
418 persist(
419 (set) => ({
420 byThreadKey: {},
421 threadPanelVisibilityByThreadKey: {},
422 open: (ref, kind) =>
423 set((state) =>
424 updateThread(state, ref, (current) => {
425 if (kind === "preview") {
426 const existing = current.surfaces.find((surface) => surface.kind === "preview");
427 return upsertSurface(current, existing ?? browserSurface(null));
428 }
429 return upsertSurface(current, singletonSurface(kind));
430 }),
431 ),
432 openBrowser: (ref, tabId) =>
433 set((state) =>
434 updateThread(state, ref, (current) => {
435 const surface = browserSurface(tabId);
436 const withoutPlaceholder = tabId
437 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
438 : current.surfaces;
439 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
440 }),
441 ),
442 openPullRequest: (ref, target) =>
443 set((state) =>
444 updateThread(state, ref, (current) => upsertSurface(current, pullRequestSurface(target))),
445 ),
446 openFile: (ref, relativePath, line) =>
447 set((state) =>
448 updateThread(state, ref, (current) => {
449 const withoutStandaloneExplorer = current.surfaces.filter(
450 (surface) => surface.kind !== "files",
451 );
452 const surfaceId = `file:${relativePath}` as const;
453 const existing = withoutStandaloneExplorer.find(
454 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
455 surface.id === surfaceId && surface.kind === "file",
456 );
457 const surface = fileSurface(
458 relativePath,
459 normalizeRevealLine(line),
460 (existing?.revealRequestId ?? 0) + 1,
461 );
462 return {
463 isOpen: true,
464 activeSurfaceId: surface.id,
465 surfaces: existing
466 ? withoutStandaloneExplorer.map((entry) =>
467 entry.id === surface.id ? surface : entry,
468 )
469 : [...withoutStandaloneExplorer, surface],
470 };
471 }),
472 ),
473 openTerminal: (ref, terminalId) =>
474 set((state) =>
475 updateThread(state, ref, (current) =>
476 upsertSurface(current, terminalSurface(terminalId)),
477 ),
478 ),
479 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
480 set((state) =>
481 updateThread(state, ref, (current) => ({
482 ...current,
483 isOpen: true,
484 activeSurfaceId: surfaceId,
485 surfaces: current.surfaces.map((surface) => {
486 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
487 const { splitDirection: _splitDirection, ...baseSurface } = surface;
488 return {
489 ...baseSurface,
490 terminalIds: surface.terminalIds.includes(terminalId)
491 ? surface.terminalIds
492 : [...surface.terminalIds, terminalId],
493 activeTerminalId: terminalId,
494 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
495 };
496 }),
497 })),
498 ),
499 activateTerminal: (ref, surfaceId, terminalId) =>
500 set((state) =>
501 updateThread(state, ref, (current) => ({
502 ...current,
503 activeSurfaceId: surfaceId,
504 surfaces: current.surfaces.map((surface) =>
505 surface.id === surfaceId &&
506 surface.kind === "terminal" &&
507 surface.terminalIds.includes(terminalId)
508 ? { ...surface, activeTerminalId: terminalId }
509 : surface,
510 ),
511 })),
512 ),
513 closeTerminal: (ref, surfaceId, terminalId) =>
514 set((state) =>
515 updateThread(state, ref, (current) => {
516 const surface = current.surfaces.find(
517 (entry) => entry.id === surfaceId && entry.kind === "terminal",
518 );
519 if (!surface || surface.kind !== "terminal") return current;
520 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
521 if (terminalIds.length === 0) {
522 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
523 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
524 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
525 return {
526 ...current,
527 isOpen: surfaces.length > 0 && current.isOpen,
528 surfaces,
529 activeSurfaceId:
530 current.activeSurfaceId === surfaceId
531 ? (fallback?.id ?? null)
532 : current.activeSurfaceId,
533 };
534 }
535 return {
536 ...current,
537 surfaces: current.surfaces.map((entry) =>
538 entry.id === surfaceId && entry.kind === "terminal"
539 ? {
540 ...entry,
541 terminalIds,
542 activeTerminalId:
543 entry.activeTerminalId === terminalId
544 ? (terminalIds.at(-1) ?? terminalIds[0]!)
545 : entry.activeTerminalId,
546 }
547 : entry,
548 ),
549 };
550 }),
551 ),
552 activateSurface: (ref, surfaceId) =>
553 set((state) =>
554 updateThread(state, ref, (current) =>
555 current.surfaces.some((surface) => surface.id === surfaceId)
556 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
557 : current,
558 ),
559 ),
560 closeSurface: (ref, surfaceId) =>
561 set((state) =>
562 updateThread(state, ref, (current) => {
563 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
564 if (index < 0) return current;
565 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
566 if (current.activeSurfaceId !== surfaceId) {
567 return { ...current, isOpen: surfaces.length > 0 && current.isOpen, surfaces };
568 }
569 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
570 return {
571 ...current,
572 isOpen: surfaces.length > 0 && current.isOpen,
573 surfaces,
574 activeSurfaceId: fallback?.id ?? null,
575 };
576 }),
577 ),
578 closeOtherSurfaces: (ref, surfaceId) =>
579 set((state) =>
580 updateThread(state, ref, (current) => {
581 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
582 if (!surface || current.surfaces.length === 1) return current;
583 return {
584 ...current,
585 isOpen: true,
586 surfaces: [surface],
587 activeSurfaceId: surface.id,
588 };
589 }),
590 ),
591 closeSurfacesToRight: (ref, surfaceId) =>
592 set((state) =>
593 updateThread(state, ref, (current) => {
594 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
595 if (index < 0 || index === current.surfaces.length - 1) return current;
596 const surfaces = current.surfaces.slice(0, index + 1);
597 const activeStillExists = surfaces.some(
598 (surface) => surface.id === current.activeSurfaceId,
599 );
600 return {
601 ...current,
602 surfaces,
603 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
604 };
605 }),
606 ),
607 closeAllSurfaces: (ref) =>
608 set((state) =>
609 updateThread(state, ref, (current) =>
610 current.surfaces.length === 0
611 ? current
612 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
613 ),
614 ),
615 reconcileBrowserSurfaces: (ref, tabIds) =>
616 set((state) =>
617 updateThread(state, ref, (current) => {
618 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
619 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
620 const existingBrowser = current.surfaces.filter(
621 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
622 surface.kind === "preview" &&
623 surface.id !== "browser:new" &&
624 validIds.has(surface.id),
625 );
626 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
627 const added = tabIds
628 .filter((tabId) => !knownIds.has(`browser:${tabId}`))
629 .map((tabId) => browserSurface(tabId));
630 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
631 const activeStillExists = surfaces.some(
632 (surface) => surface.id === current.activeSurfaceId,
633 );
634 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
635 return {
636 ...current,
637 surfaces,
638 activeSurfaceId: activeStillExists
639 ? current.activeSurfaceId
640 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
641 };
642 }),
643 ),
644 reconcileFileSurfaces: (ref, workspaceAvailable) =>
645 set((state) =>
646 updateThread(state, ref, (current) => {
647 if (workspaceAvailable) return current;
648 const surfaces = current.surfaces.filter(
649 (surface) => surface.kind !== "files" && surface.kind !== "file",
650 );
651 if (surfaces.length === current.surfaces.length) return current;
652 const activeStillExists = surfaces.some(
653 (surface) => surface.id === current.activeSurfaceId,
654 );
655 return {
656 ...current,
657 isOpen: surfaces.length > 0 ? current.isOpen : false,
658 surfaces,
659 activeSurfaceId: activeStillExists
660 ? current.activeSurfaceId
661 : (surfaces.at(-1)?.id ?? null),
662 };
663 }),
664 ),
665 show: (ref) =>
666 set((state) =>
667 updateThread(state, ref, (current) =>
668 current.isOpen ? current : { ...current, isOpen: true },
669 ),
670 ),
671 close: (ref) =>
672 set((state) =>
673 updateThread(state, ref, (current) =>
674 current.isOpen ? { ...current, isOpen: false } : current,
675 ),
676 ),
677 toggleVisibility: (ref) =>
678 set((state) =>
679 updateThread(state, ref, (current) => ({
680 ...current,
681 isOpen: !current.isOpen,
682 })),
683 ),
684 toggle: (ref, kind) =>
685 set((state) =>
686 updateThread(state, ref, (current) => {
687 const active = current.surfaces.find(
688 (surface) => surface.id === current.activeSurfaceId,
689 );
690 if (current.isOpen && active?.kind === kind) {
691 return { ...current, isOpen: false };
692 }
693 if (kind === "preview") {
694 const existing = current.surfaces.find((surface) => surface.kind === "preview");
695 return upsertSurface(current, existing ?? browserSurface(null));
696 }
697 return upsertSurface(current, singletonSurface(kind));
698 }),
699 ),
700 setThreadPanelOpen: (ref, presentation, open) =>
701 set((state) => ({
702 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
703 state.threadPanelVisibilityByThreadKey,
704 scopedThreadKey(ref),
705 (visibility) => {
706 const key = presentation === "inline" ? "inlineOpen" : "popoverOpen";
707 return visibility[key] === open ? visibility : { ...visibility, [key]: open };
708 },
709 ),
710 })),
711 toggleThreadPanel: (ref, presentation) =>
712 set((state) => ({
713 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
714 state.threadPanelVisibilityByThreadKey,
715 scopedThreadKey(ref),
716 (visibility) =>
717 presentation === "inline"
718 ? { ...visibility, inlineOpen: !visibility.inlineOpen }
719 : { ...visibility, popoverOpen: !visibility.popoverOpen },
720 ),
721 })),
722 removeThread: (ref) =>
723 set((state) => {
724 const threadKey = scopedThreadKey(ref);
725 if (
726 !(threadKey in state.byThreadKey) &&
727 !(threadKey in state.threadPanelVisibilityByThreadKey)
728 ) {
729 return state;
730 }
731 const { [threadKey]: _removedPanel, ...byThreadKey } = state.byThreadKey;
732 const { [threadKey]: _removedVisibility, ...threadPanelVisibilityByThreadKey } =
733 state.threadPanelVisibilityByThreadKey;
734 return { byThreadKey, threadPanelVisibilityByThreadKey };
735 }),
736 }),
737 {
738 name: RIGHT_PANEL_STORAGE_KEY,
739 version: RIGHT_PANEL_STORAGE_VERSION,
740 storage: createJSONStorage(() =>
741 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
742 ),
743 partialize: (state) => ({
744 byThreadKey: Object.fromEntries(
745 Object.entries(state.byThreadKey).filter(
746 ([threadKey]) => !isPullRequestsPanelKey(threadKey),
747 ),
748 ),
749 threadPanelVisibilityByThreadKey: Object.fromEntries(
750 Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
751 ([threadKey, visibility]) =>
752 visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
753 ),
754 ),
755 }),
756 migrate: migratePersistedRightPanelState,
757 },
758 ),
759);
760
761export function selectThreadRightPanelState(
762 byThreadKey: Record<string, ThreadRightPanelState>,
763 ref: ScopedThreadRef | null | undefined,
764): ThreadRightPanelState {
765 if (!ref) return EMPTY_THREAD_STATE;
766 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
767}
768
769export function selectThreadPanelVisibility(
770 byThreadKey: Record<string, ThreadPanelVisibility>,
771 ref: ScopedThreadRef | null | undefined,
772): ThreadPanelVisibility {
773 if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY;
774 return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
775}
776
777export function selectThreadPanelOpen(
778 byThreadKey: Record<string, ThreadPanelVisibility>,
779 ref: ScopedThreadRef | null | undefined,
780 presentation: ThreadPanelPresentation,
781): boolean {
782 const visibility = selectThreadPanelVisibility(byThreadKey, ref);
783 return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
784}
785
786export function selectActiveRightPanel(
787 byThreadKey: Record<string, ThreadRightPanelState>,
788 ref: ScopedThreadRef | null | undefined,
789): RightPanelKind | null {
790 const state = selectThreadRightPanelState(byThreadKey, ref);
791 if (!state.isOpen) return null;
792 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
793}
794
795export function selectActiveRightPanelSurface(
796 byThreadKey: Record<string, ThreadRightPanelState>,
797 ref: ScopedThreadRef | null | undefined,
798): RightPanelSurface | null {
799 const state = selectThreadRightPanelState(byThreadKey, ref);
800 if (!state.isOpen) return null;
801 return selectSelectedRightPanelSurface(byThreadKey, ref);
802}
803
804/** The selected surface even while the panel is hidden, so a layout control can restore it. */
805export function selectSelectedRightPanelSurface(
806 byThreadKey: Record<string, ThreadRightPanelState>,
807 ref: ScopedThreadRef | null | undefined,
808): RightPanelSurface | null {
809 const state = selectThreadRightPanelState(byThreadKey, ref);
810 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
811}