Open History to see the last commit
1import {
2 type Dispatch,
3 type ReactNode,
4 createContext,
5 createElement,
6 useContext,
7 useEffect,
8 useReducer,
9} from "react";
10
11import {
12 DEFAULT_MODEL,
13 ProviderSessionId,
14 ThreadId,
15 type OrchestrationReadModel,
16 type OrchestrationSessionStatus,
17 resolveModelSlug,
18} from "@t3tools/contracts";
19import {
20 DEFAULT_THREAD_TERMINAL_HEIGHT,
21 DEFAULT_THREAD_TERMINAL_ID,
22 DEFAULT_RUNTIME_MODE,
23 MAX_THREAD_TERMINAL_COUNT,
24 type ChatMessage,
25 type Project,
26 type RuntimeMode,
27 type Thread,
28 type ThreadTerminalGroup,
29} from "./types";
30
31// ── Actions ──────────────────────────────────────────────────────────
32
33type Action =
34 | { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
35 | { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
36 | { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
37 | { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
38 | {
39 type: "SET_THREAD_TERMINAL_ACTIVITY";
40 threadId: ThreadId;
41 terminalId: string;
42 hasRunningSubprocess: boolean;
43 }
44 | { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
45 | { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
46 | { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
47 | { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
48 | { type: "SPLIT_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
49 | { type: "NEW_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
50 | { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: ThreadId; terminalId: string }
51 | { type: "CLOSE_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
52 | { type: "SET_ERROR"; threadId: ThreadId; error: string | null }
53 | {
54 type: "SET_THREAD_BRANCH";
55 threadId: ThreadId;
56 branch: string | null;
57 worktreePath: string | null;
58 }
59 | { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
60
61// ── State ────────────────────────────────────────────────────────────
62
63export interface AppState {
64 projects: Project[];
65 threads: Thread[];
66 threadsHydrated: boolean;
67 runtimeMode: RuntimeMode;
68}
69
70const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
71const LEGACY_PERSISTED_STATE_KEYS = [
72 "t3code:renderer-state:v6",
73 "t3code:renderer-state:v5",
74 "t3code:renderer-state:v4",
75 "t3code:renderer-state:v3",
76 "codething:renderer-state:v4",
77 "codething:renderer-state:v3",
78 "codething:renderer-state:v2",
79 "codething:renderer-state:v1",
80] as const;
81
82const initialState: AppState = {
83 projects: [],
84 threads: [],
85 threadsHydrated: false,
86 runtimeMode: DEFAULT_RUNTIME_MODE,
87};
88const persistedExpandedProjectCwds = new Set<string>();
89
90// ── Helpers ──────────────────────────────────────────────────────────
91
92function readPersistedState(): AppState {
93 if (typeof window === "undefined") return initialState;
94
95 try {
96 const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
97 if (!raw) return initialState;
98 const parsed = JSON.parse(raw) as {
99 runtimeMode?: RuntimeMode;
100 expandedProjectCwds?: string[];
101 };
102 persistedExpandedProjectCwds.clear();
103 for (const cwd of parsed.expandedProjectCwds ?? []) {
104 if (typeof cwd === "string" && cwd.length > 0) {
105 persistedExpandedProjectCwds.add(cwd);
106 }
107 }
108 return {
109 ...initialState,
110 runtimeMode:
111 parsed.runtimeMode === "approval-required" || parsed.runtimeMode === "full-access"
112 ? parsed.runtimeMode
113 : DEFAULT_RUNTIME_MODE,
114 };
115 } catch {
116 return initialState;
117 }
118}
119
120function persistState(state: AppState): void {
121 if (typeof window === "undefined") return;
122
123 try {
124 window.localStorage.setItem(
125 PERSISTED_STATE_KEY,
126 JSON.stringify({
127 runtimeMode: state.runtimeMode,
128 expandedProjectCwds: state.projects
129 .filter((project) => project.expanded)
130 .map((project) => project.cwd),
131 }),
132 );
133 for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
134 window.localStorage.removeItem(legacyKey);
135 }
136 } catch {
137 // Ignore quota/storage errors to avoid breaking chat UX.
138 }
139}
140
141function updateThread(
142 threads: Thread[],
143 threadId: ThreadId,
144 updater: (t: Thread) => Thread,
145): Thread[] {
146 return threads.map((t) => (t.id === threadId ? updater(t) : t));
147}
148
149function mapProjectsFromReadModel(
150 incoming: OrchestrationReadModel["projects"],
151 previous: Project[],
152): Project[] {
153 return incoming.map((project) => {
154 const existing =
155 previous.find((entry) => entry.id === project.id) ??
156 previous.find((entry) => entry.cwd === project.workspaceRoot);
157 return {
158 id: project.id,
159 name: project.title,
160 cwd: project.workspaceRoot,
161 model: existing?.model ?? resolveModelSlug(project.defaultModel ?? DEFAULT_MODEL),
162 expanded:
163 existing?.expanded ??
164 (persistedExpandedProjectCwds.size > 0
165 ? persistedExpandedProjectCwds.has(project.workspaceRoot)
166 : true),
167 scripts: project.scripts.map((script) => ({ ...script })),
168 };
169 });
170}
171
172function toLegacySessionStatus(
173 status: OrchestrationSessionStatus,
174): "connecting" | "ready" | "running" | "error" | "closed" {
175 switch (status) {
176 case "starting":
177 return "connecting";
178 case "running":
179 return "running";
180 case "error":
181 return "error";
182 case "ready":
183 case "interrupted":
184 return "ready";
185 case "idle":
186 case "stopped":
187 return "closed";
188 }
189}
190
191function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
192 return providerName === "claudeCode" ? "claudeCode" : "codex";
193}
194
195function resolveWsHttpOrigin(): string {
196 if (typeof window === "undefined") {
197 return "";
198 }
199 const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
200 const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
201 const wsCandidate =
202 typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
203 ? bridgeWsUrl
204 : typeof envWsUrl === "string" && envWsUrl.length > 0
205 ? envWsUrl
206 : null;
207 if (!wsCandidate) {
208 return window.location.origin;
209 }
210
211 try {
212 const wsUrl = new URL(wsCandidate);
213 const protocol =
214 wsUrl.protocol === "wss:"
215 ? "https:"
216 : wsUrl.protocol === "ws:"
217 ? "http:"
218 : wsUrl.protocol;
219 return `${protocol}//${wsUrl.host}`;
220 } catch {
221 return window.location.origin;
222 }
223}
224
225function toAttachmentPreviewUrl(rawUrl: string): string {
226 if (rawUrl.startsWith("/")) {
227 return `${resolveWsHttpOrigin()}${rawUrl}`;
228 }
229 return rawUrl;
230}
231
232function normalizeTerminalIds(terminalIds: string[]): string[] {
233 const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
234 const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
235 if (unique.length > 0) {
236 return unique;
237 }
238 return [DEFAULT_THREAD_TERMINAL_ID];
239}
240
241function normalizeRunningTerminalIds(
242 runningTerminalIds: string[],
243 terminalIds: string[],
244): string[] {
245 if (runningTerminalIds.length === 0) return [];
246 const validTerminalIdSet = new Set(terminalIds);
247 return [...new Set(runningTerminalIds)]
248 .map((id) => id.trim())
249 .filter((id) => id.length > 0 && validTerminalIdSet.has(id));
250}
251
252function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
253 return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
254}
255
256function fallbackGroupId(terminalId: string): string {
257 return `group-${terminalId}`;
258}
259
260function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
261 if (!usedGroupIds.has(groupId)) {
262 usedGroupIds.add(groupId);
263 return groupId;
264 }
265 let suffix = 2;
266 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
267 suffix += 1;
268 }
269 const uniqueGroupId = `${groupId}-${suffix}`;
270 usedGroupIds.add(uniqueGroupId);
271 return uniqueGroupId;
272}
273
274function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
275 const validTerminalIdSet = new Set(terminalIds);
276 const assignedTerminalIds = new Set<string>();
277 const usedGroupIds = new Set<string>();
278 const groups: ThreadTerminalGroup[] = [];
279
280 for (const group of thread.terminalGroups) {
281 const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
282 if (!validTerminalIdSet.has(terminalId)) return false;
283 if (assignedTerminalIds.has(terminalId)) return false;
284 return true;
285 });
286 if (groupTerminalIds.length === 0) continue;
287 for (const terminalId of groupTerminalIds) {
288 assignedTerminalIds.add(terminalId);
289 }
290 const baseGroupId =
291 group.id.trim().length > 0
292 ? group.id.trim()
293 : fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
294 groups.push({
295 id: assignUniqueGroupId(baseGroupId, usedGroupIds),
296 terminalIds: groupTerminalIds,
297 });
298 }
299
300 for (const terminalId of terminalIds) {
301 if (assignedTerminalIds.has(terminalId)) continue;
302 groups.push({
303 id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
304 terminalIds: [terminalId],
305 });
306 }
307
308 if (groups.length > 0) {
309 return groups;
310 }
311
312 return [
313 {
314 id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
315 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
316 },
317 ];
318}
319
320function findGroupIndexByTerminalId(
321 terminalGroups: ThreadTerminalGroup[],
322 terminalId: string,
323): number {
324 return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
325}
326
327function normalizeThreadTerminals(thread: Thread): Thread {
328 const terminalIds = normalizeTerminalIds(thread.terminalIds);
329 const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
330 ? thread.activeTerminalId
331 : (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
332 const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
333 const activeGroupIndexFromId = terminalGroups.findIndex(
334 (group) => group.id === thread.activeTerminalGroupId,
335 );
336 const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
337 const activeGroupIndex =
338 activeGroupIndexFromId >= 0
339 ? activeGroupIndexFromId
340 : activeGroupIndexFromTerminal >= 0
341 ? activeGroupIndexFromTerminal
342 : 0;
343 const activeTerminalGroupId =
344 terminalGroups[activeGroupIndex]?.id ??
345 terminalGroups[0]?.id ??
346 fallbackGroupId(activeTerminalId);
347
348 return {
349 ...thread,
350 terminalIds,
351 runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
352 activeTerminalId,
353 terminalGroups,
354 activeTerminalGroupId,
355 };
356}
357
358function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
359 if (!thread.terminalIds.includes(terminalId)) {
360 return thread;
361 }
362
363 const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
364 if (remainingTerminalIds.length === 0) {
365 const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
366 return normalizeThreadTerminals({
367 ...thread,
368 terminalOpen: false,
369 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
370 runningTerminalIds: [],
371 activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
372 terminalGroups: [
373 {
374 id: nextTerminalGroupId,
375 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
376 },
377 ],
378 activeTerminalGroupId: nextTerminalGroupId,
379 });
380 }
381
382 const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
383 const closedTerminalGroup = thread.terminalGroups.find((group) =>
384 group.terminalIds.includes(terminalId),
385 );
386 const closedTerminalGroupIndex = closedTerminalGroup
387 ? closedTerminalGroup.terminalIds.indexOf(terminalId)
388 : -1;
389 const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
390 (id) => id !== terminalId,
391 );
392 const nextActiveTerminalId =
393 thread.activeTerminalId === terminalId
394 ? (remainingTerminalsInClosedGroup[
395 Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
396 ] ??
397 remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
398 remainingTerminalIds[0] ??
399 DEFAULT_THREAD_TERMINAL_ID)
400 : thread.activeTerminalId;
401 const nextTerminalGroups = thread.terminalGroups
402 .map((group) => ({
403 ...group,
404 terminalIds: group.terminalIds.filter((id) => id !== terminalId),
405 }))
406 .filter((group) => group.terminalIds.length > 0);
407
408 return normalizeThreadTerminals({
409 ...thread,
410 terminalIds: remainingTerminalIds,
411 runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
412 activeTerminalId: nextActiveTerminalId,
413 terminalGroups: nextTerminalGroups,
414 });
415}
416
417function setThreadTerminalActivity(
418 thread: Thread,
419 terminalId: string,
420 hasRunningSubprocess: boolean,
421): Thread {
422 const normalizedThread = normalizeThreadTerminals(thread);
423 if (!normalizedThread.terminalIds.includes(terminalId)) {
424 return normalizedThread;
425 }
426 const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
427 if (hasRunningSubprocess) {
428 runningTerminalIds.add(terminalId);
429 } else {
430 runningTerminalIds.delete(terminalId);
431 }
432 return normalizeThreadTerminals({
433 ...normalizedThread,
434 runningTerminalIds: [...runningTerminalIds],
435 });
436}
437
438// ── Reducer ──────────────────────────────────────────────────────────
439
440export function reducer(state: AppState, action: Action): AppState {
441 switch (action.type) {
442 case "SYNC_SERVER_READ_MODEL": {
443 const projects = mapProjectsFromReadModel(
444 action.readModel.projects.filter((project) => project.deletedAt === null),
445 state.projects,
446 );
447 const existingThreadById = new Map(
448 state.threads.map((thread) => [thread.id, thread] as const),
449 );
450 const threads = action.readModel.threads
451 .filter((thread) => thread.deletedAt === null)
452 .map((thread) => {
453 const existing = existingThreadById.get(thread.id);
454
455 return normalizeThreadTerminals({
456 id: thread.id,
457 codexThreadId: thread.session?.providerThreadId ?? null,
458 projectId: thread.projectId,
459 title: thread.title,
460 model: resolveModelSlug(thread.model),
461 terminalOpen: existing?.terminalOpen ?? false,
462 terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
463 terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
464 runningTerminalIds: existing?.runningTerminalIds ?? [],
465 activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
466 terminalGroups: existing?.terminalGroups ?? [
467 {
468 id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
469 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
470 },
471 ],
472 activeTerminalGroupId:
473 existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
474 session: thread.session
475 ? {
476 sessionId:
477 thread.session.providerSessionId ??
478 ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
479 provider: toLegacyProvider(thread.session.providerName),
480 status: toLegacySessionStatus(thread.session.status),
481 orchestrationStatus: thread.session.status,
482 threadId: thread.session.providerThreadId,
483 activeTurnId: thread.session.activeTurnId ?? undefined,
484 createdAt: thread.session.updatedAt,
485 updatedAt: thread.session.updatedAt,
486 ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
487 }
488 : null,
489 messages: thread.messages.map((message) => {
490 const attachments = message.attachments?.map((attachment, index) => ({
491 type: "image" as const,
492 id: `${message.id}:${index}`,
493 name: attachment.name,
494 mimeType: attachment.mimeType,
495 sizeBytes: attachment.sizeBytes,
496 previewUrl: toAttachmentPreviewUrl(attachment.dataUrl),
497 }));
498 const normalizedMessage: ChatMessage = {
499 id: message.id,
500 role: message.role,
501 text: message.text,
502 createdAt: message.createdAt,
503 streaming: message.streaming,
504 ...(message.streaming ? {} : { completedAt: message.updatedAt }),
505 ...(attachments && attachments.length > 0 ? { attachments } : {}),
506 };
507 return normalizedMessage;
508 }),
509 error: thread.session?.lastError ?? null,
510 createdAt: thread.createdAt,
511 latestTurn: thread.latestTurn,
512 lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
513 branch: thread.branch,
514 worktreePath: thread.worktreePath,
515 turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
516 turnId: checkpoint.turnId,
517 completedAt: checkpoint.completedAt,
518 status: checkpoint.status,
519 assistantMessageId: checkpoint.assistantMessageId ?? undefined,
520 checkpointTurnCount: checkpoint.checkpointTurnCount,
521 checkpointRef: checkpoint.checkpointRef,
522 files: checkpoint.files.map((file) => ({ ...file })),
523 })),
524 activities: thread.activities.map((activity) => ({ ...activity })),
525 });
526 });
527 return {
528 ...state,
529 projects,
530 threads,
531 threadsHydrated: true,
532 };
533 }
534
535 case "MARK_THREAD_VISITED": {
536 const visitedAt = action.visitedAt ?? new Date().toISOString();
537 const visitedAtMs = Date.parse(visitedAt);
538 return {
539 ...state,
540 threads: updateThread(state.threads, action.threadId, (thread) => {
541 const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
542 if (
543 Number.isFinite(previousVisitedAtMs) &&
544 Number.isFinite(visitedAtMs) &&
545 previousVisitedAtMs >= visitedAtMs
546 ) {
547 return thread;
548 }
549 return {
550 ...thread,
551 lastVisitedAt: visitedAt,
552 };
553 }),
554 };
555 }
556
557 case "MARK_THREAD_UNREAD": {
558 return {
559 ...state,
560 threads: updateThread(state.threads, action.threadId, (thread) => {
561 if (!thread.latestTurn?.completedAt) {
562 return thread;
563 }
564 const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
565 if (Number.isNaN(latestTurnCompletedAtMs)) {
566 return thread;
567 }
568 const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
569 if (thread.lastVisitedAt === unreadVisitedAt) {
570 return thread;
571 }
572 return {
573 ...thread,
574 lastVisitedAt: unreadVisitedAt,
575 };
576 }),
577 };
578 }
579
580 case "TOGGLE_PROJECT":
581 return {
582 ...state,
583 projects: state.projects.map((p) =>
584 p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
585 ),
586 };
587
588 case "SET_THREAD_TERMINAL_ACTIVITY":
589 return {
590 ...state,
591 threads: updateThread(state.threads, action.threadId, (thread) =>
592 setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
593 ),
594 };
595
596 case "SET_PROJECT_EXPANDED":
597 return {
598 ...state,
599 projects: state.projects.map((p) =>
600 p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
601 ),
602 };
603
604 case "TOGGLE_THREAD_TERMINAL":
605 return {
606 ...state,
607 threads: updateThread(state.threads, action.threadId, (t) => ({
608 ...t,
609 terminalOpen: !t.terminalOpen,
610 })),
611 };
612
613 case "SET_THREAD_TERMINAL_OPEN":
614 return {
615 ...state,
616 threads: updateThread(state.threads, action.threadId, (t) => ({
617 ...t,
618 terminalOpen: action.open,
619 })),
620 };
621
622 case "SET_THREAD_TERMINAL_HEIGHT":
623 return {
624 ...state,
625 threads: updateThread(state.threads, action.threadId, (t) => ({
626 ...t,
627 terminalHeight: action.height,
628 })),
629 };
630
631 case "SPLIT_THREAD_TERMINAL":
632 return {
633 ...state,
634 threads: updateThread(state.threads, action.threadId, (thread) => {
635 const normalizedThread = normalizeThreadTerminals(thread);
636 const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
637 if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
638 return normalizedThread;
639 }
640 const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
641 ? normalizedThread.terminalIds
642 : [...normalizedThread.terminalIds, action.terminalId];
643 const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
644 ...group,
645 terminalIds: [...group.terminalIds],
646 }));
647 let activeGroupIndex = terminalGroups.findIndex(
648 (group) => group.id === normalizedThread.activeTerminalGroupId,
649 );
650 if (activeGroupIndex < 0) {
651 activeGroupIndex = findGroupIndexByTerminalId(
652 terminalGroups,
653 normalizedThread.activeTerminalId,
654 );
655 }
656 if (activeGroupIndex < 0) {
657 terminalGroups.push({
658 id: fallbackGroupId(normalizedThread.activeTerminalId),
659 terminalIds: [normalizedThread.activeTerminalId],
660 });
661 activeGroupIndex = terminalGroups.length - 1;
662 }
663
664 const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
665 if (existingGroupIndex >= 0) {
666 terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
667 existingGroupIndex
668 ]!.terminalIds.filter((id) => id !== action.terminalId);
669 if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
670 terminalGroups.splice(existingGroupIndex, 1);
671 if (existingGroupIndex < activeGroupIndex) {
672 activeGroupIndex -= 1;
673 }
674 }
675 }
676
677 const destinationGroup = terminalGroups[activeGroupIndex];
678 if (!destinationGroup) {
679 return normalizedThread;
680 }
681 if (!destinationGroup.terminalIds.includes(action.terminalId)) {
682 const anchorIndex = destinationGroup.terminalIds.indexOf(
683 normalizedThread.activeTerminalId,
684 );
685 if (anchorIndex >= 0) {
686 destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
687 } else {
688 destinationGroup.terminalIds.push(action.terminalId);
689 }
690 }
691 return normalizeThreadTerminals({
692 ...normalizedThread,
693 terminalIds,
694 activeTerminalId: action.terminalId,
695 activeTerminalGroupId: destinationGroup.id,
696 terminalGroups,
697 });
698 }),
699 };
700
701 case "NEW_THREAD_TERMINAL":
702 return {
703 ...state,
704 threads: updateThread(state.threads, action.threadId, (thread) => {
705 const normalizedThread = normalizeThreadTerminals(thread);
706 const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
707 if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
708 return normalizedThread;
709 }
710 const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
711 ? normalizedThread.terminalIds
712 : [...normalizedThread.terminalIds, action.terminalId];
713 const terminalGroups = normalizedThread.terminalGroups
714 .map((group) => ({
715 ...group,
716 terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
717 }))
718 .filter((group) => group.terminalIds.length > 0);
719 const nextGroupId = fallbackGroupId(action.terminalId);
720 terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
721
722 return normalizeThreadTerminals({
723 ...normalizedThread,
724 terminalIds,
725 activeTerminalId: action.terminalId,
726 activeTerminalGroupId: nextGroupId,
727 terminalGroups,
728 });
729 }),
730 };
731
732 case "SET_THREAD_ACTIVE_TERMINAL":
733 return {
734 ...state,
735 threads: updateThread(state.threads, action.threadId, (thread) => {
736 const normalizedThread = normalizeThreadTerminals(thread);
737 if (!normalizedThread.terminalIds.includes(action.terminalId)) {
738 return thread;
739 }
740 const nextActiveGroupIndex = findGroupIndexByTerminalId(
741 normalizedThread.terminalGroups,
742 action.terminalId,
743 );
744 const activeTerminalGroupId =
745 nextActiveGroupIndex >= 0
746 ? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
747 normalizedThread.activeTerminalGroupId)
748 : normalizedThread.activeTerminalGroupId;
749 return normalizeThreadTerminals({
750 ...normalizedThread,
751 activeTerminalId: action.terminalId,
752 activeTerminalGroupId,
753 });
754 }),
755 };
756
757 case "CLOSE_THREAD_TERMINAL":
758 return {
759 ...state,
760 threads: updateThread(state.threads, action.threadId, (thread) =>
761 closeThreadTerminal(thread, action.terminalId),
762 ),
763 };
764
765 case "SET_ERROR":
766 return {
767 ...state,
768 threads: updateThread(state.threads, action.threadId, (t) => ({
769 ...t,
770 error: action.error,
771 })),
772 };
773
774 case "SET_THREAD_BRANCH": {
775 return {
776 ...state,
777 threads: updateThread(state.threads, action.threadId, (t) => {
778 // When the effective cwd changes (worktreePath differs), the old
779 // session is no longer valid — clear it so ensureSession creates a
780 // new one with the correct cwd on the next message.
781 const cwdChanged = t.worktreePath !== action.worktreePath;
782 return {
783 ...t,
784 branch: action.branch,
785 worktreePath: action.worktreePath,
786 ...(cwdChanged ? { session: null } : {}),
787 };
788 }),
789 };
790 }
791
792 case "SET_RUNTIME_MODE":
793 return {
794 ...state,
795 runtimeMode: action.mode,
796 };
797
798 default:
799 return state;
800 }
801}
802
803// ── Context ──────────────────────────────────────────────────────────
804
805const StoreContext = createContext<{
806 state: AppState;
807 dispatch: Dispatch<Action>;
808}>({ state: initialState, dispatch: () => {} });
809
810export function StoreProvider({ children }: { children: ReactNode }) {
811 const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
812
813 useEffect(() => {
814 persistState(state);
815 }, [state]);
816
817 return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
818}
819
820export function useStore() {
821 return useContext(StoreContext);
822}