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

rightPanelStore.ts

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