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