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