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

rightPanelStore.ts

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