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 {
11 parseScopedThreadKey,
12 scopedThreadKey,
13 scopeThreadRef,
14} from "@t3tools/client-runtime/environment";
15import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
16import { create } from "zustand";
17import { createJSONStorage, persist } from "zustand/middleware";
18
19import { useClosedViewStore } from "./closedViewStore";
20import { resolveStorage } from "./lib/storage";
21import type { ThreadPanelPresentation } from "./rightPanelLayout";
22import type { ChatFileAttachment } from "./types";
23
24const RIGHT_PANEL_KINDS = [
25 "diff",
26 "files",
27 "file",
28 "preview",
29 "device",
30 "terminal",
31 "pull-request",
32 "pull-requests",
33] as const;
34export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
35
36export interface DeviceTabTarget {
37 hostId: string;
38 deviceId: string;
39 platform: "ios" | "android";
40 name: string;
41}
42
43export type RightPanelSurface =
44 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
45 | { id: "browser:new"; kind: "preview"; resourceId: null }
46 | { id: "device" | `device:${string}`; kind: "device"; target?: DeviceTabTarget; title?: string }
47 | {
48 id: `terminal:${string}`;
49 kind: "terminal";
50 resourceId: string;
51 terminalIds: string[];
52 activeTerminalId: string;
53 splitDirection?: "horizontal" | "vertical";
54 }
55 | { id: "diff"; kind: "diff" }
56 | { id: "files"; kind: "files" }
57 | {
58 id: `file:${string}` | `attachment:${string}`;
59 kind: "file";
60 /** Workspace-relative, or absolute for a host file outside the workspace. */
61 relativePath: string;
62 revealLine: number | null;
63 revealRequestId: number;
64 /** Present when the file lives in the thread's attachment store rather
65 than at a workspace or host path. */
66 attachment?: ChatFileAttachment;
67 }
68 | {
69 /**
70 * A change request opened beside a thread or in the pull-request list's shared panel.
71 * The reference lives in the id so several pull requests can remain open as peer tabs.
72 */
73 id: `pull-request:${string}`;
74 kind: "pull-request";
75 /**
76 * Which server the change request was read from. The list spans every connected one, so
77 * two of them can hold the same project id; a panel beside a thread leaves this out and
78 * takes the environment from its own ref.
79 */
80 environmentId?: string;
81 projectId: string;
82 host?: string;
83 repository: string;
84 number: number;
85 url?: string;
86 }
87 /** The thread's linked pull requests, one singleton tab beside any number of `pull-request` tabs. */
88 | { id: "pull-requests"; kind: "pull-requests" };
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.
95// v14 removes the agents surface; lineage lives in the thread title bar.
96const RIGHT_PANEL_STORAGE_VERSION = 14;
97
98/** A fixed workspace-level ref: each PR surface carries its own real environment. */
99export const PULL_REQUESTS_PANEL_REF = scopeThreadRef(
100 EnvironmentId.make("pull-requests-panel"),
101 ThreadId.make("pull-requests-panel"),
102);
103
104/**
105 * The pull-request list's shared panel is session
106 * state: reopening the app should show the list, not last session's tabs and detail fetches.
107 */
108const isPullRequestsPanelKey = (threadKey: string) => threadKey.endsWith(":pull-requests-panel");
109
110export interface ThreadRightPanelState {
111 isOpen: boolean;
112 activeSurfaceId: string | null;
113 surfaces: RightPanelSurface[];
114 dismissedDeviceSurfaceIds?: string[];
115}
116
117export interface ThreadPanelVisibility {
118 inlineOpen: boolean;
119 popoverOpen: boolean;
120}
121
122interface RightPanelStoreState {
123 byThreadKey: Record<string, ThreadRightPanelState>;
124 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
125 /** Session-only count of user panel choices per thread. Automatic updates do not advance it. */
126 userActionRevisionByThreadKey: Record<string, number>;
127 closeRevisionByThreadKey: Record<string, number>;
128 getUserActionRevision: (ref: ScopedThreadRef) => number;
129 /**
130 * Open a surface on behalf of the app, not the user. Refused when the user
131 * made a panel choice after `expectedUserActionRevision` was read.
132 */
133 openProactive: (
134 ref: ScopedThreadRef,
135 surface: Extract<RightPanelSurface, { kind: "diff" | "pull-request" | "pull-requests" }>,
136 expectedUserActionRevision: number,
137 ) => boolean;
138 open: (
139 ref: ScopedThreadRef,
140 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
141 ) => void;
142 openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void;
143 renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;
144 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
145 openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
146 openAttachment: (ref: ScopedThreadRef, attachment: ChatFileAttachment) => void;
147 openPullRequest: (
148 ref: ScopedThreadRef,
149 target: {
150 environmentId?: string;
151 projectId: string;
152 host?: string;
153 repository: string;
154 number: number;
155 url?: string;
156 },
157 ) => void;
158 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
159 splitTerminal: (
160 ref: ScopedThreadRef,
161 surfaceId: string,
162 terminalId: string,
163 direction?: "horizontal" | "vertical",
164 ) => void;
165 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
166 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
167 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
168 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
169 closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
170 closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
171 closeAllSurfaces: (ref: ScopedThreadRef) => void;
172 reconcileBrowserSurfaces: (
173 ref: ScopedThreadRef,
174 tabIds: readonly string[],
175 hiddenTabIds?: ReadonlySet<string>,
176 ) => void;
177 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
178 show: (ref: ScopedThreadRef) => void;
179 close: (ref: ScopedThreadRef) => void;
180 toggleVisibility: (ref: ScopedThreadRef) => void;
181 toggle: (
182 ref: ScopedThreadRef,
183 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
184 ) => void;
185 setThreadPanelOpen: (
186 ref: ScopedThreadRef,
187 presentation: ThreadPanelPresentation,
188 open: boolean,
189 ) => void;
190 toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
191 removeThread: (ref: ScopedThreadRef) => void;
192}
193
194const EMPTY_THREAD_STATE: ThreadRightPanelState = {
195 isOpen: false,
196 activeSurfaceId: null,
197 surfaces: [],
198};
199
200const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
201 inlineOpen: true,
202 popoverOpen: false,
203};
204
205const singletonSurface = (
206 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request">,
207): RightPanelSurface => {
208 switch (kind) {
209 case "diff":
210 return { id: "diff", kind };
211 case "files":
212 return { id: "files", kind };
213 case "pull-requests":
214 return { id: "pull-requests", kind };
215 case "device":
216 return { id: "device", kind };
217 }
218};
219
220const browserSurface = (tabId: string | null): RightPanelSurface =>
221 tabId
222 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
223 : { id: "browser:new", kind: "preview", resourceId: null };
224
225const fileSurface = (
226 relativePath: string,
227 revealLine: number | null,
228 revealRequestId: number,
229): RightPanelSurface => ({
230 id: `file:${relativePath}`,
231 kind: "file",
232 relativePath,
233 revealLine,
234 revealRequestId,
235});
236
237const attachmentSurface = (attachment: ChatFileAttachment): RightPanelSurface => ({
238 id: `attachment:${attachment.id}`,
239 kind: "file",
240 relativePath: attachment.name,
241 revealLine: null,
242 revealRequestId: 0,
243 attachment,
244});
245
246const terminalSurface = (terminalId: string): RightPanelSurface => ({
247 id: `terminal:${terminalId}`,
248 kind: "terminal",
249 resourceId: terminalId,
250 terminalIds: [terminalId],
251 activeTerminalId: terminalId,
252});
253
254export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-request" }>;
255
256export function pullRequestSurfaceId(target: {
257 environmentId?: string;
258 projectId: string;
259 host?: string;
260 repository: string;
261 number: number;
262}): PullRequestSurface["id"] {
263 // The environment leads the id where there is one, so the same change request read from two
264 // servers is two tabs rather than one tab that changes its mind about which server it is on.
265 const scope =
266 target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
267 const host = target.host === undefined ? "" : `${encodeURIComponent(target.host.toLowerCase())}:`;
268 return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${host}${encodeURIComponent(target.repository)}:${target.number}`;
269}
270
271export function pullRequestSurface(target: {
272 environmentId?: string;
273 projectId: string;
274 host?: string;
275 repository: string;
276 number: number;
277 url?: string;
278}): PullRequestSurface {
279 return {
280 id: pullRequestSurfaceId(target),
281 kind: "pull-request",
282 ...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
283 projectId: target.projectId,
284 ...(typeof target.host === "string" ? { host: target.host.toLowerCase() } : {}),
285 repository: target.repository,
286 number: target.number,
287 ...(typeof target.url === "string" ? { url: target.url } : {}),
288 };
289}
290
291const upsertSurface = (
292 current: ThreadRightPanelState,
293 surface: RightPanelSurface,
294 activate = true,
295): ThreadRightPanelState => ({
296 ...current,
297 isOpen: true,
298 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
299 ? current.surfaces
300 : [...current.surfaces, surface],
301 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
302});
303
304const updateThreadStateMap = (
305 byThreadKey: Record<string, ThreadRightPanelState>,
306 threadKey: string,
307 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
308): Record<string, ThreadRightPanelState> => {
309 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
310 const next = updater(current);
311 if (
312 !next.isOpen &&
313 next.activeSurfaceId === null &&
314 next.surfaces.length === 0 &&
315 !next.dismissedDeviceSurfaceIds?.length
316 ) {
317 if (!(threadKey in byThreadKey)) return byThreadKey;
318 const { [threadKey]: _removed, ...rest } = byThreadKey;
319 return rest;
320 }
321 if (next === current) return byThreadKey;
322 return { ...byThreadKey, [threadKey]: next };
323};
324
325const updateThreadPanelVisibilityMap = (
326 byThreadKey: Record<string, ThreadPanelVisibility>,
327 threadKey: string,
328 updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
329): Record<string, ThreadPanelVisibility> => {
330 const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
331 const next = updater(current);
332 if (next.inlineOpen && !next.popoverOpen) {
333 if (!(threadKey in byThreadKey)) return byThreadKey;
334 const { [threadKey]: _removed, ...rest } = byThreadKey;
335 return rest;
336 }
337 if (next === current) return byThreadKey;
338 return { ...byThreadKey, [threadKey]: next };
339};
340
341type RightPanelStoreData = Pick<
342 RightPanelStoreState,
343 "byThreadKey" | "threadPanelVisibilityByThreadKey"
344>;
345
346/**
347 * Applies a real right-panel mutation and its thread-panel transition atomically.
348 * This is the only path real panel actions use, so visibility never has to be
349 * reconciled after the fact in React.
350 */
351const updateThread = (
352 state: RightPanelStoreData,
353 threadKey: string,
354 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
355): RightPanelStoreData => {
356 const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
357 const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
358 const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
359 let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
360
361 if (!current.isOpen && next.isOpen) {
362 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
363 threadPanelVisibilityByThreadKey,
364 threadKey,
365 (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
366 );
367 } else if (current.isOpen && !next.isOpen) {
368 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
369 threadPanelVisibilityByThreadKey,
370 threadKey,
371 (visibility) =>
372 visibility.popoverOpen && !visibility.inlineOpen
373 ? { ...visibility, inlineOpen: true }
374 : visibility,
375 );
376 }
377
378 return { byThreadKey, threadPanelVisibilityByThreadKey };
379};
380
381// Every store action is a user choice unless it goes through `automaticUpdate`.
382// Only `openProactive` and resource reconciliation are automatic, so a new
383// action counts as a user choice by default.
384const automaticUpdate = (
385 state: RightPanelStoreState,
386 threadKey: string,
387 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
388): Partial<RightPanelStoreState> => ({
389 ...updateThread(state, threadKey, updater),
390});
391
392const userAction = (
393 state: RightPanelStoreState,
394 threadKey: string,
395 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
396 closesView = false,
397): Partial<RightPanelStoreState> => ({
398 ...updateThread(state, threadKey, (current) => {
399 const next = updater(current);
400 if (next === current) return current;
401 const removedDevices = current.surfaces.filter(
402 (surface) =>
403 surface.kind === "device" && !next.surfaces.some((entry) => entry.id === surface.id),
404 );
405 if (removedDevices.length === 0) return next;
406 return {
407 ...next,
408 dismissedDeviceSurfaceIds: [
409 ...new Set([
410 ...(next.dismissedDeviceSurfaceIds ?? []),
411 ...removedDevices.map((surface) => surface.id),
412 ]),
413 ],
414 };
415 }),
416 userActionRevisionByThreadKey: {
417 ...state.userActionRevisionByThreadKey,
418 [threadKey]: (state.userActionRevisionByThreadKey[threadKey] ?? 0) + 1,
419 },
420 ...(closesView
421 ? {
422 closeRevisionByThreadKey: {
423 ...state.closeRevisionByThreadKey,
424 [threadKey]: (state.closeRevisionByThreadKey[threadKey] ?? 0) + 1,
425 },
426 }
427 : {}),
428});
429
430const closeAction = (
431 state: RightPanelStoreState,
432 threadKey: string,
433 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
434): Partial<RightPanelStoreState> => userAction(state, threadKey, updater, true);
435
436function normalizeRevealLine(line: number | undefined): number | null {
437 if (line === undefined || !Number.isFinite(line)) return null;
438 return Math.max(1, Math.trunc(line));
439}
440
441export function migratePersistedRightPanelState(persistedState: unknown): {
442 byThreadKey: Record<string, ThreadRightPanelState>;
443 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
444} {
445 if (!persistedState || typeof persistedState !== "object") {
446 return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
447 }
448 const byThreadKey =
449 "byThreadKey" in persistedState &&
450 persistedState.byThreadKey &&
451 typeof persistedState.byThreadKey === "object"
452 ? Object.fromEntries(
453 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>)
454 .filter(([threadKey]) => !isPullRequestsPanelKey(threadKey))
455 .map(([threadKey, threadState]) => {
456 const validThreadState =
457 threadState && typeof threadState === "object" ? threadState : null;
458 const surfaces = Array.isArray(validThreadState?.surfaces)
459 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
460 // Removed surfaces: plans render inline, agents in thread lineage.
461 const kind = (surface as { kind?: string }).kind;
462 if (kind === "plan" || kind === "agents") return [];
463 if (surface.kind === "file") {
464 const revealLine =
465 typeof surface.revealLine === "number" &&
466 Number.isFinite(surface.revealLine)
467 ? Math.max(1, Math.trunc(surface.revealLine))
468 : null;
469 const revealRequestId =
470 typeof surface.revealRequestId === "number" &&
471 Number.isSafeInteger(surface.revealRequestId) &&
472 surface.revealRequestId >= 0
473 ? surface.revealRequestId
474 : 0;
475 return [{ ...surface, revealLine, revealRequestId }];
476 }
477 if (surface.kind === "pull-request") {
478 if (
479 typeof surface.projectId !== "string" ||
480 typeof surface.repository !== "string" ||
481 typeof surface.number !== "number" ||
482 !Number.isSafeInteger(surface.number) ||
483 surface.number < 1
484 ) {
485 return [];
486 }
487 const { environmentId, ...rest } = surface;
488 // Anything else stored under that name is not an environment.
489 return [
490 pullRequestSurface({
491 ...rest,
492 ...(typeof environmentId === "string" ? { environmentId } : {}),
493 }),
494 ];
495 }
496 if (surface.kind !== "terminal") return [surface];
497 if (
498 !("resourceId" in surface) ||
499 typeof surface.resourceId !== "string" ||
500 surface.id !== `terminal:${surface.resourceId}`
501 ) {
502 return [];
503 }
504 const terminalIds =
505 "terminalIds" in surface && Array.isArray(surface.terminalIds)
506 ? [
507 ...new Set(
508 surface.terminalIds.filter(
509 (terminalId): terminalId is string =>
510 typeof terminalId === "string",
511 ),
512 ),
513 ]
514 : [surface.resourceId];
515 const activeTerminalId =
516 "activeTerminalId" in surface &&
517 typeof surface.activeTerminalId === "string" &&
518 terminalIds.includes(surface.activeTerminalId)
519 ? surface.activeTerminalId
520 : (terminalIds[0] ?? surface.resourceId);
521 return [
522 {
523 ...surface,
524 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
525 activeTerminalId,
526 },
527 ];
528 })
529 : [];
530 const rawActiveSurfaceId = validThreadState?.activeSurfaceId;
531 const persistedActiveSurfaceId = surfaces.some(
532 (surface) => surface.id === rawActiveSurfaceId,
533 )
534 ? (rawActiveSurfaceId ?? null)
535 : rawActiveSurfaceId === "pull-request"
536 ? (surfaces.find((surface) => surface.kind === "pull-request")?.id ?? null)
537 : null;
538 // A migration that dropped every surface (e.g. plan-only panels
539 // in v9) must not reopen an empty panel.
540 const isOpen =
541 surfaces.length > 0 &&
542 (typeof validThreadState?.isOpen === "boolean"
543 ? validThreadState.isOpen
544 : persistedActiveSurfaceId !== null);
545 // An open panel needs an active surface: if migration dropped
546 // the persisted one (e.g. plan was active), fall back to the
547 // first survivor instead of rendering an open empty panel. Removed
548 // agents selections also keep a survivor ready while the panel is closed.
549 const activeSurfaceId =
550 persistedActiveSurfaceId ??
551 (isOpen || rawActiveSurfaceId === "agents" ? (surfaces[0]?.id ?? null) : null);
552 return [
553 threadKey,
554 {
555 isOpen,
556 surfaces,
557 activeSurfaceId,
558 ...(Array.isArray(validThreadState?.dismissedDeviceSurfaceIds)
559 ? {
560 dismissedDeviceSurfaceIds:
561 validThreadState.dismissedDeviceSurfaceIds.filter(
562 (id): id is string => typeof id === "string",
563 ),
564 }
565 : {}),
566 },
567 ];
568 }),
569 )
570 : {};
571 const threadPanelVisibilityByThreadKey =
572 "threadPanelVisibilityByThreadKey" in persistedState &&
573 persistedState.threadPanelVisibilityByThreadKey &&
574 typeof persistedState.threadPanelVisibilityByThreadKey === "object"
575 ? Object.fromEntries(
576 Object.entries(
577 persistedState.threadPanelVisibilityByThreadKey as Record<string, unknown>,
578 ).flatMap(([threadKey, value]) => {
579 if (!value || typeof value !== "object" || !("inlineOpen" in value)) return [];
580 return value.inlineOpen === false
581 ? [[threadKey, { inlineOpen: false, popoverOpen: false }]]
582 : [];
583 }),
584 )
585 : {};
586 return { byThreadKey, threadPanelVisibilityByThreadKey };
587}
588
589export const useRightPanelStore = create<RightPanelStoreState>()(
590 persist(
591 (set, get) => ({
592 byThreadKey: {},
593 threadPanelVisibilityByThreadKey: {},
594 userActionRevisionByThreadKey: {},
595 closeRevisionByThreadKey: {},
596 getUserActionRevision: (ref) =>
597 get().userActionRevisionByThreadKey[scopedThreadKey(ref)] ?? 0,
598 openProactive: (ref, surface, expectedUserActionRevision) => {
599 let opened = false;
600 set((state) => {
601 const threadKey = scopedThreadKey(ref);
602 if (
603 (state.userActionRevisionByThreadKey[threadKey] ?? 0) !== expectedUserActionRevision
604 ) {
605 return state;
606 }
607 // A linked PR takes priority over a completed-turn diff. Manual actions
608 // always apply, and later user choices reject both proactive requests.
609 if (
610 surface.kind === "diff" &&
611 (selectActiveRightPanel(state.byThreadKey, ref) === "pull-request" ||
612 selectActiveRightPanel(state.byThreadKey, ref) === "pull-requests")
613 ) {
614 return state;
615 }
616 opened = true;
617 return automaticUpdate(state, threadKey, (current) => upsertSurface(current, surface));
618 });
619 return opened;
620 },
621 open: (ref, kind) =>
622 set((state) =>
623 userAction(state, scopedThreadKey(ref), (current) => {
624 if (kind === "preview") {
625 const existing = current.surfaces.find((surface) => surface.kind === "preview");
626 return upsertSurface(current, existing ?? browserSurface(null));
627 }
628 return upsertSurface(current, singletonSurface(kind));
629 }),
630 ),
631 openDevice: (ref, target, automatic = false) =>
632 set((state) =>
633 (automatic ? automaticUpdate : userAction)(state, scopedThreadKey(ref), (current) => {
634 const id =
635 `device:${encodeURIComponent(target.hostId)}:${encodeURIComponent(target.deviceId)}` as const;
636 if (automatic && current.dismissedDeviceSurfaceIds?.includes(id)) return current;
637 const surface: RightPanelSurface = { id, kind: "device", target };
638 const existing = current.surfaces.find((entry) => entry.id === id);
639 const surfaces = existing
640 ? current.surfaces.filter((entry) => entry.id !== "device")
641 : current.surfaces.map((entry) => (entry.id === "device" ? surface : entry));
642 return upsertSurface(
643 {
644 ...current,
645 surfaces,
646 dismissedDeviceSurfaceIds: (current.dismissedDeviceSurfaceIds ?? []).filter(
647 (entry) => entry !== id,
648 ),
649 },
650 existing ?? surface,
651 );
652 }),
653 ),
654 renameDevice: (ref, surfaceId, title) =>
655 set((state) =>
656 userAction(state, scopedThreadKey(ref), (current) => ({
657 ...current,
658 surfaces: current.surfaces.map((surface) =>
659 surface.id === surfaceId && surface.kind === "device"
660 ? { ...surface, title: title.trim() || surface.target?.name || "Device" }
661 : surface,
662 ),
663 })),
664 ),
665 openBrowser: (ref, tabId) =>
666 set((state) =>
667 userAction(state, scopedThreadKey(ref), (current) => {
668 const surface = browserSurface(tabId);
669 const withoutPlaceholder = tabId
670 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
671 : current.surfaces;
672 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
673 }),
674 ),
675 openPullRequest: (ref, target) =>
676 set((state) =>
677 userAction(state, scopedThreadKey(ref), (current) => {
678 const surface = pullRequestSurface(target);
679 const next = upsertSurface(current, surface);
680 return target.url
681 ? {
682 ...next,
683 surfaces: next.surfaces.map((entry) =>
684 entry.id === surface.id ? surface : entry,
685 ),
686 }
687 : next;
688 }),
689 ),
690 openFile: (ref, requestedPath, line) =>
691 set((state) =>
692 userAction(state, scopedThreadKey(ref), (current) => {
693 if (requestedPath === ".") {
694 return upsertSurface(current, singletonSurface("files"));
695 }
696 // Workspace entry paths use '/', including on Windows.
697 const relativePath = /^[A-Za-z]:\/+$/.test(requestedPath)
698 ? requestedPath
699 : requestedPath.replace(/\/+$/, "") || requestedPath;
700 const withoutStandaloneExplorer = current.surfaces.filter(
701 (surface) => surface.kind !== "files",
702 );
703 const surfaceId = `file:${relativePath}` as const;
704 const existing = withoutStandaloneExplorer.find(
705 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
706 surface.id === surfaceId && surface.kind === "file",
707 );
708 const surface = fileSurface(
709 relativePath,
710 normalizeRevealLine(line),
711 (existing?.revealRequestId ?? 0) + 1,
712 );
713 return {
714 ...current,
715 isOpen: true,
716 activeSurfaceId: surface.id,
717 surfaces: existing
718 ? withoutStandaloneExplorer.map((entry) =>
719 entry.id === surface.id ? surface : entry,
720 )
721 : [...withoutStandaloneExplorer, surface],
722 };
723 }),
724 ),
725 openAttachment: (ref, attachment) =>
726 set((state) =>
727 userAction(state, scopedThreadKey(ref), (current) => {
728 const withoutStandaloneExplorer = current.surfaces.filter(
729 (surface) => surface.kind !== "files",
730 );
731 return upsertSurface(
732 { ...current, surfaces: withoutStandaloneExplorer },
733 attachmentSurface(attachment),
734 );
735 }),
736 ),
737 openTerminal: (ref, terminalId) =>
738 set((state) =>
739 userAction(state, scopedThreadKey(ref), (current) =>
740 upsertSurface(current, terminalSurface(terminalId)),
741 ),
742 ),
743 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
744 set((state) =>
745 userAction(state, scopedThreadKey(ref), (current) => ({
746 ...current,
747 isOpen: true,
748 activeSurfaceId: surfaceId,
749 surfaces: current.surfaces.map((surface) => {
750 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
751 const { splitDirection: _splitDirection, ...baseSurface } = surface;
752 return {
753 ...baseSurface,
754 terminalIds: surface.terminalIds.includes(terminalId)
755 ? surface.terminalIds
756 : [...surface.terminalIds, terminalId],
757 activeTerminalId: terminalId,
758 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
759 };
760 }),
761 })),
762 ),
763 activateTerminal: (ref, surfaceId, terminalId) =>
764 set((state) =>
765 userAction(state, scopedThreadKey(ref), (current) => ({
766 ...current,
767 activeSurfaceId: surfaceId,
768 surfaces: current.surfaces.map((surface) =>
769 surface.id === surfaceId &&
770 surface.kind === "terminal" &&
771 surface.terminalIds.includes(terminalId)
772 ? { ...surface, activeTerminalId: terminalId }
773 : surface,
774 ),
775 })),
776 ),
777 closeTerminal: (ref, surfaceId, terminalId) =>
778 set((state) =>
779 closeAction(state, scopedThreadKey(ref), (current) => {
780 const surface = current.surfaces.find(
781 (entry) => entry.id === surfaceId && entry.kind === "terminal",
782 );
783 if (!surface || surface.kind !== "terminal") return current;
784 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
785 if (terminalIds.length === 0) {
786 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
787 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
788 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
789 return {
790 ...current,
791 isOpen: surfaces.length > 0 && current.isOpen,
792 surfaces,
793 activeSurfaceId:
794 current.activeSurfaceId === surfaceId
795 ? (fallback?.id ?? null)
796 : current.activeSurfaceId,
797 };
798 }
799 return {
800 ...current,
801 surfaces: current.surfaces.map((entry) =>
802 entry.id === surfaceId && entry.kind === "terminal"
803 ? {
804 ...entry,
805 terminalIds,
806 activeTerminalId:
807 entry.activeTerminalId === terminalId
808 ? (terminalIds.at(-1) ?? terminalIds[0]!)
809 : entry.activeTerminalId,
810 }
811 : entry,
812 ),
813 };
814 }),
815 ),
816 activateSurface: (ref, surfaceId) =>
817 set((state) =>
818 userAction(state, scopedThreadKey(ref), (current) =>
819 current.surfaces.some((surface) => surface.id === surfaceId)
820 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
821 : current,
822 ),
823 ),
824 closeSurface: (ref, surfaceId) =>
825 set((state) =>
826 closeAction(state, scopedThreadKey(ref), (current) => {
827 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
828 if (index < 0) return current;
829 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
830 const next = {
831 ...current,
832 isOpen: surfaces.length > 0 && current.isOpen,
833 surfaces,
834 };
835 if (current.activeSurfaceId !== surfaceId) {
836 return next;
837 }
838 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
839 return {
840 ...next,
841 activeSurfaceId: fallback?.id ?? null,
842 };
843 }),
844 ),
845 closeOtherSurfaces: (ref, surfaceId) =>
846 set((state) =>
847 closeAction(state, scopedThreadKey(ref), (current) => {
848 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
849 if (!surface || current.surfaces.length === 1) return current;
850 return {
851 ...current,
852 isOpen: true,
853 surfaces: [surface],
854 activeSurfaceId: surface.id,
855 };
856 }),
857 ),
858 closeSurfacesToRight: (ref, surfaceId) =>
859 set((state) =>
860 closeAction(state, scopedThreadKey(ref), (current) => {
861 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
862 if (index < 0 || index === current.surfaces.length - 1) return current;
863 const surfaces = current.surfaces.slice(0, index + 1);
864 const activeStillExists = surfaces.some(
865 (surface) => surface.id === current.activeSurfaceId,
866 );
867 return {
868 ...current,
869 surfaces,
870 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
871 };
872 }),
873 ),
874 closeAllSurfaces: (ref) =>
875 set((state) =>
876 closeAction(state, scopedThreadKey(ref), (current) =>
877 current.surfaces.length === 0
878 ? current
879 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
880 ),
881 ),
882 reconcileBrowserSurfaces: (ref, tabIds, hiddenTabIds) =>
883 set((state) =>
884 automaticUpdate(state, scopedThreadKey(ref), (current) => {
885 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
886 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
887 const existingBrowser = current.surfaces.filter(
888 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
889 surface.kind === "preview" &&
890 surface.id !== "browser:new" &&
891 validIds.has(surface.id),
892 );
893 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
894 const added = tabIds
895 .filter((tabId) => !knownIds.has(`browser:${tabId}`) && !hiddenTabIds?.has(tabId))
896 .map((tabId) => browserSurface(tabId));
897 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
898 const activeStillExists = surfaces.some(
899 (surface) => surface.id === current.activeSurfaceId,
900 );
901 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
902 return {
903 ...current,
904 surfaces,
905 activeSurfaceId: activeStillExists
906 ? current.activeSurfaceId
907 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
908 };
909 }),
910 ),
911 reconcileFileSurfaces: (ref, workspaceAvailable) =>
912 set((state) =>
913 automaticUpdate(state, scopedThreadKey(ref), (current) => {
914 if (workspaceAvailable) return current;
915 const surfaces = current.surfaces.filter(
916 (surface) =>
917 surface.kind !== "files" &&
918 (surface.kind !== "file" || surface.attachment !== undefined),
919 );
920 if (surfaces.length === current.surfaces.length) return current;
921 const activeStillExists = surfaces.some(
922 (surface) => surface.id === current.activeSurfaceId,
923 );
924 return {
925 ...current,
926 isOpen: surfaces.length > 0 ? current.isOpen : false,
927 surfaces,
928 activeSurfaceId: activeStillExists
929 ? current.activeSurfaceId
930 : (surfaces.at(-1)?.id ?? null),
931 };
932 }),
933 ),
934 show: (ref) =>
935 set((state) =>
936 userAction(state, scopedThreadKey(ref), (current) =>
937 current.isOpen ? current : { ...current, isOpen: true },
938 ),
939 ),
940 close: (ref) =>
941 set((state) =>
942 userAction(state, scopedThreadKey(ref), (current) =>
943 current.isOpen ? { ...current, isOpen: false } : current,
944 ),
945 ),
946 toggleVisibility: (ref) =>
947 set((state) =>
948 userAction(state, scopedThreadKey(ref), (current) => ({
949 ...current,
950 isOpen: !current.isOpen,
951 })),
952 ),
953 toggle: (ref, kind) =>
954 set((state) =>
955 userAction(state, scopedThreadKey(ref), (current) => {
956 const active = current.surfaces.find(
957 (surface) => surface.id === current.activeSurfaceId,
958 );
959 if (current.isOpen && active?.kind === kind) {
960 return { ...current, isOpen: false };
961 }
962 if (kind === "preview") {
963 const existing = current.surfaces.find((surface) => surface.kind === "preview");
964 return upsertSurface(current, existing ?? browserSurface(null));
965 }
966 return upsertSurface(current, singletonSurface(kind));
967 }),
968 ),
969 setThreadPanelOpen: (ref, presentation, open) =>
970 set((state) => ({
971 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
972 state.threadPanelVisibilityByThreadKey,
973 scopedThreadKey(ref),
974 (visibility) => {
975 const key = presentation === "inline" ? "inlineOpen" : "popoverOpen";
976 return visibility[key] === open ? visibility : { ...visibility, [key]: open };
977 },
978 ),
979 })),
980 toggleThreadPanel: (ref, presentation) =>
981 set((state) => ({
982 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
983 state.threadPanelVisibilityByThreadKey,
984 scopedThreadKey(ref),
985 (visibility) =>
986 presentation === "inline"
987 ? { ...visibility, inlineOpen: !visibility.inlineOpen }
988 : { ...visibility, popoverOpen: !visibility.popoverOpen },
989 ),
990 })),
991 removeThread: (ref) =>
992 set((state) => {
993 const threadKey = scopedThreadKey(ref);
994 if (
995 !(threadKey in state.byThreadKey) &&
996 !(threadKey in state.threadPanelVisibilityByThreadKey) &&
997 !(threadKey in state.userActionRevisionByThreadKey) &&
998 !(threadKey in state.closeRevisionByThreadKey)
999 ) {
1000 return state;
1001 }
1002 const { [threadKey]: _removed, ...byThreadKey } = state.byThreadKey;
1003 const { [threadKey]: _visibility, ...threadPanelVisibilityByThreadKey } =
1004 state.threadPanelVisibilityByThreadKey;
1005 const { [threadKey]: _revision, ...userActionRevisionByThreadKey } =
1006 state.userActionRevisionByThreadKey;
1007 const { [threadKey]: _closeRevision, ...closeRevisionByThreadKey } =
1008 state.closeRevisionByThreadKey;
1009 return {
1010 byThreadKey,
1011 threadPanelVisibilityByThreadKey,
1012 userActionRevisionByThreadKey,
1013 closeRevisionByThreadKey,
1014 };
1015 }),
1016 }),
1017 {
1018 name: RIGHT_PANEL_STORAGE_KEY,
1019 version: RIGHT_PANEL_STORAGE_VERSION,
1020 storage: createJSONStorage(() =>
1021 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
1022 ),
1023 partialize: (state) => ({
1024 byThreadKey: Object.fromEntries(
1025 Object.entries(state.byThreadKey).filter(
1026 ([threadKey]) => !isPullRequestsPanelKey(threadKey),
1027 ),
1028 ),
1029 threadPanelVisibilityByThreadKey: Object.fromEntries(
1030 Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
1031 ([threadKey, visibility]) =>
1032 visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
1033 ),
1034 ),
1035 }),
1036 migrate: migratePersistedRightPanelState,
1037 },
1038 ),
1039);
1040
1041useRightPanelStore.subscribe((next, previous) => {
1042 if (next.closeRevisionByThreadKey === previous.closeRevisionByThreadKey) return;
1043 for (const [threadKey, revision] of Object.entries(next.closeRevisionByThreadKey)) {
1044 if (revision === previous.closeRevisionByThreadKey[threadKey]) continue;
1045 const threadRef = parseScopedThreadKey(threadKey);
1046 if (!threadRef) continue;
1047 const before = previous.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
1048 const after = next.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
1049 const removed = before.surfaces.filter(
1050 (surface) => !after.surfaces.some((entry) => entry.id === surface.id),
1051 );
1052 const closedInOrder = [
1053 ...removed.filter((surface) => surface.id !== before.activeSurfaceId),
1054 ...removed.filter((surface) => surface.id === before.activeSurfaceId),
1055 ];
1056 for (const surface of closedInOrder) {
1057 if (
1058 surface.kind === "terminal" ||
1059 (surface.kind === "preview" && surface.resourceId !== null)
1060 )
1061 continue;
1062 useClosedViewStore.getState().remember({ kind: "panel-tab", threadRef, surface });
1063 }
1064 }
1065});
1066
1067export function selectThreadRightPanelState(
1068 byThreadKey: Record<string, ThreadRightPanelState>,
1069 ref: ScopedThreadRef | null | undefined,
1070): ThreadRightPanelState {
1071 if (!ref) return EMPTY_THREAD_STATE;
1072 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
1073}
1074
1075export function selectThreadPanelVisibility(
1076 byThreadKey: Record<string, ThreadPanelVisibility>,
1077 ref: ScopedThreadRef | null | undefined,
1078): ThreadPanelVisibility {
1079 if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY;
1080 return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
1081}
1082
1083export function selectThreadPanelOpen(
1084 byThreadKey: Record<string, ThreadPanelVisibility>,
1085 ref: ScopedThreadRef | null | undefined,
1086 presentation: ThreadPanelPresentation,
1087): boolean {
1088 const visibility = selectThreadPanelVisibility(byThreadKey, ref);
1089 return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
1090}
1091
1092export function selectActiveRightPanel(
1093 byThreadKey: Record<string, ThreadRightPanelState>,
1094 ref: ScopedThreadRef | null | undefined,
1095): RightPanelKind | null {
1096 const state = selectThreadRightPanelState(byThreadKey, ref);
1097 if (!state.isOpen) return null;
1098 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
1099}
1100
1101export function selectActiveRightPanelSurface(
1102 byThreadKey: Record<string, ThreadRightPanelState>,
1103 ref: ScopedThreadRef | null | undefined,
1104): RightPanelSurface | null {
1105 const state = selectThreadRightPanelState(byThreadKey, ref);
1106 if (!state.isOpen) return null;
1107 return selectSelectedRightPanelSurface(byThreadKey, ref);
1108}
1109
1110/** The selected surface even while the panel is hidden, so a layout control can restore it. */
1111export function selectSelectedRightPanelSurface(
1112 byThreadKey: Record<string, ThreadRightPanelState>,
1113 ref: ScopedThreadRef | null | undefined,
1114): RightPanelSurface | null {
1115 const state = selectThreadRightPanelState(byThreadKey, ref);
1116 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
1117}