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

rightPanelStore.ts

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