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

rightPanelStore.ts

1,315 lines50.8 KB

1import {
2 parseScopedThreadKey,
3 scopedThreadKey,
4 scopeThreadRef,
5} from "@t3tools/client-runtime/environment";
6import { EnvironmentId, RunId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
7import { create } from "zustand";
8import { createJSONStorage, persist } from "zustand/middleware";
9​
10import { useClosedViewStore } from "./closedViewStore";
11import { resolveStorage } from "./lib/storage";
12import type { ThreadPanelPresentation } from "./rightPanelLayout";
13import type { ChatFileAttachment } from "./types";
14​
15const RIGHT_PANEL_KINDS = [
16 "diff",
17 "files",
18 "file",
19 "preview",
20 "device",
21 "terminal",
22 "pull-request",
23 "pull-requests",
24 "aside",
25] as const;
26export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
27​
28export type PullRequestDetailTab = "summary" | "guide" | "timeline" | "code";
29​
30export interface DeviceTabTarget {
31 hostId: string;
32 deviceId: string;
33 platform: "ios" | "android";
34 name: string;
36​
37export type RightPanelSurface =
38 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
39 | { id: "browser:new"; kind: "preview"; resourceId: null }
40 | { id: "device" | `device:${string}`; kind: "device"; target?: DeviceTabTarget; title?: string }
41 | {
42 id: `terminal:${string}`;
43 kind: "terminal";
44 resourceId: string;
45 terminalIds: string[];
46 activeTerminalId: string;
47 splitDirection?: "horizontal" | "vertical";
48 }
49 | { id: "diff"; kind: "diff" }
50 | {
51 id: "files";
52 kind: "files";
53 /** Set when breadcrumbs moved a folder browser up to the workspace root. */
54 folderTrail?: string;
55 }
56 | {
57 id: `file:${string}` | `attachment:${string}`;
58 kind: "file";
59 relativePath: string;
60 revealLine: number | null;
61 revealRequestId: number;
62 attachment?: ChatFileAttachment;
63 /** Deepest workspace path retained for navigating back down after moving up. */
64 folderTrail?: string;
65 }
66 | {
67 id: `pull-request:${string}`;
68 kind: "pull-request";
69 /** Cross-environment lists can repeat project ids; thread panels inherit their ref's environment. */
70 environmentId?: string;
71 projectId: string;
72 host?: string;
73 repository: string;
74 number: number;
75 url?: string;
76 detailTab?: PullRequestDetailTab;
77 }
78 | { id: "pull-requests"; kind: "pull-requests" }
79 /** A side chat: the chat view of another thread, one tab per side chat. */
80 | { id: `aside:${string}`; kind: "aside"; threadId: string };
81​
82const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
83const RIGHT_PANEL_STORAGE_VERSION = 14;
84​
85export const PULL_REQUESTS_PANEL_REF = scopeThreadRef(
86 EnvironmentId.make("pull-requests-panel"),
87 ThreadId.make("pull-requests-panel"),
88);
89​
90const isPullRequestsPanelKey = (threadKey: string) => threadKey.endsWith(":pull-requests-panel");
91​
92export interface ThreadRightPanelState {
93 isOpen: boolean;
94 activeSurfaceId: string | null;
95 surfaces: RightPanelSurface[];
96 dismissedDeviceSurfaceIds?: string[];
97 maximized?: true;
98 proactiveDiffTurnId?: RunId;
100​
101export interface ThreadPanelVisibility {
102 inlineOpen: boolean;
103 popoverOpen: boolean;
105​
106interface RightPanelStoreState {
107 byThreadKey: Record<string, ThreadRightPanelState>;
108 pendingMaximizeThreadKey: string | null;
109 requestMaximize: (ref: ScopedThreadRef) => void;
110 consumeMaximizeRequest: (ref: ScopedThreadRef) => boolean;
111 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
112 userActionRevisionByThreadKey: Record<string, number>;
113 closeRevisionByThreadKey: Record<string, number>;
114 getUserActionRevision: (ref: ScopedThreadRef) => number;
115 /** Refused if the user chose a panel after expectedUserActionRevision was read. */
116 openProactive: (
117 ref: ScopedThreadRef,
118 request:
119 | Extract<RightPanelSurface, { kind: "pull-request" | "pull-requests" }>
120 | { kind: "diff"; turnId: RunId },
121 expectedUserActionRevision: number,
122 activateExisting?: boolean,
123 ) => boolean;
124 open: (
125 ref: ScopedThreadRef,
126 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request" | "aside">,
127 ) => void;
128 openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void;
129 renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;
130 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
131 /** `inOwnPanel` opens in `ref`'s own panel even while it is embedded in another thread's. */
132 openFile: (
133 ref: ScopedThreadRef,
134 relativePath: string,
135 line?: number,
136 options?: OpenInPanelOptions,
137 ) => void;
138 /** Moves in place; "" opens the root explorer. folderTrail keeps the return path; keepSource opens beside the source. */
139 navigateFolder: (
140 ref: ScopedThreadRef,
141 surfaceId: string,
142 relativePath: string,
143 folderTrail: string,
144 keepSource?: boolean,
145 ) => void;
146 openAttachment: (
147 ref: ScopedThreadRef,
148 attachment: ChatFileAttachment,
149 options?: OpenInPanelOptions,
150 ) => void;
151 openPullRequest: (
152 ref: ScopedThreadRef,
153 target: {
154 environmentId?: string;
155 projectId: string;
156 host?: string;
157 repository: string;
158 number: number;
159 url?: string;
160 detailTab?: PullRequestDetailTab;
161 },
162 options?: OpenInPanelOptions,
163 ) => void;
164 openAside: (ref: ScopedThreadRef, threadId: string) => void;
165 setPullRequestDetailTab: (
166 ref: ScopedThreadRef,
167 surfaceId: string,
168 detailTab: PullRequestDetailTab,
169 ) => void;
170 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
171 splitTerminal: (
172 ref: ScopedThreadRef,
173 surfaceId: string,
174 terminalId: string,
175 direction?: "horizontal" | "vertical",
176 ) => void;
177 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
178 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
179 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
180 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
181 closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
182 closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
183 closeAllSurfaces: (ref: ScopedThreadRef) => void;
184 moveSurface: (ref: ScopedThreadRef, surfaceId: string, toIndex: number) => void;
185 reconcileBrowserSurfaces: (
186 ref: ScopedThreadRef,
187 tabIds: readonly string[],
188 hiddenTabIds?: ReadonlySet<string>,
189 ) => void;
190 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
191 show: (ref: ScopedThreadRef) => void;
192 close: (ref: ScopedThreadRef) => void;
193 setMaximized: (ref: ScopedThreadRef, maximized: boolean) => void;
194 toggleVisibility: (ref: ScopedThreadRef) => void;
195 toggle: (
196 ref: ScopedThreadRef,
197 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request" | "aside">,
198 ) => void;
199 setThreadPanelOpen: (
200 ref: ScopedThreadRef,
201 presentation: ThreadPanelPresentation,
202 open: boolean,
203 ) => void;
204 toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
205 removeThread: (ref: ScopedThreadRef) => void;
207​
208const EMPTY_THREAD_STATE: ThreadRightPanelState = {
209 isOpen: false,
210 activeSurfaceId: null,
211 surfaces: [],
212};
213​
214const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
215 inlineOpen: true,
216 popoverOpen: false,
217};
218​
219const singletonSurface = (
220 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request" | "aside">,
221): RightPanelSurface => {
222 switch (kind) {
223 case "diff":
224 return { id: "diff", kind };
225 case "files":
226 return { id: "files", kind };
227 case "pull-requests":
228 return { id: "pull-requests", kind };
229 case "device":
230 return { id: "device", kind };
231 }
232};
233​
234const browserSurface = (tabId: string | null): RightPanelSurface =>
235 tabId
236 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
237 : { id: "browser:new", kind: "preview", resourceId: null };
238​
239const fileSurface = (
240 relativePath: string,
241 revealLine: number | null,
242 revealRequestId: number,
243): RightPanelSurface => ({
244 id: `file:${relativePath}`,
245 kind: "file",
246 relativePath,
247 revealLine,
248 revealRequestId,
249});
250​
251const attachmentSurface = (attachment: ChatFileAttachment): RightPanelSurface => ({
252 id: `attachment:${attachment.id}`,
253 kind: "file",
254 relativePath: attachment.name,
255 revealLine: null,
256 revealRequestId: 0,
257 attachment,
258});
259​
260const terminalSurface = (terminalId: string): RightPanelSurface => ({
261 id: `terminal:${terminalId}`,
262 kind: "terminal",
263 resourceId: terminalId,
264 terminalIds: [terminalId],
265 activeTerminalId: terminalId,
266});
267​
268// A side chat shown inside its parent's panel has no panel of its own, so files,
269// attachments and pull requests it opens go to the parent while it is mounted
270// there. Opened as a full thread, it owns its panel again.
271interface EmbeddedPanelHost {
272 readonly hostRef: ScopedThreadRef;
273 readonly sharesWorkspace: boolean;
274 /** The user opened something only the side chat's own panel can show. */
275 readonly onOwnPanelOpen: () => void;
277const embeddedPanelHosts = new Map<string, EmbeddedPanelHost>();
278​
279export interface OpenInPanelOptions {
280 readonly inOwnPanel?: boolean;
282​
283/**
284 * Whether a side chat tab names a thread that is gone: deleted, promoted, or missing. A restored
285 * tab can name a side chat a cached shell does not have yet, so only a live shell can say so.
286 */
287export function isSideChatTabGone(input: {
288 readonly live: boolean;
289 readonly shell: { readonly deletedAt: unknown; readonly sideChat?: boolean | undefined } | null;
290}): boolean {
291 const { live, shell } = input;
292 return live && (shell === null || shell.deletedAt !== null || shell.sideChat !== true);
294​
295/** Closes `threadId`'s side chat tab in `parentRef`'s panel when it is gone; returns whether. */
296export function closeSideChatTabIfGone(
297 parentRef: ScopedThreadRef,
298 threadId: string,
299 input: Parameters<typeof isSideChatTabGone>[0],
300): boolean {
301 const gone = isSideChatTabGone(input);
302 if (gone) useRightPanelStore.getState().closeSurface(parentRef, `aside:${threadId}`);
303 return gone;
305​
306export function registerEmbeddedPanelHost(
307 childRef: ScopedThreadRef,
308 hostRef: ScopedThreadRef,
309 onOwnPanelOpen: () => void,
310 sharesWorkspace = true,
311): () => void {
312 const key = scopedThreadKey(childRef);
313 const host: EmbeddedPanelHost = { hostRef, onOwnPanelOpen, sharesWorkspace };
314 embeddedPanelHosts.set(key, host);
315 return () => {
316 if (embeddedPanelHosts.get(key) === host) embeddedPanelHosts.delete(key);
317 };
319​
320/** The thread whose right panel shows what `ref` opens: its embedding host, or itself. */
321function panelOwnerOf(ref: ScopedThreadRef, options?: OpenInPanelOptions): ScopedThreadRef {
322 if (options?.inOwnPanel === true) return ref;
323 const host = embeddedPanelHosts.get(scopedThreadKey(ref));
324 if (host?.sharesWorkspace === false) {
325 host.onOwnPanelOpen();
326 return ref;
327 }
328 return host?.hostRef ?? ref;
330​
331/**
332 * Browsers, devices and the diff belong to the side chat, so they open in its
333 * own panel, which isn't on screen while it is embedded. Only explicit user
334 * opens call this; agent reveals and automatic updates leave the user in place.
335 */
336function notifyOwnPanelOpen(ref: ScopedThreadRef): void {
337 embeddedPanelHosts.get(scopedThreadKey(ref))?.onOwnPanelOpen();
339​
340const asideSurface = (threadId: string): RightPanelSurface => ({
341 id: `aside:${threadId}`,
342 kind: "aside",
343 threadId,
344});
345​
346export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-request" }>;
347​
348export function pullRequestSurfaceId(target: {
349 environmentId?: string;
350 projectId: string;
351 host?: string;
352 repository: string;
353 number: number;
354}): PullRequestSurface["id"] {
355 const scope =
356 target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
357 const host = target.host === undefined ? "" : `${encodeURIComponent(target.host.toLowerCase())}:`;
358 return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${host}${encodeURIComponent(target.repository)}:${target.number}`;
360​
361export function pullRequestSurface(target: {
362 environmentId?: string;
363 projectId: string;
364 host?: string;
365 repository: string;
366 number: number;
367 url?: string;
368 detailTab?: PullRequestDetailTab;
369}): PullRequestSurface {
370 return {
371 id: pullRequestSurfaceId(target),
372 kind: "pull-request",
373 ...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
374 projectId: target.projectId,
375 ...(typeof target.host === "string" ? { host: target.host.toLowerCase() } : {}),
376 repository: target.repository,
377 number: target.number,
378 ...(typeof target.url === "string" ? { url: target.url } : {}),
379 ...(target.detailTab === undefined ? {} : { detailTab: target.detailTab }),
380 };
382​
383const upsertSurface = (
384 current: ThreadRightPanelState,
385 surface: RightPanelSurface,
386 activate = true,
387): ThreadRightPanelState => ({
388 ...current,
389 isOpen: true,
390 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
391 ? current.surfaces
392 : [...current.surfaces, surface],
393 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
394});
395​
396const updateThreadStateMap = (
397 byThreadKey: Record<string, ThreadRightPanelState>,
398 threadKey: string,
399 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
400): Record<string, ThreadRightPanelState> => {
401 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
402 const next = updater(current);
403 if (
404 !next.isOpen &&
405 next.activeSurfaceId === null &&
406 next.surfaces.length === 0 &&
407 !next.dismissedDeviceSurfaceIds?.length &&
408 next.proactiveDiffTurnId === undefined
409 ) {
410 if (!(threadKey in byThreadKey)) return byThreadKey;
411 const { [threadKey]: _removed, ...rest } = byThreadKey;
412 return rest;
413 }
414 if (next === current) return byThreadKey;
415 return { ...byThreadKey, [threadKey]: next };
416};
417​
418const updateThreadPanelVisibilityMap = (
419 byThreadKey: Record<string, ThreadPanelVisibility>,
420 threadKey: string,
421 updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
422): Record<string, ThreadPanelVisibility> => {
423 const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
424 const next = updater(current);
425 if (next.inlineOpen && !next.popoverOpen) {
426 if (!(threadKey in byThreadKey)) return byThreadKey;
427 const { [threadKey]: _removed, ...rest } = byThreadKey;
428 return rest;
429 }
430 if (next === current) return byThreadKey;
431 return { ...byThreadKey, [threadKey]: next };
432};
433​
434type RightPanelStoreData = Pick<
435 RightPanelStoreState,
436 "byThreadKey" | "threadPanelVisibilityByThreadKey"
437>;
438​
439const updateThread = (
440 state: RightPanelStoreData,
441 threadKey: string,
442 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
443): RightPanelStoreData => {
444 const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
445 const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
446 const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
447 let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
448​
449 if (!current.isOpen && next.isOpen) {
450 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
451 threadPanelVisibilityByThreadKey,
452 threadKey,
453 (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
454 );
455 } else if (current.isOpen && !next.isOpen) {
456 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
457 threadPanelVisibilityByThreadKey,
458 threadKey,
459 (visibility) =>
460 visibility.popoverOpen && !visibility.inlineOpen
461 ? { ...visibility, inlineOpen: true }
462 : visibility,
463 );
464 }
465​
466 return { byThreadKey, threadPanelVisibilityByThreadKey };
467};
468​
469const automaticUpdate = (
470 state: RightPanelStoreState,
471 threadKey: string,
472 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
473): Partial<RightPanelStoreState> => ({
474 ...updateThread(state, threadKey, updater),
475});
476​
477const userAction = (
478 state: RightPanelStoreState,
479 threadKey: string,
480 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
481 closesView = false,
482): Partial<RightPanelStoreState> => ({
483 ...updateThread(state, threadKey, (current) => {
484 const next = updater(current);
485 if (next === current) return current;
486 const removedDevices = current.surfaces.filter(
487 (surface) =>
488 surface.kind === "device" && !next.surfaces.some((entry) => entry.id === surface.id),
489 );
490 if (removedDevices.length === 0) return next;
491 return {
492 ...next,
493 dismissedDeviceSurfaceIds: [
494 ...new Set([
495 ...(next.dismissedDeviceSurfaceIds ?? []),
496 ...removedDevices.map((surface) => surface.id),
497 ]),
498 ],
499 };
500 }),
501 userActionRevisionByThreadKey: {
502 ...state.userActionRevisionByThreadKey,
503 [threadKey]: (state.userActionRevisionByThreadKey[threadKey] ?? 0) + 1,
504 },
505 ...(closesView
506 ? {
507 closeRevisionByThreadKey: {
508 ...state.closeRevisionByThreadKey,
509 [threadKey]: (state.closeRevisionByThreadKey[threadKey] ?? 0) + 1,
510 },
511 }
512 : {}),
513});
514​
515const closeAction = (
516 state: RightPanelStoreState,
517 threadKey: string,
518 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
519): Partial<RightPanelStoreState> => userAction(state, threadKey, updater, true);
520​
521function normalizeRevealLine(line: number | undefined): number | null {
522 if (line === undefined || !Number.isFinite(line)) return null;
523 return Math.max(1, Math.trunc(line));
525​
526export function migratePersistedRightPanelState(persistedState: unknown): {
527 byThreadKey: Record<string, ThreadRightPanelState>;
528 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
529} {
530 if (!persistedState || typeof persistedState !== "object") {
531 return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
532 }
533 const byThreadKey =
534 "byThreadKey" in persistedState &&
535 persistedState.byThreadKey &&
536 typeof persistedState.byThreadKey === "object"
537 ? Object.fromEntries(
538 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>)
539 .filter(([threadKey]) => !isPullRequestsPanelKey(threadKey))
540 .map(([threadKey, threadState]) => {
541 const validThreadState =
542 threadState && typeof threadState === "object" ? threadState : null;
543 const surfaces = Array.isArray(validThreadState?.surfaces)
544 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
545 const kind = (surface as { kind?: string }).kind;
546 if (kind === "plan" || kind === "agents") return [];
547 if (
548 (surface.kind === "file" || surface.kind === "files") &&
549 "folderTrail" in surface &&
550 typeof surface.folderTrail !== "string"
551 ) {
552 const { folderTrail: _invalid, ...rest } = surface;
553 surface = rest;
554 }
555 if (surface.kind === "file") {
556 const revealLine =
557 typeof surface.revealLine === "number" &&
558 Number.isFinite(surface.revealLine)
559 ? Math.max(1, Math.trunc(surface.revealLine))
560 : null;
561 const revealRequestId =
562 typeof surface.revealRequestId === "number" &&
563 Number.isSafeInteger(surface.revealRequestId) &&
564 surface.revealRequestId >= 0
565 ? surface.revealRequestId
566 : 0;
567 return [{ ...surface, revealLine, revealRequestId }];
568 }
569 if (surface.kind === "aside") {
570 return typeof surface.threadId === "string" && surface.threadId.length > 0
571 ? [asideSurface(surface.threadId)]
572 : [];
573 }
574 if (surface.kind === "pull-request") {
575 if (
576 typeof surface.projectId !== "string" ||
577 typeof surface.repository !== "string" ||
578 typeof surface.number !== "number" ||
579 !Number.isSafeInteger(surface.number) ||
580 surface.number < 1
581 ) {
582 return [];
583 }
584 const { environmentId, ...rest } = surface;
585 return [
586 pullRequestSurface({
587 ...rest,
588 ...(typeof environmentId === "string" ? { environmentId } : {}),
589 }),
590 ];
591 }
592 if (surface.kind !== "terminal") return [surface];
593 if (
594 !("resourceId" in surface) ||
595 typeof surface.resourceId !== "string" ||
596 surface.id !== `terminal:${surface.resourceId}`
597 ) {
598 return [];
599 }
600 const terminalIds =
601 "terminalIds" in surface && Array.isArray(surface.terminalIds)
602 ? [
603 ...new Set(
604 surface.terminalIds.filter(
605 (terminalId): terminalId is string =>
606 typeof terminalId === "string",
607 ),
608 ),
609 ]
610 : [surface.resourceId];
611 const activeTerminalId =
612 "activeTerminalId" in surface &&
613 typeof surface.activeTerminalId === "string" &&
614 terminalIds.includes(surface.activeTerminalId)
615 ? surface.activeTerminalId
616 : (terminalIds[0] ?? surface.resourceId);
617 return [
618 {
619 ...surface,
620 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
621 activeTerminalId,
622 },
623 ];
624 })
625 : [];
626 const rawActiveSurfaceId = validThreadState?.activeSurfaceId;
627 const persistedActiveSurfaceId = surfaces.some(
628 (surface) => surface.id === rawActiveSurfaceId,
629 )
630 ? (rawActiveSurfaceId ?? null)
631 : rawActiveSurfaceId === "pull-request"
632 ? (surfaces.find((surface) => surface.kind === "pull-request")?.id ?? null)
633 : null;
634 const isOpen =
635 surfaces.length > 0 &&
636 (typeof validThreadState?.isOpen === "boolean"
637 ? validThreadState.isOpen
638 : persistedActiveSurfaceId !== null);
639 const activeSurfaceId =
640 persistedActiveSurfaceId ??
641 (isOpen || rawActiveSurfaceId === "agents" ? (surfaces[0]?.id ?? null) : null);
642 return [
643 threadKey,
644 {
645 isOpen,
646 surfaces,
647 activeSurfaceId,
648 ...(typeof validThreadState?.proactiveDiffTurnId === "string"
649 ? { proactiveDiffTurnId: RunId.make(validThreadState.proactiveDiffTurnId) }
650 : {}),
651 ...(Array.isArray(validThreadState?.dismissedDeviceSurfaceIds)
652 ? {
653 dismissedDeviceSurfaceIds:
654 validThreadState.dismissedDeviceSurfaceIds.filter(
655 (id): id is string => typeof id === "string",
656 ),
657 }
658 : {}),
659 ...(validThreadState?.maximized === true ? { maximized: true as const } : {}),
660 },
661 ];
662 }),
663 )
664 : {};
665 const threadPanelVisibilityByThreadKey =
666 "threadPanelVisibilityByThreadKey" in persistedState &&
667 persistedState.threadPanelVisibilityByThreadKey &&
668 typeof persistedState.threadPanelVisibilityByThreadKey === "object"
669 ? Object.fromEntries(
670 Object.entries(
671 persistedState.threadPanelVisibilityByThreadKey as Record<string, unknown>,
672 ).flatMap(([threadKey, value]) => {
673 if (!value || typeof value !== "object" || !("inlineOpen" in value)) return [];
674 return value.inlineOpen === false
675 ? [[threadKey, { inlineOpen: false, popoverOpen: false }]]
676 : [];
677 }),
678 )
679 : {};
680 return { byThreadKey, threadPanelVisibilityByThreadKey };
682​
683export const useRightPanelStore = create<RightPanelStoreState>()(
684 persist(
685 (set, get) => ({
686 byThreadKey: {},
687 pendingMaximizeThreadKey: null,
688 requestMaximize: (ref) => set({ pendingMaximizeThreadKey: scopedThreadKey(ref) }),
689 consumeMaximizeRequest: (ref) => {
690 if (get().pendingMaximizeThreadKey !== scopedThreadKey(ref)) return false;
691 set({ pendingMaximizeThreadKey: null });
692 return true;
693 },
694 threadPanelVisibilityByThreadKey: {},
695 userActionRevisionByThreadKey: {},
696 closeRevisionByThreadKey: {},
697 getUserActionRevision: (ref) =>
698 get().userActionRevisionByThreadKey[scopedThreadKey(ref)] ?? 0,
699 openProactive: (ref, request, expectedUserActionRevision, activateExisting = false) => {
700 let opened = false;
701 set((state) => {
702 const threadKey = scopedThreadKey(ref);
703 if (request.kind === "diff") {
704 const current = selectThreadRightPanelState(state.byThreadKey, ref);
705 if (current.proactiveDiffTurnId === request.turnId) return state;
706 const activePanel = selectActiveRightPanel(state.byThreadKey, ref);
707 const pullRequestActive =
708 activePanel === "pull-request" || activePanel === "pull-requests";
709 opened =
710 (state.userActionRevisionByThreadKey[threadKey] ?? 0) ===
711 expectedUserActionRevision &&
712 activePanel !== "diff" &&
713 !pullRequestActive;
714 // Record the offer even when refused, so a revisit does not retry this turn.
715 return automaticUpdate(state, threadKey, (thread) => ({
716 ...(opened ? upsertSurface(thread, singletonSurface("diff")) : thread),
717 proactiveDiffTurnId: request.turnId,
718 }));
719 }
720 if (
721 (state.userActionRevisionByThreadKey[threadKey] ?? 0) !== expectedUserActionRevision
722 ) {
723 return state;
724 }
725 // Keep an existing PR tab where the user left it when revisiting a thread.
726 if (
727 !activateExisting &&
728 selectThreadRightPanelState(state.byThreadKey, ref).surfaces.some(
729 (entry) => entry.id === request.id,
730 )
731 ) {
732 return state;
733 }
734 opened = true;
735 return automaticUpdate(state, threadKey, (current) => upsertSurface(current, request));
736 });
737 return opened;
738 },
739 open: (ref, kind) => {
740 set((state) =>
741 userAction(state, scopedThreadKey(ref), (current) => {
742 if (kind === "preview") {
743 const existing = current.surfaces.find((surface) => surface.kind === "preview");
744 return upsertSurface(current, existing ?? browserSurface(null));
745 }
746 return upsertSurface(current, singletonSurface(kind));
747 }),
748 );
749 notifyOwnPanelOpen(ref);
750 },
751 openDevice: (ref, target, automatic = false) => {
752 set((state) =>
753 (automatic ? automaticUpdate : userAction)(state, scopedThreadKey(ref), (current) => {
754 const id =
755 `device:${encodeURIComponent(target.hostId)}:${encodeURIComponent(target.deviceId)}` as const;
756 if (automatic && current.dismissedDeviceSurfaceIds?.includes(id)) return current;
757 const surface: RightPanelSurface = { id, kind: "device", target };
758 const existing = current.surfaces.find((entry) => entry.id === id);
759 const surfaces = existing
760 ? current.surfaces.filter((entry) => entry.id !== "device")
761 : current.surfaces.map((entry) => (entry.id === "device" ? surface : entry));
762 return upsertSurface(
763 {
764 ...current,
765 surfaces,
766 dismissedDeviceSurfaceIds: (current.dismissedDeviceSurfaceIds ?? []).filter(
767 (entry) => entry !== id,
768 ),
769 },
770 existing ?? surface,
771 );
772 }),
773 );
774 if (!automatic) notifyOwnPanelOpen(ref);
775 },
776 renameDevice: (ref, surfaceId, title) =>
777 set((state) =>
778 userAction(state, scopedThreadKey(ref), (current) => ({
779 ...current,
780 surfaces: current.surfaces.map((surface) =>
781 surface.id === surfaceId && surface.kind === "device"
782 ? { ...surface, title: title.trim() || surface.target?.name || "Device" }
783 : surface,
784 ),
785 })),
786 ),
787 openBrowser: (ref, tabId) => {
788 set((state) =>
789 userAction(state, scopedThreadKey(ref), (current) => {
790 const surface = browserSurface(tabId);
791 const withoutPlaceholder = tabId
792 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
793 : current.surfaces;
794 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
795 }),
796 );
797 notifyOwnPanelOpen(ref);
798 },
799 openPullRequest: (ref, target, options) =>
800 set((state) =>
801 userAction(state, scopedThreadKey(panelOwnerOf(ref, options)), (current) => {
802 const surface = pullRequestSurface(target);
803 const next = upsertSurface(current, surface);
804 return target.url
805 ? {
806 ...next,
807 surfaces: next.surfaces.map((entry) =>
808 entry.id === surface.id && entry.kind === "pull-request"
809 ? { ...entry, ...surface }
810 : entry,
811 ),
812 }
813 : next;
814 }),
815 ),
816 setPullRequestDetailTab: (ref, surfaceId, detailTab) =>
817 set((state) => {
818 const threadKey = scopedThreadKey(ref);
819 const existing = state.byThreadKey[threadKey]?.surfaces.find(
820 (surface) => surface.id === surfaceId,
821 );
822 if (existing?.kind !== "pull-request" || (existing.detailTab ?? "summary") === detailTab)
823 return state;
824 return automaticUpdate(state, threadKey, (current) => ({
825 ...current,
826 surfaces: current.surfaces.map((surface) =>
827 surface.id === surfaceId && surface.kind === "pull-request"
828 ? { ...surface, detailTab }
829 : surface,
830 ),
831 }));
832 }),
833 openFile: (ref, requestedPath, line, options) =>
834 set((state) =>
835 userAction(state, scopedThreadKey(panelOwnerOf(ref, options)), (current) => {
836 if (requestedPath === ".") {
837 return upsertSurface(current, singletonSurface("files"));
838 }
839 // Workspace entry paths use '/', including on Windows.
840 const relativePath = /^[A-Za-z]:\/+$/.test(requestedPath)
841 ? requestedPath
842 : requestedPath.replace(/\/+$/, "") || requestedPath;
843 const withoutStandaloneExplorer = current.surfaces.filter(
844 (surface) => surface.kind !== "files",
845 );
846 const surfaceId = `file:${relativePath}` as const;
847 const existing = withoutStandaloneExplorer.find(
848 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
849 surface.id === surfaceId && surface.kind === "file",
850 );
851 const surface = fileSurface(
852 relativePath,
853 normalizeRevealLine(line),
854 (existing?.revealRequestId ?? 0) + 1,
855 );
856 return {
857 ...current,
858 isOpen: true,
859 activeSurfaceId: surface.id,
860 surfaces: existing
861 ? withoutStandaloneExplorer.map((entry) =>
862 entry.id === surface.id ? surface : entry,
863 )
864 : [...withoutStandaloneExplorer, surface],
865 };
866 }),
867 ),
868 navigateFolder: (ref, surfaceId, relativePath, folderTrail, keepSource = false) =>
869 set((state) =>
870 userAction(state, scopedThreadKey(ref), (current) => {
871 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
872 if (index < 0) return current;
873 const trail = folderTrail === relativePath ? {} : { folderTrail };
874 const target: RightPanelSurface =
875 relativePath === ""
876 ? { ...singletonSurface("files"), ...trail }
877 : { ...fileSurface(relativePath, null, 1), ...trail };
878 const source = current.surfaces[index]!;
879 const existing = current.surfaces.some(
880 (surface, i) => i !== index && surface.id === target.id,
881 );
882 const surfaces = current.surfaces.flatMap((surface, i) => {
883 if (i === index) {
884 const kept = keepSource ? [source] : [];
885 return existing ? kept : [...kept, target];
886 }
887 return !existing && target.kind === "file" && surface.kind === "files"
888 ? []
889 : [surface];
890 });
891 return { ...current, isOpen: true, activeSurfaceId: target.id, surfaces };
892 }),
893 ),
894 openAttachment: (ref, attachment, options) =>
895 set((state) =>
896 userAction(state, scopedThreadKey(panelOwnerOf(ref, options)), (current) => {
897 const withoutStandaloneExplorer = current.surfaces.filter(
898 (surface) => surface.kind !== "files",
899 );
900 return upsertSurface(
901 { ...current, surfaces: withoutStandaloneExplorer },
902 attachmentSurface(attachment),
903 );
904 }),
905 ),
906 openAside: (ref, threadId) =>
907 set((state) =>
908 userAction(state, scopedThreadKey(ref), (current) =>
909 upsertSurface(current, asideSurface(threadId)),
910 ),
911 ),
912 openTerminal: (ref, terminalId) =>
913 set((state) =>
914 userAction(state, scopedThreadKey(ref), (current) =>
915 upsertSurface(current, terminalSurface(terminalId)),
916 ),
917 ),
918 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
919 set((state) =>
920 userAction(state, scopedThreadKey(ref), (current) => ({
921 ...current,
922 isOpen: true,
923 activeSurfaceId: surfaceId,
924 surfaces: current.surfaces.map((surface) => {
925 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
926 const { splitDirection: _splitDirection, ...baseSurface } = surface;
927 return {
928 ...baseSurface,
929 terminalIds: surface.terminalIds.includes(terminalId)
930 ? surface.terminalIds
931 : [...surface.terminalIds, terminalId],
932 activeTerminalId: terminalId,
933 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
934 };
935 }),
936 })),
937 ),
938 activateTerminal: (ref, surfaceId, terminalId) =>
939 set((state) =>
940 userAction(state, scopedThreadKey(ref), (current) => ({
941 ...current,
942 activeSurfaceId: surfaceId,
943 surfaces: current.surfaces.map((surface) =>
944 surface.id === surfaceId &&
945 surface.kind === "terminal" &&
946 surface.terminalIds.includes(terminalId)
947 ? { ...surface, activeTerminalId: terminalId }
948 : surface,
949 ),
950 })),
951 ),
952 closeTerminal: (ref, surfaceId, terminalId) =>
953 set((state) =>
954 closeAction(state, scopedThreadKey(ref), (current) => {
955 const surface = current.surfaces.find(
956 (entry) => entry.id === surfaceId && entry.kind === "terminal",
957 );
958 if (!surface || surface.kind !== "terminal") return current;
959 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
960 if (terminalIds.length === 0) {
961 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
962 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
963 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
964 return {
965 ...current,
966 isOpen: surfaces.length > 0 && current.isOpen,
967 surfaces,
968 activeSurfaceId:
969 current.activeSurfaceId === surfaceId
970 ? (fallback?.id ?? null)
971 : current.activeSurfaceId,
972 };
973 }
974 return {
975 ...current,
976 surfaces: current.surfaces.map((entry) =>
977 entry.id === surfaceId && entry.kind === "terminal"
978 ? {
979 ...entry,
980 terminalIds,
981 activeTerminalId:
982 entry.activeTerminalId === terminalId
983 ? (terminalIds.at(-1) ?? terminalIds[0]!)
984 : entry.activeTerminalId,
985 }
986 : entry,
987 ),
988 };
989 }),
990 ),
991 activateSurface: (ref, surfaceId) =>
992 set((state) =>
993 userAction(state, scopedThreadKey(ref), (current) =>
994 current.surfaces.some((surface) => surface.id === surfaceId)
995 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
996 : current,
997 ),
998 ),
999 closeSurface: (ref, surfaceId) =>
1000 set((state) =>
1001 closeAction(state, scopedThreadKey(ref), (current) => {
1002 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
1003 if (index < 0) return current;
1004 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
1005 const next = {
1006 ...current,
1007 isOpen: surfaces.length > 0 && current.isOpen,
1008 surfaces,
1009 };
1010 if (current.activeSurfaceId !== surfaceId) {
1011 return next;
1013 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
1014 return {
1015 ...next,
1016 activeSurfaceId: fallback?.id ?? null,
1017 };
1018 }),
1019 ),
1020 closeOtherSurfaces: (ref, surfaceId) =>
1021 set((state) =>
1022 closeAction(state, scopedThreadKey(ref), (current) => {
1023 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
1024 if (!surface || current.surfaces.length === 1) return current;
1025 return {
1026 ...current,
1027 isOpen: true,
1028 surfaces: [surface],
1029 activeSurfaceId: surface.id,
1030 };
1031 }),
1032 ),
1033 closeSurfacesToRight: (ref, surfaceId) =>
1034 set((state) =>
1035 closeAction(state, scopedThreadKey(ref), (current) => {
1036 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
1037 if (index < 0 || index === current.surfaces.length - 1) return current;
1038 const surfaces = current.surfaces.slice(0, index + 1);
1039 const activeStillExists = surfaces.some(
1040 (surface) => surface.id === current.activeSurfaceId,
1041 );
1042 return {
1043 ...current,
1044 surfaces,
1045 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
1046 };
1047 }),
1048 ),
1049 closeAllSurfaces: (ref) =>
1050 set((state) =>
1051 closeAction(state, scopedThreadKey(ref), (current) =>
1052 current.surfaces.length === 0
1053 ? current
1054 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
1055 ),
1056 ),
1057 moveSurface: (ref, surfaceId, toIndex) =>
1058 set((state) =>
1059 updateThread(state, scopedThreadKey(ref), (current) => {
1060 const fromIndex = current.surfaces.findIndex((surface) => surface.id === surfaceId);
1061 if (fromIndex < 0 || fromIndex === toIndex) return current;
1062 const surfaces = [...current.surfaces];
1063 surfaces.splice(toIndex, 0, ...surfaces.splice(fromIndex, 1));
1064 return { ...current, surfaces };
1065 }),
1066 ),
1067 reconcileBrowserSurfaces: (ref, tabIds, hiddenTabIds) =>
1068 set((state) =>
1069 automaticUpdate(state, scopedThreadKey(ref), (current) => {
1070 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
1071 const kept = current.surfaces.filter(
1072 (surface) =>
1073 surface.kind !== "preview" ||
1074 (surface.id !== "browser:new" && validIds.has(surface.id)),
1075 );
1076 const knownIds = new Set(kept.map((surface) => surface.id));
1077 const added = tabIds
1078 .filter((tabId) => !knownIds.has(`browser:${tabId}`) && !hiddenTabIds?.has(tabId))
1079 .map((tabId) => browserSurface(tabId));
1080 const surfaces = [...kept, ...added];
1081 const activeStillExists = surfaces.some(
1082 (surface) => surface.id === current.activeSurfaceId,
1083 );
1084 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
1085 // A closed session tab was the last surface: hide the panel rather than leave it on
1086 // the empty picker, as a user close would. A dropped `browser:new` placeholder does not count.
1087 const closedLastSessionTab =
1088 surfaces.length === 0 &&
1089 current.surfaces.some((surface) => surface.kind === "preview" && surface.resourceId);
1090 return {
1091 ...current,
1092 isOpen: closedLastSessionTab ? false : current.isOpen,
1093 surfaces,
1094 activeSurfaceId: activeStillExists
1095 ? current.activeSurfaceId
1096 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
1097 };
1098 }),
1099 ),
1100 reconcileFileSurfaces: (ref, workspaceAvailable) =>
1101 set((state) =>
1102 automaticUpdate(state, scopedThreadKey(ref), (current) => {
1103 if (workspaceAvailable) return current;
1104 const surfaces = current.surfaces.filter(
1105 (surface) =>
1106 surface.kind !== "files" &&
1107 (surface.kind !== "file" || surface.attachment !== undefined),
1108 );
1109 if (surfaces.length === current.surfaces.length) return current;
1110 const activeStillExists = surfaces.some(
1111 (surface) => surface.id === current.activeSurfaceId,
1112 );
1113 return {
1114 ...current,
1115 isOpen: surfaces.length > 0 ? current.isOpen : false,
1116 surfaces,
1117 activeSurfaceId: activeStillExists
1118 ? current.activeSurfaceId
1119 : (surfaces.at(-1)?.id ?? null),
1120 };
1121 }),
1122 ),
1123 show: (ref) =>
1124 set((state) =>
1125 userAction(state, scopedThreadKey(ref), (current) =>
1126 current.isOpen ? current : { ...current, isOpen: true },
1127 ),
1128 ),
1129 close: (ref) =>
1130 set((state) =>
1131 userAction(state, scopedThreadKey(ref), (current) =>
1132 current.isOpen ? { ...current, isOpen: false } : current,
1133 ),
1134 ),
1135 setMaximized: (ref, maximized) =>
1136 set((state) =>
1137 automaticUpdate(state, scopedThreadKey(ref), (current) => {
1138 if ((current.maximized ?? false) === maximized) return current;
1139 const { maximized: _maximized, ...rest } = current;
1140 return maximized ? { ...rest, maximized: true } : rest;
1141 }),
1142 ),
1143 toggleVisibility: (ref) =>
1144 set((state) =>
1145 userAction(state, scopedThreadKey(ref), (current) => ({
1146 ...current,
1147 isOpen: !current.isOpen,
1148 })),
1149 ),
1150 toggle: (ref, kind) =>
1151 set((state) =>
1152 userAction(state, scopedThreadKey(ref), (current) => {
1153 const active = current.surfaces.find(
1154 (surface) => surface.id === current.activeSurfaceId,
1155 );
1156 if (current.isOpen && active?.kind === kind) {
1157 return { ...current, isOpen: false };
1159 if (kind === "preview") {
1160 const existing = current.surfaces.find((surface) => surface.kind === "preview");
1161 return upsertSurface(current, existing ?? browserSurface(null));
1163 return upsertSurface(current, singletonSurface(kind));
1164 }),
1165 ),
1166 setThreadPanelOpen: (ref, presentation, open) =>
1167 set((state) => ({
1168 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
1169 state.threadPanelVisibilityByThreadKey,
1170 scopedThreadKey(ref),
1171 (visibility) => {
1172 const key = presentation === "inline" ? "inlineOpen" : "popoverOpen";
1173 return visibility[key] === open ? visibility : { ...visibility, [key]: open };
1174 },
1175 ),
1176 })),
1177 toggleThreadPanel: (ref, presentation) =>
1178 set((state) => ({
1179 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
1180 state.threadPanelVisibilityByThreadKey,
1181 scopedThreadKey(ref),
1182 (visibility) =>
1183 presentation === "inline"
1184 ? { ...visibility, inlineOpen: !visibility.inlineOpen }
1185 : { ...visibility, popoverOpen: !visibility.popoverOpen },
1186 ),
1187 })),
1188 removeThread: (ref) =>
1189 set((state) => {
1190 const threadKey = scopedThreadKey(ref);
1191 if (
1192 !(threadKey in state.byThreadKey) &&
1193 !(threadKey in state.threadPanelVisibilityByThreadKey) &&
1194 !(threadKey in state.userActionRevisionByThreadKey) &&
1195 !(threadKey in state.closeRevisionByThreadKey)
1196 ) {
1197 return state;
1199 const { [threadKey]: _removed, ...byThreadKey } = state.byThreadKey;
1200 const { [threadKey]: _visibility, ...threadPanelVisibilityByThreadKey } =
1201 state.threadPanelVisibilityByThreadKey;
1202 const { [threadKey]: _revision, ...userActionRevisionByThreadKey } =
1203 state.userActionRevisionByThreadKey;
1204 const { [threadKey]: _closeRevision, ...closeRevisionByThreadKey } =
1205 state.closeRevisionByThreadKey;
1206 return {
1207 byThreadKey,
1208 threadPanelVisibilityByThreadKey,
1209 userActionRevisionByThreadKey,
1210 closeRevisionByThreadKey,
1211 };
1212 }),
1213 }),
1215 name: RIGHT_PANEL_STORAGE_KEY,
1216 version: RIGHT_PANEL_STORAGE_VERSION,
1217 storage: createJSONStorage(() =>
1218 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
1219 ),
1220 partialize: (state) => ({
1221 byThreadKey: Object.fromEntries(
1222 Object.entries(state.byThreadKey).filter(
1223 ([threadKey]) => !isPullRequestsPanelKey(threadKey),
1224 ),
1225 ),
1226 threadPanelVisibilityByThreadKey: Object.fromEntries(
1227 Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
1228 ([threadKey, visibility]) =>
1229 visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
1230 ),
1231 ),
1232 }),
1233 migrate: migratePersistedRightPanelState,
1234 },
1235 ),
1237​
1238useRightPanelStore.subscribe((next, previous) => {
1239 if (next.closeRevisionByThreadKey === previous.closeRevisionByThreadKey) return;
1240 for (const [threadKey, revision] of Object.entries(next.closeRevisionByThreadKey)) {
1241 if (revision === previous.closeRevisionByThreadKey[threadKey]) continue;
1242 const threadRef = parseScopedThreadKey(threadKey);
1243 if (!threadRef) continue;
1244 const before = previous.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
1245 const after = next.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
1246 const removed = before.surfaces.filter(
1247 (surface) => !after.surfaces.some((entry) => entry.id === surface.id),
1248 );
1249 const closedInOrder = [
1250 ...removed.filter((surface) => surface.id !== before.activeSurfaceId),
1251 ...removed.filter((surface) => surface.id === before.activeSurfaceId),
1252 ];
1253 for (const surface of closedInOrder) {
1254 // Side chats reopen from their own list, and a discarded one is gone.
1255 if (
1256 surface.kind === "terminal" ||
1257 surface.kind === "aside" ||
1258 (surface.kind === "preview" && surface.resourceId !== null)
1260 continue;
1261 useClosedViewStore.getState().remember({ kind: "panel-tab", threadRef, surface });
1264});
1265​
1266export function selectThreadRightPanelState(
1267 byThreadKey: Record<string, ThreadRightPanelState>,
1268 ref: ScopedThreadRef | null | undefined,
1269): ThreadRightPanelState {
1270 if (!ref) return EMPTY_THREAD_STATE;
1271 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
1273​
1274export function selectThreadPanelVisibility(
1275 byThreadKey: Record<string, ThreadPanelVisibility>,
1276 ref: ScopedThreadRef | null | undefined,
1277): ThreadPanelVisibility {
1278 if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY;
1279 return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
1281​
1282export function selectThreadPanelOpen(
1283 byThreadKey: Record<string, ThreadPanelVisibility>,
1284 ref: ScopedThreadRef | null | undefined,
1285 presentation: ThreadPanelPresentation,
1286): boolean {
1287 const visibility = selectThreadPanelVisibility(byThreadKey, ref);
1288 return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
1290​
1291export function selectActiveRightPanel(
1292 byThreadKey: Record<string, ThreadRightPanelState>,
1293 ref: ScopedThreadRef | null | undefined,
1294): RightPanelKind | null {
1295 const state = selectThreadRightPanelState(byThreadKey, ref);
1296 if (!state.isOpen) return null;
1297 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
1299​
1300export function selectActiveRightPanelSurface(
1301 byThreadKey: Record<string, ThreadRightPanelState>,
1302 ref: ScopedThreadRef | null | undefined,
1303): RightPanelSurface | null {
1304 const state = selectThreadRightPanelState(byThreadKey, ref);
1305 if (!state.isOpen) return null;
1306 return selectSelectedRightPanelSurface(byThreadKey, ref);
1308​
1309export function selectSelectedRightPanelSurface(
1310 byThreadKey: Record<string, ThreadRightPanelState>,
1311 ref: ScopedThreadRef | null | undefined,
1312): RightPanelSurface | null {
1313 const state = selectThreadRightPanelState(byThreadKey, ref);
1314 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;