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