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

rightPanelStore.ts

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