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

rightPanelStore.ts

1,183 lines45.7 KB

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