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

rightPanelStore.ts

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