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