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 // Workspace entry paths use '/', including on Windows.
672 const relativePath = /^[A-Za-z]:\/+$/.test(requestedPath)
673 ? requestedPath
674 : requestedPath.replace(/\/+$/, "") || requestedPath;
675 const withoutStandaloneExplorer = current.surfaces.filter(
676 (surface) => surface.kind !== "files",
677 );
678 const surfaceId = `file:${relativePath}` as const;
679 const existing = withoutStandaloneExplorer.find(
680 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
681 surface.id === surfaceId && surface.kind === "file",
682 );
683 const surface = fileSurface(
684 relativePath,
685 normalizeRevealLine(line),
686 (existing?.revealRequestId ?? 0) + 1,
687 );
688 return {
689 ...current,
690 isOpen: true,
691 activeSurfaceId: surface.id,
692 surfaces: existing
693 ? withoutStandaloneExplorer.map((entry) =>
694 entry.id === surface.id ? surface : entry,
695 )
696 : [...withoutStandaloneExplorer, surface],
697 };
698 }),
699 ),
700 openAttachment: (ref, attachment) =>
701 set((state) =>
702 userAction(state, scopedThreadKey(ref), (current) => {
703 const withoutStandaloneExplorer = current.surfaces.filter(
704 (surface) => surface.kind !== "files",
705 );
706 return upsertSurface(
707 { ...current, surfaces: withoutStandaloneExplorer },
708 attachmentSurface(attachment),
709 );
710 }),
711 ),
712 openTerminal: (ref, terminalId) =>
713 set((state) =>
714 userAction(state, scopedThreadKey(ref), (current) =>
715 upsertSurface(current, terminalSurface(terminalId)),
716 ),
717 ),
718 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
719 set((state) =>
720 userAction(state, scopedThreadKey(ref), (current) => ({
721 ...current,
722 isOpen: true,
723 activeSurfaceId: surfaceId,
724 surfaces: current.surfaces.map((surface) => {
725 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
726 const { splitDirection: _splitDirection, ...baseSurface } = surface;
727 return {
728 ...baseSurface,
729 terminalIds: surface.terminalIds.includes(terminalId)
730 ? surface.terminalIds
731 : [...surface.terminalIds, terminalId],
732 activeTerminalId: terminalId,
733 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
734 };
735 }),
736 })),
737 ),
738 activateTerminal: (ref, surfaceId, terminalId) =>
739 set((state) =>
740 userAction(state, scopedThreadKey(ref), (current) => ({
741 ...current,
742 activeSurfaceId: surfaceId,
743 surfaces: current.surfaces.map((surface) =>
744 surface.id === surfaceId &&
745 surface.kind === "terminal" &&
746 surface.terminalIds.includes(terminalId)
747 ? { ...surface, activeTerminalId: terminalId }
748 : surface,
749 ),
750 })),
751 ),
752 closeTerminal: (ref, surfaceId, terminalId) =>
753 set((state) =>
754 userAction(state, scopedThreadKey(ref), (current) => {
755 const surface = current.surfaces.find(
756 (entry) => entry.id === surfaceId && entry.kind === "terminal",
757 );
758 if (!surface || surface.kind !== "terminal") return current;
759 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
760 if (terminalIds.length === 0) {
761 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
762 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
763 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
764 return {
765 ...current,
766 isOpen: surfaces.length > 0 && current.isOpen,
767 surfaces,
768 activeSurfaceId:
769 current.activeSurfaceId === surfaceId
770 ? (fallback?.id ?? null)
771 : current.activeSurfaceId,
772 };
773 }
774 return {
775 ...current,
776 surfaces: current.surfaces.map((entry) =>
777 entry.id === surfaceId && entry.kind === "terminal"
778 ? {
779 ...entry,
780 terminalIds,
781 activeTerminalId:
782 entry.activeTerminalId === terminalId
783 ? (terminalIds.at(-1) ?? terminalIds[0]!)
784 : entry.activeTerminalId,
785 }
786 : entry,
787 ),
788 };
789 }),
790 ),
791 activateSurface: (ref, surfaceId) =>
792 set((state) =>
793 userAction(state, scopedThreadKey(ref), (current) =>
794 current.surfaces.some((surface) => surface.id === surfaceId)
795 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
796 : current,
797 ),
798 ),
799 closeSurface: (ref, surfaceId) =>
800 set((state) =>
801 userAction(state, scopedThreadKey(ref), (current) => {
802 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
803 if (index < 0) return current;
804 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
805 if (current.activeSurfaceId !== surfaceId) {
806 return { ...current, isOpen: surfaces.length > 0 && current.isOpen, surfaces };
807 }
808 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
809 return {
810 ...current,
811 isOpen: surfaces.length > 0 && current.isOpen,
812 surfaces,
813 activeSurfaceId: fallback?.id ?? null,
814 };
815 }),
816 ),
817 closeOtherSurfaces: (ref, surfaceId) =>
818 set((state) =>
819 userAction(state, scopedThreadKey(ref), (current) => {
820 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
821 if (!surface || current.surfaces.length === 1) return current;
822 return {
823 ...current,
824 isOpen: true,
825 surfaces: [surface],
826 activeSurfaceId: surface.id,
827 };
828 }),
829 ),
830 closeSurfacesToRight: (ref, surfaceId) =>
831 set((state) =>
832 userAction(state, scopedThreadKey(ref), (current) => {
833 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
834 if (index < 0 || index === current.surfaces.length - 1) return current;
835 const surfaces = current.surfaces.slice(0, index + 1);
836 const activeStillExists = surfaces.some(
837 (surface) => surface.id === current.activeSurfaceId,
838 );
839 return {
840 ...current,
841 surfaces,
842 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
843 };
844 }),
845 ),
846 closeAllSurfaces: (ref) =>
847 set((state) =>
848 userAction(state, scopedThreadKey(ref), (current) =>
849 current.surfaces.length === 0
850 ? current
851 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
852 ),
853 ),
854 reconcileBrowserSurfaces: (ref, tabIds) =>
855 set((state) =>
856 automaticUpdate(state, scopedThreadKey(ref), (current) => {
857 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
858 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
859 const existingBrowser = current.surfaces.filter(
860 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
861 surface.kind === "preview" &&
862 surface.id !== "browser:new" &&
863 validIds.has(surface.id),
864 );
865 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
866 const added = tabIds
867 .filter((tabId) => !knownIds.has(`browser:${tabId}`))
868 .map((tabId) => browserSurface(tabId));
869 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
870 const activeStillExists = surfaces.some(
871 (surface) => surface.id === current.activeSurfaceId,
872 );
873 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
874 return {
875 ...current,
876 surfaces,
877 activeSurfaceId: activeStillExists
878 ? current.activeSurfaceId
879 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
880 };
881 }),
882 ),
883 reconcileFileSurfaces: (ref, workspaceAvailable) =>
884 set((state) =>
885 automaticUpdate(state, scopedThreadKey(ref), (current) => {
886 if (workspaceAvailable) return current;
887 const surfaces = current.surfaces.filter(
888 (surface) =>
889 surface.kind !== "files" &&
890 (surface.kind !== "file" || surface.attachment !== undefined),
891 );
892 if (surfaces.length === current.surfaces.length) return current;
893 const activeStillExists = surfaces.some(
894 (surface) => surface.id === current.activeSurfaceId,
895 );
896 return {
897 ...current,
898 isOpen: surfaces.length > 0 ? current.isOpen : false,
899 surfaces,
900 activeSurfaceId: activeStillExists
901 ? current.activeSurfaceId
902 : (surfaces.at(-1)?.id ?? null),
903 };
904 }),
905 ),
906 show: (ref) =>
907 set((state) =>
908 userAction(state, scopedThreadKey(ref), (current) =>
909 current.isOpen ? current : { ...current, isOpen: true },
910 ),
911 ),
912 close: (ref) =>
913 set((state) =>
914 userAction(state, scopedThreadKey(ref), (current) =>
915 current.isOpen ? { ...current, isOpen: false } : current,
916 ),
917 ),
918 toggleVisibility: (ref) =>
919 set((state) =>
920 userAction(state, scopedThreadKey(ref), (current) => ({
921 ...current,
922 isOpen: !current.isOpen,
923 })),
924 ),
925 toggle: (ref, kind) =>
926 set((state) =>
927 userAction(state, scopedThreadKey(ref), (current) => {
928 const active = current.surfaces.find(
929 (surface) => surface.id === current.activeSurfaceId,
930 );
931 if (current.isOpen && active?.kind === kind) {
932 return { ...current, isOpen: false };
933 }
934 if (kind === "preview") {
935 const existing = current.surfaces.find((surface) => surface.kind === "preview");
936 return upsertSurface(current, existing ?? browserSurface(null));
937 }
938 return upsertSurface(current, singletonSurface(kind));
939 }),
940 ),
941 setThreadPanelOpen: (ref, presentation, open) =>
942 set((state) => ({
943 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
944 state.threadPanelVisibilityByThreadKey,
945 scopedThreadKey(ref),
946 (visibility) => {
947 const key = presentation === "inline" ? "inlineOpen" : "popoverOpen";
948 return visibility[key] === open ? visibility : { ...visibility, [key]: open };
949 },
950 ),
951 })),
952 toggleThreadPanel: (ref, presentation) =>
953 set((state) => ({
954 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
955 state.threadPanelVisibilityByThreadKey,
956 scopedThreadKey(ref),
957 (visibility) =>
958 presentation === "inline"
959 ? { ...visibility, inlineOpen: !visibility.inlineOpen }
960 : { ...visibility, popoverOpen: !visibility.popoverOpen },
961 ),
962 })),
963 removeThread: (ref) =>
964 set((state) => {
965 const threadKey = scopedThreadKey(ref);
966 if (
967 !(threadKey in state.byThreadKey) &&
968 !(threadKey in state.threadPanelVisibilityByThreadKey) &&
969 !(threadKey in state.userActionRevisionByThreadKey)
970 ) {
971 return state;
972 }
973 const { [threadKey]: _removed, ...byThreadKey } = state.byThreadKey;
974 const { [threadKey]: _visibility, ...threadPanelVisibilityByThreadKey } =
975 state.threadPanelVisibilityByThreadKey;
976 const { [threadKey]: _revision, ...userActionRevisionByThreadKey } =
977 state.userActionRevisionByThreadKey;
978 return {
979 byThreadKey,
980 threadPanelVisibilityByThreadKey,
981 userActionRevisionByThreadKey,
982 };
983 }),
984 }),
985 {
986 name: RIGHT_PANEL_STORAGE_KEY,
987 version: RIGHT_PANEL_STORAGE_VERSION,
988 storage: createJSONStorage(() =>
989 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
990 ),
991 partialize: (state) => ({
992 byThreadKey: Object.fromEntries(
993 Object.entries(state.byThreadKey).filter(
994 ([threadKey]) => !isPullRequestsPanelKey(threadKey),
995 ),
996 ),
997 threadPanelVisibilityByThreadKey: Object.fromEntries(
998 Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
999 ([threadKey, visibility]) =>
1000 visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
1001 ),
1002 ),
1003 }),
1004 migrate: migratePersistedRightPanelState,
1005 },
1006 ),
1007);
1008
1009export function selectThreadRightPanelState(
1010 byThreadKey: Record<string, ThreadRightPanelState>,
1011 ref: ScopedThreadRef | null | undefined,
1012): ThreadRightPanelState {
1013 if (!ref) return EMPTY_THREAD_STATE;
1014 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
1015}
1016
1017export function selectThreadPanelVisibility(
1018 byThreadKey: Record<string, ThreadPanelVisibility>,
1019 ref: ScopedThreadRef | null | undefined,
1020): ThreadPanelVisibility {
1021 if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY;
1022 return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
1023}
1024
1025export function selectThreadPanelOpen(
1026 byThreadKey: Record<string, ThreadPanelVisibility>,
1027 ref: ScopedThreadRef | null | undefined,
1028 presentation: ThreadPanelPresentation,
1029): boolean {
1030 const visibility = selectThreadPanelVisibility(byThreadKey, ref);
1031 return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
1032}
1033
1034export function selectActiveRightPanel(
1035 byThreadKey: Record<string, ThreadRightPanelState>,
1036 ref: ScopedThreadRef | null | undefined,
1037): RightPanelKind | null {
1038 const state = selectThreadRightPanelState(byThreadKey, ref);
1039 if (!state.isOpen) return null;
1040 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
1041}
1042
1043export function selectActiveRightPanelSurface(
1044 byThreadKey: Record<string, ThreadRightPanelState>,
1045 ref: ScopedThreadRef | null | undefined,
1046): RightPanelSurface | null {
1047 const state = selectThreadRightPanelState(byThreadKey, ref);
1048 if (!state.isOpen) return null;
1049 return selectSelectedRightPanelSurface(byThreadKey, ref);
1050}
1051
1052/** The selected surface even while the panel is hidden, so a layout control can restore it. */
1053export function selectSelectedRightPanelSurface(
1054 byThreadKey: Record<string, ThreadRightPanelState>,
1055 ref: ScopedThreadRef | null | undefined,
1056): RightPanelSurface | null {
1057 const state = selectThreadRightPanelState(byThreadKey, ref);
1058 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
1059}