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

rightPanelStore.ts

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