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

rightPanelStore.ts

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