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