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, requestedPath, line) =>
579 set((state) =>
580 userAction(state, scopedThreadKey(ref), (current) => {
581 if (requestedPath === ".") {
582 return upsertSurface(current, singletonSurface("files"));
583 }
584 // Workspace entry paths use '/', including on Windows.
585 const relativePath = /^[A-Za-z]:\/+$/.test(requestedPath)
586 ? requestedPath
587 : requestedPath.replace(/\/+$/, "") || requestedPath;
588 const withoutStandaloneExplorer = current.surfaces.filter(
589 (surface) => surface.kind !== "files",
590 );
591 const surfaceId = `file:${relativePath}` as const;
592 const existing = withoutStandaloneExplorer.find(
593 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
594 surface.id === surfaceId && surface.kind === "file",
595 );
596 const surface = fileSurface(
597 relativePath,
598 normalizeRevealLine(line),
599 (existing?.revealRequestId ?? 0) + 1,
600 );
601 return {
602 isOpen: true,
603 activeSurfaceId: surface.id,
604 surfaces: existing
605 ? withoutStandaloneExplorer.map((entry) =>
606 entry.id === surface.id ? surface : entry,
607 )
608 : [...withoutStandaloneExplorer, surface],
609 };
610 }),
611 ),
612 openAttachment: (ref, attachment) =>
613 set((state) =>
614 userAction(state, scopedThreadKey(ref), (current) => {
615 const withoutStandaloneExplorer = current.surfaces.filter(
616 (surface) => surface.kind !== "files",
617 );
618 return upsertSurface(
619 { ...current, surfaces: withoutStandaloneExplorer },
620 attachmentSurface(attachment),
621 );
622 }),
623 ),
624 openTerminal: (ref, terminalId) =>
625 set((state) =>
626 userAction(state, scopedThreadKey(ref), (current) =>
627 upsertSurface(current, terminalSurface(terminalId)),
628 ),
629 ),
630 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
631 set((state) =>
632 userAction(state, scopedThreadKey(ref), (current) => ({
633 ...current,
634 isOpen: true,
635 activeSurfaceId: surfaceId,
636 surfaces: current.surfaces.map((surface) => {
637 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
638 const { splitDirection: _splitDirection, ...baseSurface } = surface;
639 return {
640 ...baseSurface,
641 terminalIds: surface.terminalIds.includes(terminalId)
642 ? surface.terminalIds
643 : [...surface.terminalIds, terminalId],
644 activeTerminalId: terminalId,
645 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
646 };
647 }),
648 })),
649 ),
650 activateTerminal: (ref, surfaceId, terminalId) =>
651 set((state) =>
652 userAction(state, scopedThreadKey(ref), (current) => ({
653 ...current,
654 activeSurfaceId: surfaceId,
655 surfaces: current.surfaces.map((surface) =>
656 surface.id === surfaceId &&
657 surface.kind === "terminal" &&
658 surface.terminalIds.includes(terminalId)
659 ? { ...surface, activeTerminalId: terminalId }
660 : surface,
661 ),
662 })),
663 ),
664 closeTerminal: (ref, surfaceId, terminalId) =>
665 set((state) =>
666 userAction(state, scopedThreadKey(ref), (current) => {
667 const surface = current.surfaces.find(
668 (entry) => entry.id === surfaceId && entry.kind === "terminal",
669 );
670 if (!surface || surface.kind !== "terminal") return current;
671 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
672 if (terminalIds.length === 0) {
673 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
674 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
675 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
676 return {
677 ...current,
678 isOpen: surfaces.length > 0 && current.isOpen,
679 surfaces,
680 activeSurfaceId:
681 current.activeSurfaceId === surfaceId
682 ? (fallback?.id ?? null)
683 : current.activeSurfaceId,
684 };
685 }
686 return {
687 ...current,
688 surfaces: current.surfaces.map((entry) =>
689 entry.id === surfaceId && entry.kind === "terminal"
690 ? {
691 ...entry,
692 terminalIds,
693 activeTerminalId:
694 entry.activeTerminalId === terminalId
695 ? (terminalIds.at(-1) ?? terminalIds[0]!)
696 : entry.activeTerminalId,
697 }
698 : entry,
699 ),
700 };
701 }),
702 ),
703 activateSurface: (ref, surfaceId) =>
704 set((state) =>
705 userAction(state, scopedThreadKey(ref), (current) =>
706 current.surfaces.some((surface) => surface.id === surfaceId)
707 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
708 : current,
709 ),
710 ),
711 closeSurface: (ref, surfaceId) =>
712 set((state) =>
713 userAction(state, scopedThreadKey(ref), (current) => {
714 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
715 if (index < 0) return current;
716 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
717 if (current.activeSurfaceId !== surfaceId) {
718 return { ...current, isOpen: surfaces.length > 0 && current.isOpen, surfaces };
719 }
720 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
721 return {
722 ...current,
723 isOpen: surfaces.length > 0 && current.isOpen,
724 surfaces,
725 activeSurfaceId: fallback?.id ?? null,
726 };
727 }),
728 ),
729 closeOtherSurfaces: (ref, surfaceId) =>
730 set((state) =>
731 userAction(state, scopedThreadKey(ref), (current) => {
732 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
733 if (!surface || current.surfaces.length === 1) return current;
734 return {
735 ...current,
736 isOpen: true,
737 surfaces: [surface],
738 activeSurfaceId: surface.id,
739 };
740 }),
741 ),
742 closeSurfacesToRight: (ref, surfaceId) =>
743 set((state) =>
744 userAction(state, scopedThreadKey(ref), (current) => {
745 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
746 if (index < 0 || index === current.surfaces.length - 1) return current;
747 const surfaces = current.surfaces.slice(0, index + 1);
748 const activeStillExists = surfaces.some(
749 (surface) => surface.id === current.activeSurfaceId,
750 );
751 return {
752 ...current,
753 surfaces,
754 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
755 };
756 }),
757 ),
758 closeAllSurfaces: (ref) =>
759 set((state) =>
760 userAction(state, scopedThreadKey(ref), (current) =>
761 current.surfaces.length === 0
762 ? current
763 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
764 ),
765 ),
766 reconcileBrowserSurfaces: (ref, tabIds) =>
767 set((state) =>
768 automaticUpdate(state, scopedThreadKey(ref), (current) => {
769 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
770 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
771 const existingBrowser = current.surfaces.filter(
772 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
773 surface.kind === "preview" &&
774 surface.id !== "browser:new" &&
775 validIds.has(surface.id),
776 );
777 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
778 const added = tabIds
779 .filter((tabId) => !knownIds.has(`browser:${tabId}`))
780 .map((tabId) => browserSurface(tabId));
781 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
782 const activeStillExists = surfaces.some(
783 (surface) => surface.id === current.activeSurfaceId,
784 );
785 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
786 return {
787 ...current,
788 surfaces,
789 activeSurfaceId: activeStillExists
790 ? current.activeSurfaceId
791 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
792 };
793 }),
794 ),
795 reconcileFileSurfaces: (ref, workspaceAvailable) =>
796 set((state) =>
797 automaticUpdate(state, scopedThreadKey(ref), (current) => {
798 if (workspaceAvailable) return current;
799 const surfaces = current.surfaces.filter(
800 (surface) =>
801 surface.kind !== "files" &&
802 (surface.kind !== "file" || surface.attachment !== undefined),
803 );
804 if (surfaces.length === current.surfaces.length) return current;
805 const activeStillExists = surfaces.some(
806 (surface) => surface.id === current.activeSurfaceId,
807 );
808 return {
809 ...current,
810 isOpen: surfaces.length > 0 ? current.isOpen : false,
811 surfaces,
812 activeSurfaceId: activeStillExists
813 ? current.activeSurfaceId
814 : (surfaces.at(-1)?.id ?? null),
815 };
816 }),
817 ),
818 show: (ref) =>
819 set((state) =>
820 userAction(state, scopedThreadKey(ref), (current) =>
821 current.isOpen ? current : { ...current, isOpen: true },
822 ),
823 ),
824 close: (ref) =>
825 set((state) =>
826 userAction(state, scopedThreadKey(ref), (current) =>
827 current.isOpen ? { ...current, isOpen: false } : current,
828 ),
829 ),
830 toggleVisibility: (ref) =>
831 set((state) =>
832 userAction(state, scopedThreadKey(ref), (current) => ({
833 ...current,
834 isOpen: !current.isOpen,
835 })),
836 ),
837 toggle: (ref, kind) =>
838 set((state) =>
839 userAction(state, scopedThreadKey(ref), (current) => {
840 const active = current.surfaces.find(
841 (surface) => surface.id === current.activeSurfaceId,
842 );
843 if (current.isOpen && active?.kind === kind) {
844 return { ...current, isOpen: false };
845 }
846 if (kind === "preview") {
847 const existing = current.surfaces.find((surface) => surface.kind === "preview");
848 return upsertSurface(current, existing ?? browserSurface(null));
849 }
850 return upsertSurface(current, singletonSurface(kind));
851 }),
852 ),
853 removeThread: (ref) =>
854 set((state) => {
855 const threadKey = scopedThreadKey(ref);
856 if (
857 !(threadKey in state.byThreadKey) &&
858 !(threadKey in state.userActionRevisionByThreadKey)
859 ) {
860 return state;
861 }
862 const { [threadKey]: _removed, ...rest } = state.byThreadKey;
863 const { [threadKey]: _revision, ...userActionRevisionByThreadKey } =
864 state.userActionRevisionByThreadKey;
865 return { byThreadKey: rest, userActionRevisionByThreadKey };
866 }),
867 }),
868 {
869 name: RIGHT_PANEL_STORAGE_KEY,
870 version: RIGHT_PANEL_STORAGE_VERSION,
871 storage: createJSONStorage(() =>
872 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
873 ),
874 partialize: (state) => ({
875 byThreadKey: Object.fromEntries(
876 Object.entries(state.byThreadKey).filter(
877 ([threadKey]) => !isPullRequestsPanelKey(threadKey),
878 ),
879 ),
880 }),
881 migrate: migratePersistedRightPanelState,
882 },
883 ),
884);
885
886export function selectThreadRightPanelState(
887 byThreadKey: Record<string, ThreadRightPanelState>,
888 ref: ScopedThreadRef | null | undefined,
889): ThreadRightPanelState {
890 if (!ref) return EMPTY_THREAD_STATE;
891 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
892}
893
894export function selectActiveRightPanel(
895 byThreadKey: Record<string, ThreadRightPanelState>,
896 ref: ScopedThreadRef | null | undefined,
897): RightPanelKind | null {
898 const state = selectThreadRightPanelState(byThreadKey, ref);
899 if (!state.isOpen) return null;
900 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
901}
902
903export function selectActiveRightPanelSurface(
904 byThreadKey: Record<string, ThreadRightPanelState>,
905 ref: ScopedThreadRef | null | undefined,
906): RightPanelSurface | null {
907 const state = selectThreadRightPanelState(byThreadKey, ref);
908 if (!state.isOpen) return null;
909 return selectSelectedRightPanelSurface(byThreadKey, ref);
910}
911
912/** The selected surface even while the panel is hidden, so a layout control can restore it. */
913export function selectSelectedRightPanelSurface(
914 byThreadKey: Record<string, ThreadRightPanelState>,
915 ref: ScopedThreadRef | null | undefined,
916): RightPanelSurface | null {
917 const state = selectThreadRightPanelState(byThreadKey, ref);
918 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
919}