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/plan/files remain singleton surfaces.
9 */
10import { scopedThreadKey } from "@v12/client-runtime/environment";
11import type { ScopedThreadRef } from "@v12/contracts";
12import { create } from "zustand";
13import { createJSONStorage, persist } from "zustand/middleware";
14
15import { resolveStorage } from "./lib/storage";
16
17export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const;
18export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
19
20export type RightPanelSurface =
21 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
22 | { id: "browser:new"; kind: "preview"; resourceId: null }
23 | {
24 id: `terminal:${string}`;
25 kind: "terminal";
26 resourceId: string;
27 terminalIds: string[];
28 activeTerminalId: string;
29 splitDirection?: "horizontal" | "vertical";
30 }
31 | { id: "diff"; kind: "diff" }
32 | { id: "files"; kind: "files" }
33 | {
34 id: `file:${string}`;
35 kind: "file";
36 relativePath: string;
37 revealLine: number | null;
38 revealRequestId: number;
39 }
40 | { id: "plan"; kind: "plan" };
41
42const RIGHT_PANEL_STORAGE_KEY = "v12:right-panel-state:v2";
43const RIGHT_PANEL_STORAGE_VERSION = 7;
44
45export interface ThreadRightPanelState {
46 isOpen: boolean;
47 activeSurfaceId: string | null;
48 surfaces: RightPanelSurface[];
49}
50
51interface RightPanelStoreState {
52 byThreadKey: Record<string, ThreadRightPanelState>;
53 open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
54 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
55 openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
56 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
57 splitTerminal: (
58 ref: ScopedThreadRef,
59 surfaceId: string,
60 terminalId: string,
61 direction?: "horizontal" | "vertical",
62 ) => void;
63 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
64 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
65 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
66 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
67 closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
68 closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
69 closeAllSurfaces: (ref: ScopedThreadRef) => void;
70 reconcileBrowserSurfaces: (ref: ScopedThreadRef, tabIds: readonly string[]) => void;
71 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
72 show: (ref: ScopedThreadRef) => void;
73 close: (ref: ScopedThreadRef) => void;
74 toggleVisibility: (ref: ScopedThreadRef) => void;
75 toggle: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
76 removeThread: (ref: ScopedThreadRef) => void;
77}
78
79const EMPTY_THREAD_STATE: ThreadRightPanelState = {
80 isOpen: false,
81 activeSurfaceId: null,
82 surfaces: [],
83};
84
85const singletonSurface = (
86 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal">,
87): RightPanelSurface => {
88 switch (kind) {
89 case "diff":
90 return { id: "diff", kind };
91 case "files":
92 return { id: "files", kind };
93 case "plan":
94 return { id: "plan", kind };
95 }
96};
97
98const browserSurface = (tabId: string | null): RightPanelSurface =>
99 tabId
100 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
101 : { id: "browser:new", kind: "preview", resourceId: null };
102
103const fileSurface = (
104 relativePath: string,
105 revealLine: number | null,
106 revealRequestId: number,
107): RightPanelSurface => ({
108 id: `file:${relativePath}`,
109 kind: "file",
110 relativePath,
111 revealLine,
112 revealRequestId,
113});
114
115const terminalSurface = (terminalId: string): RightPanelSurface => ({
116 id: `terminal:${terminalId}`,
117 kind: "terminal",
118 resourceId: terminalId,
119 terminalIds: [terminalId],
120 activeTerminalId: terminalId,
121});
122
123const upsertSurface = (
124 current: ThreadRightPanelState,
125 surface: RightPanelSurface,
126 activate = true,
127): ThreadRightPanelState => ({
128 isOpen: true,
129 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
130 ? current.surfaces
131 : [...current.surfaces, surface],
132 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
133});
134
135const updateThread = (
136 byThreadKey: Record<string, ThreadRightPanelState>,
137 threadKey: string,
138 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
139): Record<string, ThreadRightPanelState> => {
140 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
141 const next = updater(current);
142 if (!next.isOpen && next.activeSurfaceId === null && next.surfaces.length === 0) {
143 if (!(threadKey in byThreadKey)) return byThreadKey;
144 const { [threadKey]: _removed, ...rest } = byThreadKey;
145 return rest;
146 }
147 if (next === current) return byThreadKey;
148 return { ...byThreadKey, [threadKey]: next };
149};
150
151function normalizeRevealLine(line: number | undefined): number | null {
152 if (line === undefined || !Number.isFinite(line)) return null;
153 return Math.max(1, Math.trunc(line));
154}
155
156export function migratePersistedRightPanelState(persistedState: unknown): {
157 byThreadKey: Record<string, ThreadRightPanelState>;
158} {
159 if (!persistedState || typeof persistedState !== "object") {
160 return { byThreadKey: {} };
161 }
162 const byThreadKey =
163 "byThreadKey" in persistedState &&
164 persistedState.byThreadKey &&
165 typeof persistedState.byThreadKey === "object"
166 ? Object.fromEntries(
167 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>).map(
168 ([threadKey, threadState]) => {
169 const validThreadState =
170 threadState && typeof threadState === "object" ? threadState : null;
171 const surfaces = Array.isArray(validThreadState?.surfaces)
172 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
173 if (surface.kind === "file") {
174 const revealLine =
175 typeof surface.revealLine === "number" &&
176 Number.isFinite(surface.revealLine)
177 ? Math.max(1, Math.trunc(surface.revealLine))
178 : null;
179 const revealRequestId =
180 typeof surface.revealRequestId === "number" &&
181 Number.isSafeInteger(surface.revealRequestId) &&
182 surface.revealRequestId >= 0
183 ? surface.revealRequestId
184 : 0;
185 return [{ ...surface, revealLine, revealRequestId }];
186 }
187 if (surface.kind !== "terminal") return [surface];
188 if (
189 !("resourceId" in surface) ||
190 typeof surface.resourceId !== "string" ||
191 surface.id !== `terminal:${surface.resourceId}`
192 ) {
193 return [];
194 }
195 const terminalIds =
196 "terminalIds" in surface && Array.isArray(surface.terminalIds)
197 ? [
198 ...new Set(
199 surface.terminalIds.filter(
200 (terminalId): terminalId is string =>
201 typeof terminalId === "string",
202 ),
203 ),
204 ]
205 : [surface.resourceId];
206 const activeTerminalId =
207 "activeTerminalId" in surface &&
208 typeof surface.activeTerminalId === "string" &&
209 terminalIds.includes(surface.activeTerminalId)
210 ? surface.activeTerminalId
211 : (terminalIds[0] ?? surface.resourceId);
212 return [
213 {
214 ...surface,
215 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
216 activeTerminalId,
217 },
218 ];
219 })
220 : [];
221 const activeSurfaceId = surfaces.some(
222 (surface) => surface.id === validThreadState?.activeSurfaceId,
223 )
224 ? (validThreadState?.activeSurfaceId ?? null)
225 : null;
226 const isOpen =
227 typeof validThreadState?.isOpen === "boolean"
228 ? validThreadState.isOpen
229 : activeSurfaceId !== null;
230 return [threadKey, { isOpen, surfaces, activeSurfaceId }];
231 },
232 ),
233 )
234 : {};
235 return { byThreadKey };
236}
237
238export const useRightPanelStore = create<RightPanelStoreState>()(
239 persist(
240 (set) => ({
241 byThreadKey: {},
242 open: (ref, kind) =>
243 set((state) => ({
244 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
245 if (kind === "preview") {
246 const existing = current.surfaces.find((surface) => surface.kind === "preview");
247 return upsertSurface(current, existing ?? browserSurface(null));
248 }
249 return upsertSurface(current, singletonSurface(kind));
250 }),
251 })),
252 openBrowser: (ref, tabId) =>
253 set((state) => ({
254 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
255 const surface = browserSurface(tabId);
256 const withoutPlaceholder = tabId
257 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
258 : current.surfaces;
259 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
260 }),
261 })),
262 openFile: (ref, relativePath, line) =>
263 set((state) => ({
264 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
265 const withoutStandaloneExplorer = current.surfaces.filter(
266 (surface) => surface.kind !== "files",
267 );
268 const surfaceId = `file:${relativePath}` as const;
269 const existing = withoutStandaloneExplorer.find(
270 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
271 surface.id === surfaceId && surface.kind === "file",
272 );
273 const surface = fileSurface(
274 relativePath,
275 normalizeRevealLine(line),
276 (existing?.revealRequestId ?? 0) + 1,
277 );
278 return {
279 isOpen: true,
280 activeSurfaceId: surface.id,
281 surfaces: existing
282 ? withoutStandaloneExplorer.map((entry) =>
283 entry.id === surface.id ? surface : entry,
284 )
285 : [...withoutStandaloneExplorer, surface],
286 };
287 }),
288 })),
289 openTerminal: (ref, terminalId) =>
290 set((state) => ({
291 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
292 upsertSurface(current, terminalSurface(terminalId)),
293 ),
294 })),
295 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
296 set((state) => ({
297 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
298 ...current,
299 isOpen: true,
300 activeSurfaceId: surfaceId,
301 surfaces: current.surfaces.map((surface) => {
302 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
303 const { splitDirection: _splitDirection, ...baseSurface } = surface;
304 return {
305 ...baseSurface,
306 terminalIds: surface.terminalIds.includes(terminalId)
307 ? surface.terminalIds
308 : [...surface.terminalIds, terminalId],
309 activeTerminalId: terminalId,
310 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
311 };
312 }),
313 })),
314 })),
315 activateTerminal: (ref, surfaceId, terminalId) =>
316 set((state) => ({
317 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
318 ...current,
319 activeSurfaceId: surfaceId,
320 surfaces: current.surfaces.map((surface) =>
321 surface.id === surfaceId &&
322 surface.kind === "terminal" &&
323 surface.terminalIds.includes(terminalId)
324 ? { ...surface, activeTerminalId: terminalId }
325 : surface,
326 ),
327 })),
328 })),
329 closeTerminal: (ref, surfaceId, terminalId) =>
330 set((state) => ({
331 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
332 const surface = current.surfaces.find(
333 (entry) => entry.id === surfaceId && entry.kind === "terminal",
334 );
335 if (!surface || surface.kind !== "terminal") return current;
336 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
337 if (terminalIds.length === 0) {
338 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
339 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
340 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
341 return {
342 ...current,
343 isOpen: surfaces.length > 0 && current.isOpen,
344 surfaces,
345 activeSurfaceId:
346 current.activeSurfaceId === surfaceId
347 ? (fallback?.id ?? null)
348 : current.activeSurfaceId,
349 };
350 }
351 return {
352 ...current,
353 surfaces: current.surfaces.map((entry) =>
354 entry.id === surfaceId && entry.kind === "terminal"
355 ? {
356 ...entry,
357 terminalIds,
358 activeTerminalId:
359 entry.activeTerminalId === terminalId
360 ? (terminalIds.at(-1) ?? terminalIds[0]!)
361 : entry.activeTerminalId,
362 }
363 : entry,
364 ),
365 };
366 }),
367 })),
368 activateSurface: (ref, surfaceId) =>
369 set((state) => ({
370 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
371 current.surfaces.some((surface) => surface.id === surfaceId)
372 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
373 : current,
374 ),
375 })),
376 closeSurface: (ref, surfaceId) =>
377 set((state) => ({
378 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
379 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
380 if (index < 0) return current;
381 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
382 if (current.activeSurfaceId !== surfaceId) {
383 return { ...current, isOpen: surfaces.length > 0 && current.isOpen, surfaces };
384 }
385 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
386 return {
387 ...current,
388 isOpen: surfaces.length > 0 && current.isOpen,
389 surfaces,
390 activeSurfaceId: fallback?.id ?? null,
391 };
392 }),
393 })),
394 closeOtherSurfaces: (ref, surfaceId) =>
395 set((state) => ({
396 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
397 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
398 if (!surface || current.surfaces.length === 1) return current;
399 return {
400 ...current,
401 isOpen: true,
402 surfaces: [surface],
403 activeSurfaceId: surface.id,
404 };
405 }),
406 })),
407 closeSurfacesToRight: (ref, surfaceId) =>
408 set((state) => ({
409 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
410 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
411 if (index < 0 || index === current.surfaces.length - 1) return current;
412 const surfaces = current.surfaces.slice(0, index + 1);
413 const activeStillExists = surfaces.some(
414 (surface) => surface.id === current.activeSurfaceId,
415 );
416 return {
417 ...current,
418 surfaces,
419 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
420 };
421 }),
422 })),
423 closeAllSurfaces: (ref) =>
424 set((state) => ({
425 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
426 current.surfaces.length === 0
427 ? current
428 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
429 ),
430 })),
431 reconcileBrowserSurfaces: (ref, tabIds) =>
432 set((state) => ({
433 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
434 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
435 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
436 const existingBrowser = current.surfaces.filter(
437 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
438 surface.kind === "preview" &&
439 surface.id !== "browser:new" &&
440 validIds.has(surface.id),
441 );
442 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
443 const added = tabIds
444 .filter((tabId) => !knownIds.has(`browser:${tabId}`))
445 .map((tabId) => browserSurface(tabId));
446 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
447 const activeStillExists = surfaces.some(
448 (surface) => surface.id === current.activeSurfaceId,
449 );
450 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
451 return {
452 ...current,
453 surfaces,
454 activeSurfaceId: activeStillExists
455 ? current.activeSurfaceId
456 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
457 };
458 }),
459 })),
460 reconcileFileSurfaces: (ref, workspaceAvailable) =>
461 set((state) => ({
462 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
463 if (workspaceAvailable) return current;
464 const surfaces = current.surfaces.filter(
465 (surface) => surface.kind !== "files" && surface.kind !== "file",
466 );
467 if (surfaces.length === current.surfaces.length) return current;
468 const activeStillExists = surfaces.some(
469 (surface) => surface.id === current.activeSurfaceId,
470 );
471 return {
472 ...current,
473 isOpen: surfaces.length > 0 ? current.isOpen : false,
474 surfaces,
475 activeSurfaceId: activeStillExists
476 ? current.activeSurfaceId
477 : (surfaces.at(-1)?.id ?? null),
478 };
479 }),
480 })),
481 show: (ref) =>
482 set((state) => ({
483 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
484 current.isOpen ? current : { ...current, isOpen: true },
485 ),
486 })),
487 close: (ref) =>
488 set((state) => ({
489 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
490 current.isOpen ? { ...current, isOpen: false } : current,
491 ),
492 })),
493 toggleVisibility: (ref) =>
494 set((state) => ({
495 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
496 ...current,
497 isOpen: !current.isOpen,
498 })),
499 })),
500 toggle: (ref, kind) =>
501 set((state) => ({
502 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
503 const active = current.surfaces.find(
504 (surface) => surface.id === current.activeSurfaceId,
505 );
506 if (current.isOpen && active?.kind === kind) {
507 return { ...current, isOpen: false };
508 }
509 if (kind === "preview") {
510 const existing = current.surfaces.find((surface) => surface.kind === "preview");
511 return upsertSurface(current, existing ?? browserSurface(null));
512 }
513 return upsertSurface(current, singletonSurface(kind));
514 }),
515 })),
516 removeThread: (ref) =>
517 set((state) => {
518 const threadKey = scopedThreadKey(ref);
519 if (!(threadKey in state.byThreadKey)) return state;
520 const { [threadKey]: _removed, ...rest } = state.byThreadKey;
521 return { byThreadKey: rest };
522 }),
523 }),
524 {
525 name: RIGHT_PANEL_STORAGE_KEY,
526 version: RIGHT_PANEL_STORAGE_VERSION,
527 storage: createJSONStorage(() =>
528 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
529 ),
530 partialize: (state) => ({ byThreadKey: state.byThreadKey }),
531 migrate: migratePersistedRightPanelState,
532 },
533 ),
534);
535
536export function selectThreadRightPanelState(
537 byThreadKey: Record<string, ThreadRightPanelState>,
538 ref: ScopedThreadRef | null | undefined,
539): ThreadRightPanelState {
540 if (!ref) return EMPTY_THREAD_STATE;
541 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
542}
543
544export function selectActiveRightPanel(
545 byThreadKey: Record<string, ThreadRightPanelState>,
546 ref: ScopedThreadRef | null | undefined,
547): RightPanelKind | null {
548 const state = selectThreadRightPanelState(byThreadKey, ref);
549 if (!state.isOpen) return null;
550 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
551}
552
553export function selectActiveRightPanelSurface(
554 byThreadKey: Record<string, ThreadRightPanelState>,
555 ref: ScopedThreadRef | null | undefined,
556): RightPanelSurface | null {
557 const state = selectThreadRightPanelState(byThreadKey, ref);
558 if (!state.isOpen) return null;
559 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
560}