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