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