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

rightPanelStore.ts

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