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