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

rightPanelStore.ts

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