@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 846 lines 29.7 KB
Raw
1 import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
2 import { type ScopedThreadRef } from "@t3tools/contracts";
3 import { create } from "zustand";
4 import { createJSONStorage, persist } from "zustand/middleware";
5 import { resolveStorage } from "./lib/storage";
6 import {
7 DEFAULT_THREAD_TERMINAL_HEIGHT,
8 DEFAULT_THREAD_TERMINAL_ID,
9 MAX_TERMINALS_PER_GROUP,
10 type ThreadTerminalGroup,
11 } from "./types";
12
13 interface ThreadTerminalUiState {
14 terminalOpen: boolean;
15 terminalHeight: number;
16 terminalIds: string[];
17 activeTerminalId: string;
18 terminalGroups: ThreadTerminalGroup[];
19 activeTerminalGroupId: string;
20 }
21
22 const TERMINAL_UI_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
23
24 interface PersistedTerminalUiStateStoreState {
25 terminalUiStateByThreadKey?: Record<string, ThreadTerminalUiState>;
26 terminalStateByThreadKey?: Record<string, ThreadTerminalUiState>;
27 }
28
29 export function migratePersistedTerminalUiStateStoreState(
30 persistedState: unknown,
31 _version: number,
32 ): PersistedTerminalUiStateStoreState {
33 if (!persistedState || typeof persistedState !== "object") {
34 return { terminalUiStateByThreadKey: {} };
35 }
36
37 const candidate = persistedState as PersistedTerminalUiStateStoreState;
38 const persistedUiStateByThreadKey =
39 candidate.terminalUiStateByThreadKey ?? candidate.terminalStateByThreadKey ?? {};
40 const terminalUiStateByThreadKey = Object.fromEntries(
41 Object.entries(persistedUiStateByThreadKey).filter(([threadKey]) =>
42 parseScopedThreadKey(threadKey),
43 ),
44 );
45
46 return { terminalUiStateByThreadKey };
47 }
48
49 function createTerminalUiStateStorage() {
50 return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined);
51 }
52
53 function normalizeTerminalIds(terminalIds: string[]): string[] {
54 const normalizedIds: string[] = [];
55 const seen = new Set<string>();
56 for (const id of terminalIds) {
57 const trimmedId = id.trim();
58 if (trimmedId.length === 0 || seen.has(trimmedId)) continue;
59 seen.add(trimmedId);
60 normalizedIds.push(trimmedId);
61 }
62 return normalizedIds;
63 }
64
65 function fallbackGroupId(terminalId: string): string {
66 return `group-${terminalId}`;
67 }
68
69 function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
70 let candidate = baseId;
71 let index = 2;
72 while (usedGroupIds.has(candidate)) {
73 candidate = `${baseId}-${index}`;
74 index += 1;
75 }
76 usedGroupIds.add(candidate);
77 return candidate;
78 }
79
80 function findGroupIndexByTerminalId(
81 terminalGroups: ThreadTerminalGroup[],
82 terminalId: string,
83 ): number {
84 return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
85 }
86
87 function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
88 return normalizeTerminalIds(terminalIds);
89 }
90
91 function normalizeTerminalGroups(
92 terminalGroups: ThreadTerminalGroup[],
93 terminalIds: string[],
94 ): ThreadTerminalGroup[] {
95 if (terminalIds.length === 0) {
96 return [];
97 }
98
99 const validTerminalIdSet = new Set(terminalIds);
100 const assignedTerminalIds = new Set<string>();
101 const nextGroups: ThreadTerminalGroup[] = [];
102 const usedGroupIds = new Set<string>();
103
104 for (const group of terminalGroups) {
105 const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
106 if (!validTerminalIdSet.has(terminalId)) return false;
107 if (assignedTerminalIds.has(terminalId)) return false;
108 return true;
109 });
110 if (groupTerminalIds.length === 0) continue;
111 for (const terminalId of groupTerminalIds) {
112 assignedTerminalIds.add(terminalId);
113 }
114 const baseGroupId =
115 group.id.trim().length > 0
116 ? group.id.trim()
117 : fallbackGroupId(groupTerminalIds[0] ?? terminalIds[0] ?? "");
118 nextGroups.push({
119 id: assignUniqueGroupId(baseGroupId, usedGroupIds),
120 terminalIds: groupTerminalIds,
121 ...(group.splitDirection === "vertical" ? { splitDirection: "vertical" as const } : {}),
122 });
123 }
124
125 for (const terminalId of terminalIds) {
126 if (assignedTerminalIds.has(terminalId)) continue;
127 nextGroups.push({
128 id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
129 terminalIds: [terminalId],
130 });
131 }
132
133 return nextGroups;
134 }
135
136 function arraysEqual(a: string[], b: string[]): boolean {
137 if (a.length !== b.length) return false;
138 for (let index = 0; index < a.length; index += 1) {
139 if (a[index] !== b[index]) return false;
140 }
141 return true;
142 }
143
144 function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalGroup[]): boolean {
145 if (left.length !== right.length) return false;
146 for (let index = 0; index < left.length; index += 1) {
147 const leftGroup = left[index];
148 const rightGroup = right[index];
149 if (!leftGroup || !rightGroup) return false;
150 if (leftGroup.id !== rightGroup.id) return false;
151 if (
152 (leftGroup.splitDirection ?? "horizontal") !== (rightGroup.splitDirection ?? "horizontal")
153 ) {
154 return false;
155 }
156 if (!arraysEqual(leftGroup.terminalIds, rightGroup.terminalIds)) return false;
157 }
158 return true;
159 }
160
161 function threadTerminalUiStateEqual(
162 left: ThreadTerminalUiState,
163 right: ThreadTerminalUiState,
164 ): boolean {
165 return (
166 left.terminalOpen === right.terminalOpen &&
167 left.terminalHeight === right.terminalHeight &&
168 left.activeTerminalId === right.activeTerminalId &&
169 left.activeTerminalGroupId === right.activeTerminalGroupId &&
170 arraysEqual(left.terminalIds, right.terminalIds) &&
171 terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
172 );
173 }
174
175 const DEFAULT_THREAD_TERMINAL_UI_STATE: ThreadTerminalUiState = Object.freeze({
176 terminalOpen: false,
177 terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
178 terminalIds: [],
179 activeTerminalId: "",
180 terminalGroups: [],
181 activeTerminalGroupId: "",
182 });
183
184 function createDefaultThreadTerminalUiState(): ThreadTerminalUiState {
185 return {
186 ...DEFAULT_THREAD_TERMINAL_UI_STATE,
187 terminalIds: [...DEFAULT_THREAD_TERMINAL_UI_STATE.terminalIds],
188 terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_UI_STATE.terminalGroups),
189 };
190 }
191
192 function getDefaultThreadTerminalUiState(): ThreadTerminalUiState {
193 return DEFAULT_THREAD_TERMINAL_UI_STATE;
194 }
195
196 function normalizeThreadTerminalUiState(state: ThreadTerminalUiState): ThreadTerminalUiState {
197 const nextTerminalIds = normalizeTerminalIds(state.terminalIds);
198 const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
199 ? state.activeTerminalId
200 : (nextTerminalIds[0] ?? "");
201 const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
202 const activeGroupIdFromState = terminalGroups.some(
203 (group) => group.id === state.activeTerminalGroupId,
204 )
205 ? state.activeTerminalGroupId
206 : null;
207 const activeGroupIdFromTerminal =
208 terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
209
210 const normalized: ThreadTerminalUiState = {
211 terminalOpen: state.terminalOpen,
212 terminalHeight:
213 Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
214 ? state.terminalHeight
215 : DEFAULT_THREAD_TERMINAL_HEIGHT,
216 terminalIds: nextTerminalIds,
217 activeTerminalId,
218 terminalGroups,
219 activeTerminalGroupId:
220 activeGroupIdFromState ?? activeGroupIdFromTerminal ?? terminalGroups[0]?.id ?? "",
221 };
222 return threadTerminalUiStateEqual(state, normalized) ? state : normalized;
223 }
224
225 function isDefaultThreadTerminalUiState(state: ThreadTerminalUiState): boolean {
226 const normalized = normalizeThreadTerminalUiState(state);
227 return threadTerminalUiStateEqual(normalized, DEFAULT_THREAD_TERMINAL_UI_STATE);
228 }
229
230 function isValidTerminalId(terminalId: string): boolean {
231 return terminalId.trim().length > 0;
232 }
233
234 function terminalThreadKey(threadRef: ScopedThreadRef): string {
235 return scopedThreadKey(threadRef);
236 }
237
238 function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
239 return groups.map((group) => ({
240 id: group.id,
241 terminalIds: [...group.terminalIds],
242 ...(group.splitDirection === "vertical" ? { splitDirection: "vertical" as const } : {}),
243 }));
244 }
245
246 function upsertTerminalIntoGroups(
247 state: ThreadTerminalUiState,
248 terminalId: string,
249 mode: "split" | "new",
250 splitDirection: "horizontal" | "vertical" = "horizontal",
251 ): ThreadTerminalUiState {
252 const normalized = normalizeThreadTerminalUiState(state);
253 const effectiveMode: "split" | "new" = normalized.terminalIds.length === 0 ? "new" : mode;
254 if (!isValidTerminalId(terminalId)) {
255 return normalized;
256 }
257
258 const isNewTerminal = !normalized.terminalIds.includes(terminalId);
259 const terminalIds = isNewTerminal
260 ? [...normalized.terminalIds, terminalId]
261 : normalized.terminalIds;
262 const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
263
264 const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);
265 if (existingGroupIndex >= 0) {
266 terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
267 existingGroupIndex
268 ]!.terminalIds.filter((id) => id !== terminalId);
269 if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
270 terminalGroups.splice(existingGroupIndex, 1);
271 }
272 }
273
274 if (effectiveMode === "new") {
275 const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
276 const nextGroupId = assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds);
277 terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
278 return normalizeThreadTerminalUiState({
279 ...normalized,
280 terminalOpen: true,
281 terminalIds,
282 activeTerminalId: terminalId,
283 terminalGroups,
284 activeTerminalGroupId: nextGroupId,
285 });
286 }
287
288 let activeGroupIndex = terminalGroups.findIndex(
289 (group) => group.id === normalized.activeTerminalGroupId,
290 );
291 if (activeGroupIndex < 0) {
292 activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
293 }
294 if (activeGroupIndex < 0) {
295 const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
296 const nextGroupId = assignUniqueGroupId(
297 fallbackGroupId(normalized.activeTerminalId),
298 usedGroupIds,
299 );
300 terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
301 activeGroupIndex = terminalGroups.length - 1;
302 }
303
304 const destinationGroup = terminalGroups[activeGroupIndex];
305 if (!destinationGroup) {
306 return normalized;
307 }
308 const destinationTerminalIdSet = new Set(destinationGroup.terminalIds);
309
310 if (
311 isNewTerminal &&
312 !destinationTerminalIdSet.has(terminalId) &&
313 destinationGroup.terminalIds.length >= MAX_TERMINALS_PER_GROUP
314 ) {
315 return normalized;
316 }
317
318 if (!destinationTerminalIdSet.has(terminalId)) {
319 const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
320 if (anchorIndex >= 0) {
321 destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
322 } else {
323 destinationGroup.terminalIds.push(terminalId);
324 }
325 }
326 if (splitDirection === "vertical") {
327 destinationGroup.splitDirection = "vertical";
328 } else {
329 delete destinationGroup.splitDirection;
330 }
331
332 return normalizeThreadTerminalUiState({
333 ...normalized,
334 terminalOpen: true,
335 terminalIds,
336 activeTerminalId: terminalId,
337 terminalGroups,
338 activeTerminalGroupId: destinationGroup.id,
339 });
340 }
341
342 function setThreadTerminalOpen(state: ThreadTerminalUiState, open: boolean): ThreadTerminalUiState {
343 const normalized = normalizeThreadTerminalUiState(state);
344 if (open && normalized.terminalIds.length === 0) {
345 return upsertTerminalIntoGroups(normalized, DEFAULT_THREAD_TERMINAL_ID, "new");
346 }
347 if (normalized.terminalOpen === open) return normalized;
348 return { ...normalized, terminalOpen: open };
349 }
350
351 function setThreadTerminalHeight(
352 state: ThreadTerminalUiState,
353 height: number,
354 ): ThreadTerminalUiState {
355 const normalized = normalizeThreadTerminalUiState(state);
356 if (!Number.isFinite(height) || height <= 0 || normalized.terminalHeight === height) {
357 return normalized;
358 }
359 return { ...normalized, terminalHeight: height };
360 }
361
362 function splitThreadTerminal(
363 state: ThreadTerminalUiState,
364 terminalId: string,
365 direction: "horizontal" | "vertical" = "horizontal",
366 ): ThreadTerminalUiState {
367 return upsertTerminalIntoGroups(state, terminalId, "split", direction);
368 }
369
370 function newThreadTerminal(
371 state: ThreadTerminalUiState,
372 terminalId: string,
373 ): ThreadTerminalUiState {
374 return upsertTerminalIntoGroups(state, terminalId, "new");
375 }
376
377 function setThreadActiveTerminal(
378 state: ThreadTerminalUiState,
379 terminalId: string,
380 ): ThreadTerminalUiState {
381 const normalized = normalizeThreadTerminalUiState(state);
382 if (!normalized.terminalIds.includes(terminalId)) {
383 return normalized;
384 }
385 const activeTerminalGroupId =
386 normalized.terminalGroups.find((group) => group.terminalIds.includes(terminalId))?.id ??
387 normalized.activeTerminalGroupId;
388 if (
389 normalized.activeTerminalId === terminalId &&
390 normalized.activeTerminalGroupId === activeTerminalGroupId
391 ) {
392 return normalized;
393 }
394 return {
395 ...normalized,
396 activeTerminalId: terminalId,
397 activeTerminalGroupId,
398 };
399 }
400
401 function closeThreadTerminal(
402 state: ThreadTerminalUiState,
403 terminalId: string,
404 ): ThreadTerminalUiState {
405 const normalized = normalizeThreadTerminalUiState(state);
406 if (!normalized.terminalIds.includes(terminalId)) {
407 return normalized;
408 }
409
410 const remainingTerminalIds = normalized.terminalIds.filter((id) => id !== terminalId);
411 if (remainingTerminalIds.length === 0) {
412 return createDefaultThreadTerminalUiState();
413 }
414
415 const closedTerminalIndex = normalized.terminalIds.indexOf(terminalId);
416 const groupTerminalIds =
417 normalized.terminalGroups.find((group) => group.terminalIds.includes(terminalId))
418 ?.terminalIds ?? [];
419 const groupIndex = groupTerminalIds.indexOf(terminalId);
420 const nextActiveTerminalId =
421 normalized.activeTerminalId === terminalId
422 ? (groupTerminalIds[groupIndex + 1] ??
423 groupTerminalIds[groupIndex - 1] ??
424 remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
425 remainingTerminalIds[0] ??
426 "")
427 : normalized.activeTerminalId;
428
429 const terminalGroups: ThreadTerminalGroup[] = [];
430 for (const group of normalized.terminalGroups) {
431 const terminalIds = group.terminalIds.filter((id) => id !== terminalId);
432 if (terminalIds.length > 0) {
433 terminalGroups.push({ ...group, terminalIds });
434 }
435 }
436
437 const nextActiveTerminalGroupId =
438 terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
439 terminalGroups[0]?.id ??
440 fallbackGroupId(nextActiveTerminalId);
441
442 return normalizeThreadTerminalUiState({
443 terminalOpen: normalized.terminalOpen,
444 terminalHeight: normalized.terminalHeight,
445 terminalIds: remainingTerminalIds,
446 activeTerminalId: nextActiveTerminalId,
447 terminalGroups,
448 activeTerminalGroupId: nextActiveTerminalGroupId,
449 });
450 }
451
452 function reconcileThreadTerminalSessionIds(
453 state: ThreadTerminalUiState,
454 serverIds: string[],
455 previousServerIds: readonly string[],
456 ): ThreadTerminalUiState {
457 const normalized = normalizeThreadTerminalUiState(state);
458 const serverIdSet = new Set(serverIds);
459 const localIdSet = new Set(normalized.terminalIds);
460 const added = serverIds.filter((id) => !localIdSet.has(id));
461 let next =
462 added.length === 0
463 ? normalized
464 : normalizeThreadTerminalUiState({
465 ...normalized,
466 terminalIds: [...normalized.terminalIds, ...added],
467 });
468
469 for (const id of previousServerIds) {
470 if (id !== normalized.activeTerminalId && !serverIdSet.has(id)) {
471 next = closeThreadTerminal(next, id);
472 }
473 }
474 if (
475 !serverIdSet.has(normalized.activeTerminalId) &&
476 previousServerIds.includes(normalized.activeTerminalId)
477 ) {
478 next = closeThreadTerminal(next, normalized.activeTerminalId);
479 }
480 return next;
481 }
482
483 export function selectThreadTerminalUiState(
484 terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>,
485 threadRef: ScopedThreadRef | null | undefined,
486 ): ThreadTerminalUiState {
487 if (!threadRef || threadRef.threadId.length === 0) {
488 return getDefaultThreadTerminalUiState();
489 }
490 return (
491 terminalUiStateByThreadKey[terminalThreadKey(threadRef)] ?? getDefaultThreadTerminalUiState()
492 );
493 }
494
495 function updateTerminalUiStateByThreadKey(
496 terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>,
497 threadRef: ScopedThreadRef,
498 updater: (state: ThreadTerminalUiState) => ThreadTerminalUiState,
499 ): Record<string, ThreadTerminalUiState> {
500 if (threadRef.threadId.length === 0) {
501 return terminalUiStateByThreadKey;
502 }
503
504 const threadKey = terminalThreadKey(threadRef);
505 const current = selectThreadTerminalUiState(terminalUiStateByThreadKey, threadRef);
506 const next = updater(current);
507 if (next === current) {
508 return terminalUiStateByThreadKey;
509 }
510
511 if (isDefaultThreadTerminalUiState(next)) {
512 if (terminalUiStateByThreadKey[threadKey] === undefined) {
513 return terminalUiStateByThreadKey;
514 }
515 const { [threadKey]: _removed, ...rest } = terminalUiStateByThreadKey;
516 return rest;
517 }
518
519 return {
520 ...terminalUiStateByThreadKey,
521 [threadKey]: next,
522 };
523 }
524
525 function updateSuppressedTerminalId(
526 suppressedTerminalIdsByThreadKey: Record<string, string[]>,
527 threadRef: ScopedThreadRef,
528 terminalId: string,
529 suppressed: boolean,
530 ): Record<string, string[]> {
531 const normalizedTerminalId = terminalId.trim();
532 if (normalizedTerminalId.length === 0) {
533 return suppressedTerminalIdsByThreadKey;
534 }
535 const threadKey = terminalThreadKey(threadRef);
536 const currentIds = suppressedTerminalIdsByThreadKey[threadKey] ?? [];
537 const currentlySuppressed = currentIds.includes(normalizedTerminalId);
538 if (currentlySuppressed === suppressed) {
539 return suppressedTerminalIdsByThreadKey;
540 }
541 if (suppressed) {
542 return {
543 ...suppressedTerminalIdsByThreadKey,
544 [threadKey]: [...currentIds, normalizedTerminalId],
545 };
546 }
547
548 const remainingIds = currentIds.filter((id) => id !== normalizedTerminalId);
549 if (remainingIds.length > 0) {
550 return {
551 ...suppressedTerminalIdsByThreadKey,
552 [threadKey]: remainingIds,
553 };
554 }
555 return removeRecordEntry(suppressedTerminalIdsByThreadKey, threadKey);
556 }
557
558 function removeRecordEntry<T>(record: Record<string, T>, key: string): Record<string, T> {
559 if (record[key] === undefined) {
560 return record;
561 }
562 const { [key]: _removed, ...remaining } = record;
563 return remaining;
564 }
565
566 interface TerminalServerObservation {
567 readonly ids: string[];
568 readonly snapshotId: string | symbol | undefined;
569 }
570
571 function forgetObservedTerminalId(
572 serverObservationsByThreadKey: Record<string, TerminalServerObservation>,
573 threadKey: string,
574 terminalId: string,
575 ): Record<string, TerminalServerObservation> {
576 const observation = serverObservationsByThreadKey[threadKey];
577 if (!observation?.ids.includes(terminalId)) {
578 return serverObservationsByThreadKey;
579 }
580 const ids = observation.ids.filter((id) => id !== terminalId);
581 if (ids.length === 0) {
582 return removeRecordEntry(serverObservationsByThreadKey, threadKey);
583 }
584 return { ...serverObservationsByThreadKey, [threadKey]: { ...observation, ids } };
585 }
586
587 interface TerminalUiStateStoreState {
588 serverObservationsByThreadKey: Record<string, TerminalServerObservation>;
589 terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>;
590 suppressedTerminalIdsByThreadKey: Record<string, string[]>;
591 setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void;
592 setTerminalHeight: (threadRef: ScopedThreadRef, height: number) => void;
593 splitTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
594 splitTerminalVertical: (threadRef: ScopedThreadRef, terminalId: string) => void;
595 newTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
596 ensureTerminal: (
597 threadRef: ScopedThreadRef,
598 terminalId: string,
599 options?: { open?: boolean; active?: boolean },
600 ) => void;
601 setActiveTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
602 closeTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
603 reconcileTerminalIds: (
604 threadRef: ScopedThreadRef,
605 serverIds: string[],
606 snapshotId?: string | symbol,
607 ) => void;
608 clearTerminalUiState: (threadRef: ScopedThreadRef) => void;
609 removeTerminalUiState: (threadRef: ScopedThreadRef) => void;
610 removeOrphanedTerminalUiStates: (activeThreadKeys: Set<string>) => void;
611 }
612
613 export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
614 persist(
615 (set, get) => {
616 const removeTerminalUiState = (threadRef: ScopedThreadRef) =>
617 set((state) => {
618 const threadKey = terminalThreadKey(threadRef);
619 if (
620 state.terminalUiStateByThreadKey[threadKey] === undefined &&
621 state.suppressedTerminalIdsByThreadKey[threadKey] === undefined &&
622 state.serverObservationsByThreadKey[threadKey] === undefined
623 ) {
624 return state;
625 }
626 return {
627 terminalUiStateByThreadKey: removeRecordEntry(
628 state.terminalUiStateByThreadKey,
629 threadKey,
630 ),
631 suppressedTerminalIdsByThreadKey: removeRecordEntry(
632 state.suppressedTerminalIdsByThreadKey,
633 threadKey,
634 ),
635 serverObservationsByThreadKey: removeRecordEntry(
636 state.serverObservationsByThreadKey,
637 threadKey,
638 ),
639 };
640 });
641
642 const updateTerminal = (
643 threadRef: ScopedThreadRef,
644 updater: (state: ThreadTerminalUiState) => ThreadTerminalUiState,
645 suppression?: { terminalId: string; suppressed: boolean },
646 ) => {
647 set((state) => {
648 const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey(
649 state.terminalUiStateByThreadKey,
650 threadRef,
651 updater,
652 );
653 const nextSuppressedTerminalIdsByThreadKey = suppression
654 ? updateSuppressedTerminalId(
655 state.suppressedTerminalIdsByThreadKey,
656 threadRef,
657 suppression.terminalId,
658 suppression.suppressed,
659 )
660 : state.suppressedTerminalIdsByThreadKey;
661 // A listing from before this client placed the id is about an earlier terminal, so it
662 // must not make reconcile close the new one.
663 const nextServerObservationsByThreadKey =
664 suppression &&
665 !suppression.suppressed &&
666 !selectThreadTerminalUiState(
667 state.terminalUiStateByThreadKey,
668 threadRef,
669 ).terminalIds.includes(suppression.terminalId)
670 ? forgetObservedTerminalId(
671 state.serverObservationsByThreadKey,
672 terminalThreadKey(threadRef),
673 suppression.terminalId,
674 )
675 : state.serverObservationsByThreadKey;
676 if (
677 nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey &&
678 nextSuppressedTerminalIdsByThreadKey === state.suppressedTerminalIdsByThreadKey &&
679 nextServerObservationsByThreadKey === state.serverObservationsByThreadKey
680 ) {
681 return state;
682 }
683 return {
684 terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
685 suppressedTerminalIdsByThreadKey: nextSuppressedTerminalIdsByThreadKey,
686 serverObservationsByThreadKey: nextServerObservationsByThreadKey,
687 };
688 });
689 };
690
691 return {
692 terminalUiStateByThreadKey: {},
693 serverObservationsByThreadKey: {},
694 suppressedTerminalIdsByThreadKey: {},
695 setTerminalOpen: (threadRef, open) => {
696 const terminalState = selectThreadTerminalUiState(
697 get().terminalUiStateByThreadKey,
698 threadRef,
699 );
700 updateTerminal(
701 threadRef,
702 (state) => setThreadTerminalOpen(state, open),
703 open && terminalState.terminalIds.length === 0
704 ? { terminalId: DEFAULT_THREAD_TERMINAL_ID, suppressed: false }
705 : undefined,
706 );
707 },
708 setTerminalHeight: (threadRef, height) =>
709 updateTerminal(threadRef, (state) => setThreadTerminalHeight(state, height)),
710 splitTerminal: (threadRef, terminalId) =>
711 updateTerminal(threadRef, (state) => splitThreadTerminal(state, terminalId), {
712 terminalId,
713 suppressed: false,
714 }),
715 splitTerminalVertical: (threadRef, terminalId) =>
716 updateTerminal(threadRef, (state) => splitThreadTerminal(state, terminalId, "vertical"), {
717 terminalId,
718 suppressed: false,
719 }),
720 newTerminal: (threadRef, terminalId) =>
721 updateTerminal(threadRef, (state) => newThreadTerminal(state, terminalId), {
722 terminalId,
723 suppressed: false,
724 }),
725 ensureTerminal: (threadRef, terminalId, options) =>
726 updateTerminal(
727 threadRef,
728 (state) => {
729 let nextState = state;
730 if (!state.terminalIds.includes(terminalId)) {
731 nextState = newThreadTerminal(nextState, terminalId);
732 }
733 if (options?.active === false) {
734 nextState = {
735 ...nextState,
736 activeTerminalId: state.activeTerminalId,
737 activeTerminalGroupId: state.activeTerminalGroupId,
738 };
739 }
740 if (options?.active ?? true) {
741 nextState = setThreadActiveTerminal(nextState, terminalId);
742 }
743 if (options?.open) {
744 nextState = setThreadTerminalOpen(nextState, true);
745 }
746 return normalizeThreadTerminalUiState(nextState);
747 },
748 { terminalId, suppressed: false },
749 ),
750 setActiveTerminal: (threadRef, terminalId) =>
751 updateTerminal(threadRef, (state) => setThreadActiveTerminal(state, terminalId)),
752 closeTerminal: (threadRef, terminalId) =>
753 updateTerminal(threadRef, (state) => closeThreadTerminal(state, terminalId), {
754 terminalId,
755 suppressed: true,
756 }),
757 reconcileTerminalIds: (threadRef, serverIds, snapshotId) => {
758 if (threadRef.threadId.length === 0) return;
759 const threadKey = terminalThreadKey(threadRef);
760 const state = get();
761 const previous = state.serverObservationsByThreadKey[threadKey];
762 const suppressedIds = new Set(state.suppressedTerminalIdsByThreadKey[threadKey]);
763 const terminalUiStateByThreadKey = updateTerminalUiStateByThreadKey(
764 state.terminalUiStateByThreadKey,
765 threadRef,
766 (terminalState) =>
767 reconcileThreadTerminalSessionIds(
768 terminalState,
769 serverIds.filter((id) => !suppressedIds.has(id)),
770 // A different manager can start empty before old sessions reattach.
771 previous?.snapshotId === snapshotId ? (previous?.ids ?? []) : [],
772 ),
773 );
774 // Metadata is ordered by activity, which does not change which terminals were seen.
775 const observedIds = [...serverIds].sort();
776 let serverObservationsByThreadKey = state.serverObservationsByThreadKey;
777 if (observedIds.length === 0) {
778 serverObservationsByThreadKey = removeRecordEntry(
779 serverObservationsByThreadKey,
780 threadKey,
781 );
782 } else if (
783 !previous ||
784 previous.snapshotId !== snapshotId ||
785 !arraysEqual(previous.ids, observedIds)
786 ) {
787 serverObservationsByThreadKey = {
788 ...serverObservationsByThreadKey,
789 [threadKey]: { ids: observedIds, snapshotId },
790 };
791 }
792 if (
793 terminalUiStateByThreadKey !== state.terminalUiStateByThreadKey ||
794 serverObservationsByThreadKey !== state.serverObservationsByThreadKey
795 ) {
796 set({ terminalUiStateByThreadKey, serverObservationsByThreadKey });
797 }
798 },
799 clearTerminalUiState: removeTerminalUiState,
800 removeTerminalUiState,
801 removeOrphanedTerminalUiStates: (activeThreadKeys) =>
802 set((state) => {
803 const orphanedIds = new Set(
804 [
805 ...Object.keys(state.terminalUiStateByThreadKey),
806 ...Object.keys(state.suppressedTerminalIdsByThreadKey),
807 ...Object.keys(state.serverObservationsByThreadKey),
808 ].filter((key) => !activeThreadKeys.has(key)),
809 );
810 if (orphanedIds.size === 0) {
811 return state;
812 }
813 const nextTerminalUiStateByThreadKey = { ...state.terminalUiStateByThreadKey };
814 const nextSuppressedTerminalIdsByThreadKey = {
815 ...state.suppressedTerminalIdsByThreadKey,
816 };
817 const serverObservationsByThreadKey = { ...state.serverObservationsByThreadKey };
818 for (const id of orphanedIds) {
819 delete nextTerminalUiStateByThreadKey[id];
820 delete nextSuppressedTerminalIdsByThreadKey[id];
821 delete serverObservationsByThreadKey[id];
822 }
823 return {
824 terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
825 suppressedTerminalIdsByThreadKey: nextSuppressedTerminalIdsByThreadKey,
826 serverObservationsByThreadKey,
827 };
828 }),
829 };
830 },
831 {
832 name: TERMINAL_UI_STATE_STORAGE_KEY,
833 version: 4,
834 storage: createJSONStorage(createTerminalUiStateStorage),
835 migrate: migratePersistedTerminalUiStateStoreState,
836 partialize: (state) => ({
837 terminalUiStateByThreadKey: state.terminalUiStateByThreadKey,
838 serverObservationsByThreadKey: Object.fromEntries(
839 Object.entries(state.serverObservationsByThreadKey).filter(
840 ([, observation]) => typeof observation.snapshotId === "string",
841 ),
842 ),
843 }),
844 },
845 ),
846 );