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

rightPanelStore.ts

1,215 lines48.1 KB

1/**
2 * Thread-scoped right-panel surface state.
3 *
4 * This is intentionally a shallow workspace model: it owns an ordered set of
5 * surface descriptors and the active surface, while each feature continues to
6 * own its durable resource state. Browser surfaces point at preview tab ids,
7 * terminal surfaces point at terminal session ids, file surfaces point at
8 * workspace paths, and diff/files remain singleton surfaces.
9 */
10import {
11 parseScopedThreadKey,
12 scopedThreadKey,
13 scopeThreadRef,
14} from "@t3tools/client-runtime/environment";
15import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
16import { create } from "zustand";
17import { createJSONStorage, persist } from "zustand/middleware";
18​
19import { useClosedViewStore } from "./closedViewStore";
20import { resolveStorage } from "./lib/storage";
21import type { ThreadPanelPresentation } from "./rightPanelLayout";
22import type { ChatFileAttachment } from "./types";
23​
24const RIGHT_PANEL_KINDS = [
25 "diff",
26 "files",
27 "file",
28 "preview",
29 "device",
30 "terminal",
31 "pull-request",
32 "pull-requests",
33] as const;
34export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
35​
36export interface DeviceTabTarget {
37 hostId: string;
38 deviceId: string;
39 platform: "ios" | "android";
40 name: string;
42​
43export type RightPanelSurface =
44 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
45 | { id: "browser:new"; kind: "preview"; resourceId: null }
46 | { id: "device" | `device:${string}`; kind: "device"; target?: DeviceTabTarget; title?: string }
47 | {
48 id: `terminal:${string}`;
49 kind: "terminal";
50 resourceId: string;
51 terminalIds: string[];
52 activeTerminalId: string;
53 splitDirection?: "horizontal" | "vertical";
54 }
55 | { id: "diff"; kind: "diff" }
56 | {
57 id: "files";
58 kind: "files";
59 /** Set when breadcrumbs moved a folder browser up to the workspace root. */
60 folderTrail?: string;
61 }
62 | {
63 id: `file:${string}` | `attachment:${string}`;
64 kind: "file";
65 /** Workspace-relative, or absolute for a host file outside the workspace. */
66 relativePath: string;
67 revealLine: number | null;
68 revealRequestId: number;
69 /** Present when the file lives in the thread's attachment store rather
70 than at a workspace or host path. */
71 attachment?: ChatFileAttachment;
72 /**
73 * Set when breadcrumbs moved a folder browser up from a deeper path: the
74 * deepest workspace path the breadcrumbs keep offering on the way back down.
75 */
76 folderTrail?: string;
77 }
78 | {
79 /**
80 * A change request opened beside a thread or in the pull-request list's shared panel.
81 * The reference lives in the id so several pull requests can remain open as peer tabs.
82 */
83 id: `pull-request:${string}`;
84 kind: "pull-request";
85 /**
86 * Which server the change request was read from. The list spans every connected one, so
87 * two of them can hold the same project id; a panel beside a thread leaves this out and
88 * takes the environment from its own ref.
89 */
90 environmentId?: string;
91 projectId: string;
92 host?: string;
93 repository: string;
94 number: number;
95 url?: string;
96 }
97 /** The thread's linked pull requests, one singleton tab beside any number of `pull-request` tabs. */
98 | { id: "pull-requests"; kind: "pull-requests" };
99​
100const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
101// v9 removed the "plan" surface kind (plans render inline in the transcript).
102// v10 keys pull-request surfaces by reference instead of a singleton tab.
103// v11 stops persisting the pull-request list's shared panel, so a restart opens the page fresh.
104// v12 adds the device surface.
105// v14 removes the agents surface; lineage lives in the thread title bar.
106const RIGHT_PANEL_STORAGE_VERSION = 14;
107​
108/** A fixed workspace-level ref: each PR surface carries its own real environment. */
109export const PULL_REQUESTS_PANEL_REF = scopeThreadRef(
110 EnvironmentId.make("pull-requests-panel"),
111 ThreadId.make("pull-requests-panel"),
112);
113​
114/**
115 * The pull-request list's shared panel is session
116 * state: reopening the app should show the list, not last session's tabs and detail fetches.
117 */
118const isPullRequestsPanelKey = (threadKey: string) => threadKey.endsWith(":pull-requests-panel");
119​
120export interface ThreadRightPanelState {
121 isOpen: boolean;
122 activeSurfaceId: string | null;
123 surfaces: RightPanelSurface[];
124 dismissedDeviceSurfaceIds?: string[];
125 /** Kept with the thread so the layout survives a ChatView remount or a reload. */
126 maximized?: true;
128​
129export interface ThreadPanelVisibility {
130 inlineOpen: boolean;
131 popoverOpen: boolean;
133​
134interface RightPanelStoreState {
135 byThreadKey: Record<string, ThreadRightPanelState>;
136 /**
137 * A thread whose right panel should open maximized the next time it shows,
138 * such as one started for a link the OS opened. Its view consumes it once.
139 */
140 pendingMaximizeThreadKey: string | null;
141 requestMaximize: (ref: ScopedThreadRef) => void;
142 consumeMaximizeRequest: (ref: ScopedThreadRef) => boolean;
143 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
144 /** Session-only count of user panel choices per thread. Automatic updates do not advance it. */
145 userActionRevisionByThreadKey: Record<string, number>;
146 closeRevisionByThreadKey: Record<string, number>;
147 getUserActionRevision: (ref: ScopedThreadRef) => number;
148 /**
149 * Open a surface on behalf of the app, not the user. Refused when the user
150 * made a panel choice after `expectedUserActionRevision` was read.
151 */
152 openProactive: (
153 ref: ScopedThreadRef,
154 surface: Extract<RightPanelSurface, { kind: "diff" | "pull-request" | "pull-requests" }>,
155 expectedUserActionRevision: number,
156 ) => boolean;
157 open: (
158 ref: ScopedThreadRef,
159 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
160 ) => void;
161 openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void;
162 renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;
163 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
164 openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
165 /**
166 * Moves the folder browser in `surfaceId` to `relativePath` in place, so walking
167 * the breadcrumbs does not leave a tab behind per folder. `""` is the workspace
168 * root, which is the files explorer. `folderTrail` is kept for the way back down.
169 * `keepSource` opens the folder beside the source tab instead, for a file preview.
170 */
171 navigateFolder: (
172 ref: ScopedThreadRef,
173 surfaceId: string,
174 relativePath: string,
175 folderTrail: string,
176 keepSource?: boolean,
177 ) => void;
178 openAttachment: (ref: ScopedThreadRef, attachment: ChatFileAttachment) => void;
179 openPullRequest: (
180 ref: ScopedThreadRef,
181 target: {
182 environmentId?: string;
183 projectId: string;
184 host?: string;
185 repository: string;
186 number: number;
187 url?: string;
188 },
189 ) => void;
190 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
191 splitTerminal: (
192 ref: ScopedThreadRef,
193 surfaceId: string,
194 terminalId: string,
195 direction?: "horizontal" | "vertical",
196 ) => void;
197 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
198 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
199 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
200 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
201 closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
202 closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
203 closeAllSurfaces: (ref: ScopedThreadRef) => void;
204 moveSurface: (ref: ScopedThreadRef, surfaceId: string, toIndex: number) => void;
205 reconcileBrowserSurfaces: (
206 ref: ScopedThreadRef,
207 tabIds: readonly string[],
208 hiddenTabIds?: ReadonlySet<string>,
209 ) => void;
210 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
211 show: (ref: ScopedThreadRef) => void;
212 close: (ref: ScopedThreadRef) => void;
213 setMaximized: (ref: ScopedThreadRef, maximized: boolean) => void;
214 toggleVisibility: (ref: ScopedThreadRef) => void;
215 toggle: (
216 ref: ScopedThreadRef,
217 kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
218 ) => void;
219 setThreadPanelOpen: (
220 ref: ScopedThreadRef,
221 presentation: ThreadPanelPresentation,
222 open: boolean,
223 ) => void;
224 toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
225 removeThread: (ref: ScopedThreadRef) => void;
227​
228const EMPTY_THREAD_STATE: ThreadRightPanelState = {
229 isOpen: false,
230 activeSurfaceId: null,
231 surfaces: [],
232};
233​
234const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
235 inlineOpen: true,
236 popoverOpen: false,
237};
238​
239const singletonSurface = (
240 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request">,
241): RightPanelSurface => {
242 switch (kind) {
243 case "diff":
244 return { id: "diff", kind };
245 case "files":
246 return { id: "files", kind };
247 case "pull-requests":
248 return { id: "pull-requests", kind };
249 case "device":
250 return { id: "device", kind };
251 }
252};
253​
254const browserSurface = (tabId: string | null): RightPanelSurface =>
255 tabId
256 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
257 : { id: "browser:new", kind: "preview", resourceId: null };
258​
259const fileSurface = (
260 relativePath: string,
261 revealLine: number | null,
262 revealRequestId: number,
263): RightPanelSurface => ({
264 id: `file:${relativePath}`,
265 kind: "file",
266 relativePath,
267 revealLine,
268 revealRequestId,
269});
270​
271const attachmentSurface = (attachment: ChatFileAttachment): RightPanelSurface => ({
272 id: `attachment:${attachment.id}`,
273 kind: "file",
274 relativePath: attachment.name,
275 revealLine: null,
276 revealRequestId: 0,
277 attachment,
278});
279​
280const terminalSurface = (terminalId: string): RightPanelSurface => ({
281 id: `terminal:${terminalId}`,
282 kind: "terminal",
283 resourceId: terminalId,
284 terminalIds: [terminalId],
285 activeTerminalId: terminalId,
286});
287​
288export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-request" }>;
289​
290export function pullRequestSurfaceId(target: {
291 environmentId?: string;
292 projectId: string;
293 host?: string;
294 repository: string;
295 number: number;
296}): PullRequestSurface["id"] {
297 // The environment leads the id where there is one, so the same change request read from two
298 // servers is two tabs rather than one tab that changes its mind about which server it is on.
299 const scope =
300 target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
301 const host = target.host === undefined ? "" : `${encodeURIComponent(target.host.toLowerCase())}:`;
302 return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${host}${encodeURIComponent(target.repository)}:${target.number}`;
304​
305export function pullRequestSurface(target: {
306 environmentId?: string;
307 projectId: string;
308 host?: string;
309 repository: string;
310 number: number;
311 url?: string;
312}): PullRequestSurface {
313 return {
314 id: pullRequestSurfaceId(target),
315 kind: "pull-request",
316 ...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
317 projectId: target.projectId,
318 ...(typeof target.host === "string" ? { host: target.host.toLowerCase() } : {}),
319 repository: target.repository,
320 number: target.number,
321 ...(typeof target.url === "string" ? { url: target.url } : {}),
322 };
324​
325const upsertSurface = (
326 current: ThreadRightPanelState,
327 surface: RightPanelSurface,
328 activate = true,
329): ThreadRightPanelState => ({
330 ...current,
331 isOpen: true,
332 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
333 ? current.surfaces
334 : [...current.surfaces, surface],
335 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
336});
337​
338const updateThreadStateMap = (
339 byThreadKey: Record<string, ThreadRightPanelState>,
340 threadKey: string,
341 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
342): Record<string, ThreadRightPanelState> => {
343 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
344 const next = updater(current);
345 if (
346 !next.isOpen &&
347 next.activeSurfaceId === null &&
348 next.surfaces.length === 0 &&
349 !next.dismissedDeviceSurfaceIds?.length
350 ) {
351 if (!(threadKey in byThreadKey)) return byThreadKey;
352 const { [threadKey]: _removed, ...rest } = byThreadKey;
353 return rest;
354 }
355 if (next === current) return byThreadKey;
356 return { ...byThreadKey, [threadKey]: next };
357};
358​
359const updateThreadPanelVisibilityMap = (
360 byThreadKey: Record<string, ThreadPanelVisibility>,
361 threadKey: string,
362 updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
363): Record<string, ThreadPanelVisibility> => {
364 const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
365 const next = updater(current);
366 if (next.inlineOpen && !next.popoverOpen) {
367 if (!(threadKey in byThreadKey)) return byThreadKey;
368 const { [threadKey]: _removed, ...rest } = byThreadKey;
369 return rest;
370 }
371 if (next === current) return byThreadKey;
372 return { ...byThreadKey, [threadKey]: next };
373};
374​
375type RightPanelStoreData = Pick<
376 RightPanelStoreState,
377 "byThreadKey" | "threadPanelVisibilityByThreadKey"
378>;
379​
380/**
381 * Applies a real right-panel mutation and its thread-panel transition atomically.
382 * This is the only path real panel actions use, so visibility never has to be
383 * reconciled after the fact in React.
384 */
385const updateThread = (
386 state: RightPanelStoreData,
387 threadKey: string,
388 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
389): RightPanelStoreData => {
390 const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
391 const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
392 const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
393 let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
394​
395 if (!current.isOpen && next.isOpen) {
396 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
397 threadPanelVisibilityByThreadKey,
398 threadKey,
399 (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
400 );
401 } else if (current.isOpen && !next.isOpen) {
402 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
403 threadPanelVisibilityByThreadKey,
404 threadKey,
405 (visibility) =>
406 visibility.popoverOpen && !visibility.inlineOpen
407 ? { ...visibility, inlineOpen: true }
408 : visibility,
409 );
410 }
411​
412 return { byThreadKey, threadPanelVisibilityByThreadKey };
413};
414​
415// Every store action is a user choice unless it goes through `automaticUpdate`.
416// Only `openProactive` and resource reconciliation are automatic, so a new
417// action counts as a user choice by default.
418const automaticUpdate = (
419 state: RightPanelStoreState,
420 threadKey: string,
421 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
422): Partial<RightPanelStoreState> => ({
423 ...updateThread(state, threadKey, updater),
424});
425​
426const userAction = (
427 state: RightPanelStoreState,
428 threadKey: string,
429 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
430 closesView = false,
431): Partial<RightPanelStoreState> => ({
432 ...updateThread(state, threadKey, (current) => {
433 const next = updater(current);
434 if (next === current) return current;
435 const removedDevices = current.surfaces.filter(
436 (surface) =>
437 surface.kind === "device" && !next.surfaces.some((entry) => entry.id === surface.id),
438 );
439 if (removedDevices.length === 0) return next;
440 return {
441 ...next,
442 dismissedDeviceSurfaceIds: [
443 ...new Set([
444 ...(next.dismissedDeviceSurfaceIds ?? []),
445 ...removedDevices.map((surface) => surface.id),
446 ]),
447 ],
448 };
449 }),
450 userActionRevisionByThreadKey: {
451 ...state.userActionRevisionByThreadKey,
452 [threadKey]: (state.userActionRevisionByThreadKey[threadKey] ?? 0) + 1,
453 },
454 ...(closesView
455 ? {
456 closeRevisionByThreadKey: {
457 ...state.closeRevisionByThreadKey,
458 [threadKey]: (state.closeRevisionByThreadKey[threadKey] ?? 0) + 1,
459 },
460 }
461 : {}),
462});
463​
464const closeAction = (
465 state: RightPanelStoreState,
466 threadKey: string,
467 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
468): Partial<RightPanelStoreState> => userAction(state, threadKey, updater, true);
469​
470function normalizeRevealLine(line: number | undefined): number | null {
471 if (line === undefined || !Number.isFinite(line)) return null;
472 return Math.max(1, Math.trunc(line));
474​
475export function migratePersistedRightPanelState(persistedState: unknown): {
476 byThreadKey: Record<string, ThreadRightPanelState>;
477 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
478} {
479 if (!persistedState || typeof persistedState !== "object") {
480 return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
481 }
482 const byThreadKey =
483 "byThreadKey" in persistedState &&
484 persistedState.byThreadKey &&
485 typeof persistedState.byThreadKey === "object"
486 ? Object.fromEntries(
487 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>)
488 .filter(([threadKey]) => !isPullRequestsPanelKey(threadKey))
489 .map(([threadKey, threadState]) => {
490 const validThreadState =
491 threadState && typeof threadState === "object" ? threadState : null;
492 const surfaces = Array.isArray(validThreadState?.surfaces)
493 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
494 // Removed surfaces: plans render inline, agents in thread lineage.
495 const kind = (surface as { kind?: string }).kind;
496 if (kind === "plan" || kind === "agents") return [];
497 if (
498 (surface.kind === "file" || surface.kind === "files") &&
499 "folderTrail" in surface &&
500 typeof surface.folderTrail !== "string"
501 ) {
502 const { folderTrail: _invalid, ...rest } = surface;
503 surface = rest;
504 }
505 if (surface.kind === "file") {
506 const revealLine =
507 typeof surface.revealLine === "number" &&
508 Number.isFinite(surface.revealLine)
509 ? Math.max(1, Math.trunc(surface.revealLine))
510 : null;
511 const revealRequestId =
512 typeof surface.revealRequestId === "number" &&
513 Number.isSafeInteger(surface.revealRequestId) &&
514 surface.revealRequestId >= 0
515 ? surface.revealRequestId
516 : 0;
517 return [{ ...surface, revealLine, revealRequestId }];
518 }
519 if (surface.kind === "pull-request") {
520 if (
521 typeof surface.projectId !== "string" ||
522 typeof surface.repository !== "string" ||
523 typeof surface.number !== "number" ||
524 !Number.isSafeInteger(surface.number) ||
525 surface.number < 1
526 ) {
527 return [];
528 }
529 const { environmentId, ...rest } = surface;
530 // Anything else stored under that name is not an environment.
531 return [
532 pullRequestSurface({
533 ...rest,
534 ...(typeof environmentId === "string" ? { environmentId } : {}),
535 }),
536 ];
537 }
538 if (surface.kind !== "terminal") return [surface];
539 if (
540 !("resourceId" in surface) ||
541 typeof surface.resourceId !== "string" ||
542 surface.id !== `terminal:${surface.resourceId}`
543 ) {
544 return [];
545 }
546 const terminalIds =
547 "terminalIds" in surface && Array.isArray(surface.terminalIds)
548 ? [
549 ...new Set(
550 surface.terminalIds.filter(
551 (terminalId): terminalId is string =>
552 typeof terminalId === "string",
553 ),
554 ),
555 ]
556 : [surface.resourceId];
557 const activeTerminalId =
558 "activeTerminalId" in surface &&
559 typeof surface.activeTerminalId === "string" &&
560 terminalIds.includes(surface.activeTerminalId)
561 ? surface.activeTerminalId
562 : (terminalIds[0] ?? surface.resourceId);
563 return [
564 {
565 ...surface,
566 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
567 activeTerminalId,
568 },
569 ];
570 })
571 : [];
572 const rawActiveSurfaceId = validThreadState?.activeSurfaceId;
573 const persistedActiveSurfaceId = surfaces.some(
574 (surface) => surface.id === rawActiveSurfaceId,
575 )
576 ? (rawActiveSurfaceId ?? null)
577 : rawActiveSurfaceId === "pull-request"
578 ? (surfaces.find((surface) => surface.kind === "pull-request")?.id ?? null)
579 : null;
580 // A migration that dropped every surface (e.g. plan-only panels
581 // in v9) must not reopen an empty panel.
582 const isOpen =
583 surfaces.length > 0 &&
584 (typeof validThreadState?.isOpen === "boolean"
585 ? validThreadState.isOpen
586 : persistedActiveSurfaceId !== null);
587 // An open panel needs an active surface: if migration dropped
588 // the persisted one (e.g. plan was active), fall back to the
589 // first survivor instead of rendering an open empty panel. Removed
590 // agents selections also keep a survivor ready while the panel is closed.
591 const activeSurfaceId =
592 persistedActiveSurfaceId ??
593 (isOpen || rawActiveSurfaceId === "agents" ? (surfaces[0]?.id ?? null) : null);
594 return [
595 threadKey,
596 {
597 isOpen,
598 surfaces,
599 activeSurfaceId,
600 ...(Array.isArray(validThreadState?.dismissedDeviceSurfaceIds)
601 ? {
602 dismissedDeviceSurfaceIds:
603 validThreadState.dismissedDeviceSurfaceIds.filter(
604 (id): id is string => typeof id === "string",
605 ),
606 }
607 : {}),
608 ...(validThreadState?.maximized === true ? { maximized: true as const } : {}),
609 },
610 ];
611 }),
612 )
613 : {};
614 const threadPanelVisibilityByThreadKey =
615 "threadPanelVisibilityByThreadKey" in persistedState &&
616 persistedState.threadPanelVisibilityByThreadKey &&
617 typeof persistedState.threadPanelVisibilityByThreadKey === "object"
618 ? Object.fromEntries(
619 Object.entries(
620 persistedState.threadPanelVisibilityByThreadKey as Record<string, unknown>,
621 ).flatMap(([threadKey, value]) => {
622 if (!value || typeof value !== "object" || !("inlineOpen" in value)) return [];
623 return value.inlineOpen === false
624 ? [[threadKey, { inlineOpen: false, popoverOpen: false }]]
625 : [];
626 }),
627 )
628 : {};
629 return { byThreadKey, threadPanelVisibilityByThreadKey };
631​
632export const useRightPanelStore = create<RightPanelStoreState>()(
633 persist(
634 (set, get) => ({
635 byThreadKey: {},
636 pendingMaximizeThreadKey: null,
637 requestMaximize: (ref) => set({ pendingMaximizeThreadKey: scopedThreadKey(ref) }),
638 consumeMaximizeRequest: (ref) => {
639 if (get().pendingMaximizeThreadKey !== scopedThreadKey(ref)) return false;
640 set({ pendingMaximizeThreadKey: null });
641 return true;
642 },
643 threadPanelVisibilityByThreadKey: {},
644 userActionRevisionByThreadKey: {},
645 closeRevisionByThreadKey: {},
646 getUserActionRevision: (ref) =>
647 get().userActionRevisionByThreadKey[scopedThreadKey(ref)] ?? 0,
648 openProactive: (ref, surface, expectedUserActionRevision) => {
649 let opened = false;
650 set((state) => {
651 const threadKey = scopedThreadKey(ref);
652 if (
653 (state.userActionRevisionByThreadKey[threadKey] ?? 0) !== expectedUserActionRevision
654 ) {
655 return state;
656 }
657 // A linked PR takes priority over a completed-turn diff. Manual actions
658 // always apply, and later user choices reject both proactive requests.
659 if (
660 surface.kind === "diff" &&
661 (selectActiveRightPanel(state.byThreadKey, ref) === "pull-request" ||
662 selectActiveRightPanel(state.byThreadKey, ref) === "pull-requests")
663 ) {
664 return state;
665 }
666 opened = true;
667 return automaticUpdate(state, threadKey, (current) => upsertSurface(current, surface));
668 });
669 return opened;
670 },
671 open: (ref, kind) =>
672 set((state) =>
673 userAction(state, scopedThreadKey(ref), (current) => {
674 if (kind === "preview") {
675 const existing = current.surfaces.find((surface) => surface.kind === "preview");
676 return upsertSurface(current, existing ?? browserSurface(null));
677 }
678 return upsertSurface(current, singletonSurface(kind));
679 }),
680 ),
681 openDevice: (ref, target, automatic = false) =>
682 set((state) =>
683 (automatic ? automaticUpdate : userAction)(state, scopedThreadKey(ref), (current) => {
684 const id =
685 `device:${encodeURIComponent(target.hostId)}:${encodeURIComponent(target.deviceId)}` as const;
686 if (automatic && current.dismissedDeviceSurfaceIds?.includes(id)) return current;
687 const surface: RightPanelSurface = { id, kind: "device", target };
688 const existing = current.surfaces.find((entry) => entry.id === id);
689 const surfaces = existing
690 ? current.surfaces.filter((entry) => entry.id !== "device")
691 : current.surfaces.map((entry) => (entry.id === "device" ? surface : entry));
692 return upsertSurface(
693 {
694 ...current,
695 surfaces,
696 dismissedDeviceSurfaceIds: (current.dismissedDeviceSurfaceIds ?? []).filter(
697 (entry) => entry !== id,
698 ),
699 },
700 existing ?? surface,
701 );
702 }),
703 ),
704 renameDevice: (ref, surfaceId, title) =>
705 set((state) =>
706 userAction(state, scopedThreadKey(ref), (current) => ({
707 ...current,
708 surfaces: current.surfaces.map((surface) =>
709 surface.id === surfaceId && surface.kind === "device"
710 ? { ...surface, title: title.trim() || surface.target?.name || "Device" }
711 : surface,
712 ),
713 })),
714 ),
715 openBrowser: (ref, tabId) =>
716 set((state) =>
717 userAction(state, scopedThreadKey(ref), (current) => {
718 const surface = browserSurface(tabId);
719 const withoutPlaceholder = tabId
720 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
721 : current.surfaces;
722 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
723 }),
724 ),
725 openPullRequest: (ref, target) =>
726 set((state) =>
727 userAction(state, scopedThreadKey(ref), (current) => {
728 const surface = pullRequestSurface(target);
729 const next = upsertSurface(current, surface);
730 return target.url
731 ? {
732 ...next,
733 surfaces: next.surfaces.map((entry) =>
734 entry.id === surface.id ? surface : entry,
735 ),
736 }
737 : next;
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 // A tab already showing the target wins, so its state is never replaced.
787 const existing = current.surfaces.some(
788 (surface, i) => i !== index && surface.id === target.id,
789 );
790 const surfaces = current.surfaces.flatMap((surface, i) => {
791 if (i === index) {
792 const kept = keepSource ? [source] : [];
793 return existing ? kept : [...kept, target];
794 }
795 // Like openFile: a file surface replaces the standalone explorer.
796 return !existing && target.kind === "file" && surface.kind === "files"
797 ? []
798 : [surface];
799 });
800 return { ...current, isOpen: true, activeSurfaceId: target.id, surfaces };
801 }),
802 ),
803 openAttachment: (ref, attachment) =>
804 set((state) =>
805 userAction(state, scopedThreadKey(ref), (current) => {
806 const withoutStandaloneExplorer = current.surfaces.filter(
807 (surface) => surface.kind !== "files",
808 );
809 return upsertSurface(
810 { ...current, surfaces: withoutStandaloneExplorer },
811 attachmentSurface(attachment),
812 );
813 }),
814 ),
815 openTerminal: (ref, terminalId) =>
816 set((state) =>
817 userAction(state, scopedThreadKey(ref), (current) =>
818 upsertSurface(current, terminalSurface(terminalId)),
819 ),
820 ),
821 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
822 set((state) =>
823 userAction(state, scopedThreadKey(ref), (current) => ({
824 ...current,
825 isOpen: true,
826 activeSurfaceId: surfaceId,
827 surfaces: current.surfaces.map((surface) => {
828 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
829 const { splitDirection: _splitDirection, ...baseSurface } = surface;
830 return {
831 ...baseSurface,
832 terminalIds: surface.terminalIds.includes(terminalId)
833 ? surface.terminalIds
834 : [...surface.terminalIds, terminalId],
835 activeTerminalId: terminalId,
836 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
837 };
838 }),
839 })),
840 ),
841 activateTerminal: (ref, surfaceId, terminalId) =>
842 set((state) =>
843 userAction(state, scopedThreadKey(ref), (current) => ({
844 ...current,
845 activeSurfaceId: surfaceId,
846 surfaces: current.surfaces.map((surface) =>
847 surface.id === surfaceId &&
848 surface.kind === "terminal" &&
849 surface.terminalIds.includes(terminalId)
850 ? { ...surface, activeTerminalId: terminalId }
851 : surface,
852 ),
853 })),
854 ),
855 closeTerminal: (ref, surfaceId, terminalId) =>
856 set((state) =>
857 closeAction(state, scopedThreadKey(ref), (current) => {
858 const surface = current.surfaces.find(
859 (entry) => entry.id === surfaceId && entry.kind === "terminal",
860 );
861 if (!surface || surface.kind !== "terminal") return current;
862 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
863 if (terminalIds.length === 0) {
864 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
865 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
866 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
867 return {
868 ...current,
869 isOpen: surfaces.length > 0 && current.isOpen,
870 surfaces,
871 activeSurfaceId:
872 current.activeSurfaceId === surfaceId
873 ? (fallback?.id ?? null)
874 : current.activeSurfaceId,
875 };
876 }
877 return {
878 ...current,
879 surfaces: current.surfaces.map((entry) =>
880 entry.id === surfaceId && entry.kind === "terminal"
881 ? {
882 ...entry,
883 terminalIds,
884 activeTerminalId:
885 entry.activeTerminalId === terminalId
886 ? (terminalIds.at(-1) ?? terminalIds[0]!)
887 : entry.activeTerminalId,
888 }
889 : entry,
890 ),
891 };
892 }),
893 ),
894 activateSurface: (ref, surfaceId) =>
895 set((state) =>
896 userAction(state, scopedThreadKey(ref), (current) =>
897 current.surfaces.some((surface) => surface.id === surfaceId)
898 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
899 : current,
900 ),
901 ),
902 closeSurface: (ref, surfaceId) =>
903 set((state) =>
904 closeAction(state, scopedThreadKey(ref), (current) => {
905 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
906 if (index < 0) return current;
907 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
908 const next = {
909 ...current,
910 isOpen: surfaces.length > 0 && current.isOpen,
911 surfaces,
912 };
913 if (current.activeSurfaceId !== surfaceId) {
914 return next;
915 }
916 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
917 return {
918 ...next,
919 activeSurfaceId: fallback?.id ?? null,
920 };
921 }),
922 ),
923 closeOtherSurfaces: (ref, surfaceId) =>
924 set((state) =>
925 closeAction(state, scopedThreadKey(ref), (current) => {
926 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
927 if (!surface || current.surfaces.length === 1) return current;
928 return {
929 ...current,
930 isOpen: true,
931 surfaces: [surface],
932 activeSurfaceId: surface.id,
933 };
934 }),
935 ),
936 closeSurfacesToRight: (ref, surfaceId) =>
937 set((state) =>
938 closeAction(state, scopedThreadKey(ref), (current) => {
939 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
940 if (index < 0 || index === current.surfaces.length - 1) return current;
941 const surfaces = current.surfaces.slice(0, index + 1);
942 const activeStillExists = surfaces.some(
943 (surface) => surface.id === current.activeSurfaceId,
944 );
945 return {
946 ...current,
947 surfaces,
948 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
949 };
950 }),
951 ),
952 closeAllSurfaces: (ref) =>
953 set((state) =>
954 closeAction(state, scopedThreadKey(ref), (current) =>
955 current.surfaces.length === 0
956 ? current
957 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
958 ),
959 ),
960 // Reordering is not a choice about what the panel shows, so it leaves the
961 // user-action revision alone and proactive opens still apply.
962 moveSurface: (ref, surfaceId, toIndex) =>
963 set((state) =>
964 updateThread(state, scopedThreadKey(ref), (current) => {
965 const fromIndex = current.surfaces.findIndex((surface) => surface.id === surfaceId);
966 if (fromIndex < 0 || fromIndex === toIndex) return current;
967 const surfaces = [...current.surfaces];
968 surfaces.splice(toIndex, 0, ...surfaces.splice(fromIndex, 1));
969 return { ...current, surfaces };
970 }),
971 ),
972 reconcileBrowserSurfaces: (ref, tabIds, hiddenTabIds) =>
973 set((state) =>
974 automaticUpdate(state, scopedThreadKey(ref), (current) => {
975 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
976 // Filtered in place so browser tabs keep the order the user dragged them into.
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 // Layout only: it changes no surface, so proactive panels still apply.
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​
1208/** The selected surface even while the panel is hidden, so a layout control can restore it. */
1209export function selectSelectedRightPanelSurface(
1210 byThreadKey: Record<string, ThreadRightPanelState>,
1211 ref: ScopedThreadRef | null | undefined,
1212): RightPanelSurface | null {
1213 const state = selectThreadRightPanelState(byThreadKey, ref);
1214 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;