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