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