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