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

rightPanelStore.ts

911 lines35.2 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" }>,
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 ) {
501 return state;
502 }
503 opened = true;
504 return automaticUpdate(state, threadKey, (current) => upsertSurface(current, surface));
505 });
506 return opened;
507 },
508 open: (ref, kind) =>
509 set((state) =>
510 userAction(state, scopedThreadKey(ref), (current) => {
511 if (kind === "preview") {
512 const existing = current.surfaces.find((surface) => surface.kind === "preview");
513 return upsertSurface(current, existing ?? browserSurface(null));
514 }
515 return upsertSurface(current, singletonSurface(kind));
516 }),
517 ),
518 openDevice: (ref, target, automatic = false) =>
519 set((state) =>
520 (automatic ? automaticUpdate : userAction)(state, scopedThreadKey(ref), (current) => {
521 const id =
522 `device:${encodeURIComponent(target.hostId)}:${encodeURIComponent(target.deviceId)}` as const;
523 if (automatic && current.dismissedDeviceSurfaceIds?.includes(id)) return current;
524 const surface: RightPanelSurface = { id, kind: "device", target };
525 const existing = current.surfaces.find((entry) => entry.id === id);
526 const surfaces = existing
527 ? current.surfaces.filter((entry) => entry.id !== "device")
528 : current.surfaces.map((entry) => (entry.id === "device" ? surface : entry));
529 return upsertSurface(
530 {
531 ...current,
532 surfaces,
533 dismissedDeviceSurfaceIds: (current.dismissedDeviceSurfaceIds ?? []).filter(
534 (entry) => entry !== id,
535 ),
536 },
537 existing ?? surface,
538 );
539 }),
540 ),
541 renameDevice: (ref, surfaceId, title) =>
542 set((state) =>
543 userAction(state, scopedThreadKey(ref), (current) => ({
544 ...current,
545 surfaces: current.surfaces.map((surface) =>
546 surface.id === surfaceId && surface.kind === "device"
547 ? { ...surface, title: title.trim() || surface.target?.name || "Device" }
548 : surface,
549 ),
550 })),
551 ),
552 openBrowser: (ref, tabId) =>
553 set((state) =>
554 userAction(state, scopedThreadKey(ref), (current) => {
555 const surface = browserSurface(tabId);
556 const withoutPlaceholder = tabId
557 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
558 : current.surfaces;
559 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
560 }),
561 ),
562 openPullRequest: (ref, target) =>
563 set((state) =>
564 userAction(state, scopedThreadKey(ref), (current) => {
565 const surface = pullRequestSurface(target);
566 const next = upsertSurface(current, surface);
567 return target.url
568 ? {
569 ...next,
570 surfaces: next.surfaces.map((entry) =>
571 entry.id === surface.id ? surface : entry,
572 ),
573 }
574 : next;
575 }),
576 ),
577 openFile: (ref, relativePath, line) =>
578 set((state) =>
579 userAction(state, scopedThreadKey(ref), (current) => {
580 const withoutStandaloneExplorer = current.surfaces.filter(
581 (surface) => surface.kind !== "files",
582 );
583 const surfaceId = `file:${relativePath}` as const;
584 const existing = withoutStandaloneExplorer.find(
585 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
586 surface.id === surfaceId && surface.kind === "file",
587 );
588 const surface = fileSurface(
589 relativePath,
590 normalizeRevealLine(line),
591 (existing?.revealRequestId ?? 0) + 1,
592 );
593 return {
594 isOpen: true,
595 activeSurfaceId: surface.id,
596 surfaces: existing
597 ? withoutStandaloneExplorer.map((entry) =>
598 entry.id === surface.id ? surface : entry,
599 )
600 : [...withoutStandaloneExplorer, surface],
601 };
602 }),
603 ),
604 openAttachment: (ref, attachment) =>
605 set((state) =>
606 userAction(state, scopedThreadKey(ref), (current) => {
607 const withoutStandaloneExplorer = current.surfaces.filter(
608 (surface) => surface.kind !== "files",
609 );
610 return upsertSurface(
611 { ...current, surfaces: withoutStandaloneExplorer },
612 attachmentSurface(attachment),
613 );
614 }),
615 ),
616 openTerminal: (ref, terminalId) =>
617 set((state) =>
618 userAction(state, scopedThreadKey(ref), (current) =>
619 upsertSurface(current, terminalSurface(terminalId)),
620 ),
621 ),
622 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
623 set((state) =>
624 userAction(state, scopedThreadKey(ref), (current) => ({
625 ...current,
626 isOpen: true,
627 activeSurfaceId: surfaceId,
628 surfaces: current.surfaces.map((surface) => {
629 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
630 const { splitDirection: _splitDirection, ...baseSurface } = surface;
631 return {
632 ...baseSurface,
633 terminalIds: surface.terminalIds.includes(terminalId)
634 ? surface.terminalIds
635 : [...surface.terminalIds, terminalId],
636 activeTerminalId: terminalId,
637 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
638 };
639 }),
640 })),
641 ),
642 activateTerminal: (ref, surfaceId, terminalId) =>
643 set((state) =>
644 userAction(state, scopedThreadKey(ref), (current) => ({
645 ...current,
646 activeSurfaceId: surfaceId,
647 surfaces: current.surfaces.map((surface) =>
648 surface.id === surfaceId &&
649 surface.kind === "terminal" &&
650 surface.terminalIds.includes(terminalId)
651 ? { ...surface, activeTerminalId: terminalId }
652 : surface,
653 ),
654 })),
655 ),
656 closeTerminal: (ref, surfaceId, terminalId) =>
657 set((state) =>
658 userAction(state, scopedThreadKey(ref), (current) => {
659 const surface = current.surfaces.find(
660 (entry) => entry.id === surfaceId && entry.kind === "terminal",
661 );
662 if (!surface || surface.kind !== "terminal") return current;
663 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
664 if (terminalIds.length === 0) {
665 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
666 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
667 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
668 return {
669 ...current,
670 isOpen: surfaces.length > 0 && current.isOpen,
671 surfaces,
672 activeSurfaceId:
673 current.activeSurfaceId === surfaceId
674 ? (fallback?.id ?? null)
675 : current.activeSurfaceId,
676 };
677 }
678 return {
679 ...current,
680 surfaces: current.surfaces.map((entry) =>
681 entry.id === surfaceId && entry.kind === "terminal"
682 ? {
683 ...entry,
684 terminalIds,
685 activeTerminalId:
686 entry.activeTerminalId === terminalId
687 ? (terminalIds.at(-1) ?? terminalIds[0]!)
688 : entry.activeTerminalId,
689 }
690 : entry,
691 ),
692 };
693 }),
694 ),
695 activateSurface: (ref, surfaceId) =>
696 set((state) =>
697 userAction(state, scopedThreadKey(ref), (current) =>
698 current.surfaces.some((surface) => surface.id === surfaceId)
699 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
700 : current,
701 ),
702 ),
703 closeSurface: (ref, surfaceId) =>
704 set((state) =>
705 userAction(state, scopedThreadKey(ref), (current) => {
706 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
707 if (index < 0) return current;
708 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
709 if (current.activeSurfaceId !== surfaceId) {
710 return { ...current, isOpen: surfaces.length > 0 && current.isOpen, surfaces };
711 }
712 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
713 return {
714 ...current,
715 isOpen: surfaces.length > 0 && current.isOpen,
716 surfaces,
717 activeSurfaceId: fallback?.id ?? null,
718 };
719 }),
720 ),
721 closeOtherSurfaces: (ref, surfaceId) =>
722 set((state) =>
723 userAction(state, scopedThreadKey(ref), (current) => {
724 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
725 if (!surface || current.surfaces.length === 1) return current;
726 return {
727 ...current,
728 isOpen: true,
729 surfaces: [surface],
730 activeSurfaceId: surface.id,
731 };
732 }),
733 ),
734 closeSurfacesToRight: (ref, surfaceId) =>
735 set((state) =>
736 userAction(state, scopedThreadKey(ref), (current) => {
737 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
738 if (index < 0 || index === current.surfaces.length - 1) return current;
739 const surfaces = current.surfaces.slice(0, index + 1);
740 const activeStillExists = surfaces.some(
741 (surface) => surface.id === current.activeSurfaceId,
742 );
743 return {
744 ...current,
745 surfaces,
746 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
747 };
748 }),
749 ),
750 closeAllSurfaces: (ref) =>
751 set((state) =>
752 userAction(state, scopedThreadKey(ref), (current) =>
753 current.surfaces.length === 0
754 ? current
755 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
756 ),
757 ),
758 reconcileBrowserSurfaces: (ref, tabIds) =>
759 set((state) =>
760 automaticUpdate(state, scopedThreadKey(ref), (current) => {
761 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
762 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
763 const existingBrowser = current.surfaces.filter(
764 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
765 surface.kind === "preview" &&
766 surface.id !== "browser:new" &&
767 validIds.has(surface.id),
768 );
769 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
770 const added = tabIds
771 .filter((tabId) => !knownIds.has(`browser:${tabId}`))
772 .map((tabId) => browserSurface(tabId));
773 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
774 const activeStillExists = surfaces.some(
775 (surface) => surface.id === current.activeSurfaceId,
776 );
777 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
778 return {
779 ...current,
780 surfaces,
781 activeSurfaceId: activeStillExists
782 ? current.activeSurfaceId
783 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
784 };
785 }),
786 ),
787 reconcileFileSurfaces: (ref, workspaceAvailable) =>
788 set((state) =>
789 automaticUpdate(state, scopedThreadKey(ref), (current) => {
790 if (workspaceAvailable) return current;
791 const surfaces = current.surfaces.filter(
792 (surface) =>
793 surface.kind !== "files" &&
794 (surface.kind !== "file" || surface.attachment !== undefined),
795 );
796 if (surfaces.length === current.surfaces.length) return current;
797 const activeStillExists = surfaces.some(
798 (surface) => surface.id === current.activeSurfaceId,
799 );
800 return {
801 ...current,
802 isOpen: surfaces.length > 0 ? current.isOpen : false,
803 surfaces,
804 activeSurfaceId: activeStillExists
805 ? current.activeSurfaceId
806 : (surfaces.at(-1)?.id ?? null),
807 };
808 }),
809 ),
810 show: (ref) =>
811 set((state) =>
812 userAction(state, scopedThreadKey(ref), (current) =>
813 current.isOpen ? current : { ...current, isOpen: true },
814 ),
815 ),
816 close: (ref) =>
817 set((state) =>
818 userAction(state, scopedThreadKey(ref), (current) =>
819 current.isOpen ? { ...current, isOpen: false } : current,
820 ),
821 ),
822 toggleVisibility: (ref) =>
823 set((state) =>
824 userAction(state, scopedThreadKey(ref), (current) => ({
825 ...current,
826 isOpen: !current.isOpen,
827 })),
828 ),
829 toggle: (ref, kind) =>
830 set((state) =>
831 userAction(state, scopedThreadKey(ref), (current) => {
832 const active = current.surfaces.find(
833 (surface) => surface.id === current.activeSurfaceId,
834 );
835 if (current.isOpen && active?.kind === kind) {
836 return { ...current, isOpen: false };
837 }
838 if (kind === "preview") {
839 const existing = current.surfaces.find((surface) => surface.kind === "preview");
840 return upsertSurface(current, existing ?? browserSurface(null));
841 }
842 return upsertSurface(current, singletonSurface(kind));
843 }),
844 ),
845 removeThread: (ref) =>
846 set((state) => {
847 const threadKey = scopedThreadKey(ref);
848 if (
849 !(threadKey in state.byThreadKey) &&
850 !(threadKey in state.userActionRevisionByThreadKey)
851 ) {
852 return state;
853 }
854 const { [threadKey]: _removed, ...rest } = state.byThreadKey;
855 const { [threadKey]: _revision, ...userActionRevisionByThreadKey } =
856 state.userActionRevisionByThreadKey;
857 return { byThreadKey: rest, userActionRevisionByThreadKey };
858 }),
859 }),
860 {
861 name: RIGHT_PANEL_STORAGE_KEY,
862 version: RIGHT_PANEL_STORAGE_VERSION,
863 storage: createJSONStorage(() =>
864 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
865 ),
866 partialize: (state) => ({
867 byThreadKey: Object.fromEntries(
868 Object.entries(state.byThreadKey).filter(
869 ([threadKey]) => !isPullRequestsPanelKey(threadKey),
870 ),
871 ),
872 }),
873 migrate: migratePersistedRightPanelState,
874 },
875 ),
876);
877​
878export function selectThreadRightPanelState(
879 byThreadKey: Record<string, ThreadRightPanelState>,
880 ref: ScopedThreadRef | null | undefined,
881): ThreadRightPanelState {
882 if (!ref) return EMPTY_THREAD_STATE;
883 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
885​
886export function selectActiveRightPanel(
887 byThreadKey: Record<string, ThreadRightPanelState>,
888 ref: ScopedThreadRef | null | undefined,
889): RightPanelKind | null {
890 const state = selectThreadRightPanelState(byThreadKey, ref);
891 if (!state.isOpen) return null;
892 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
894​
895export function selectActiveRightPanelSurface(
896 byThreadKey: Record<string, ThreadRightPanelState>,
897 ref: ScopedThreadRef | null | undefined,
898): RightPanelSurface | null {
899 const state = selectThreadRightPanelState(byThreadKey, ref);
900 if (!state.isOpen) return null;
901 return selectSelectedRightPanelSurface(byThreadKey, ref);
903​
904/** The selected surface even while the panel is hidden, so a layout control can restore it. */
905export function selectSelectedRightPanelSurface(
906 byThreadKey: Record<string, ThreadRightPanelState>,
907 ref: ScopedThreadRef | null | undefined,
908): RightPanelSurface | null {
909 const state = selectThreadRightPanelState(byThreadKey, ref);
910 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;