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

rightPanelStore.ts

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