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