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

rightPanelStore.ts

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