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