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

rightPanelStore.ts

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