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 { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
12import { resolveModelSlug } from "./model-logic";
13import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
14import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
15import {
16 type ChatAttachment,
17 DEFAULT_THREAD_TERMINAL_ID,
18 DEFAULT_RUNTIME_MODE,
19 MAX_THREAD_TERMINAL_COUNT,
20 type ProjectScript,
21 type Project,
22 type RuntimeMode,
23 type Thread,
24 type ThreadTerminalGroup,
25} from "./types";
26
27// ── Actions ──────────────────────────────────────────────────────────
28
29type Action =
30 | { type: "ADD_PROJECT"; project: Project }
31 | { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
32 | { type: "SYNC_PROJECTS"; projects: Project[] }
33 | { type: "TOGGLE_PROJECT"; projectId: string }
34 | { type: "DELETE_PROJECT"; projectId: string }
35 | { type: "ADD_THREAD"; thread: Thread }
36 | { type: "SET_ACTIVE_THREAD"; threadId: string }
37 | { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
38 | { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
39 | { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number }
40 | { type: "SPLIT_THREAD_TERMINAL"; threadId: string; terminalId: string }
41 | { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
42 | { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
43 | { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
44 | { type: "TOGGLE_DIFF" }
45 | {
46 type: "APPLY_EVENT";
47 event: ProviderEvent;
48 activeAssistantItemRef: { current: string | null };
49 }
50 | { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
51 | { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
52 | {
53 type: "PUSH_USER_MESSAGE";
54 threadId: string;
55 id: string;
56 text: string;
57 attachments?: ChatAttachment[];
58 }
59 | { type: "SET_ERROR"; threadId: string; error: string | null }
60 | { type: "SET_THREAD_TITLE"; threadId: string; title: string }
61 | { type: "SET_THREAD_MODEL"; threadId: string; model: string }
62 | {
63 type: "SET_THREAD_BRANCH";
64 threadId: string;
65 branch: string | null;
66 worktreePath: string | null;
67 }
68 | { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
69 | { type: "DELETE_THREAD"; threadId: string };
70
71// ── State ────────────────────────────────────────────────────────────
72
73export interface AppState {
74 projects: Project[];
75 threads: Thread[];
76 activeThreadId: string | null;
77 runtimeMode: RuntimeMode;
78 diffOpen: boolean;
79}
80
81const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
82const LEGACY_PERSISTED_STATE_KEYS = [
83 "t3code:renderer-state:v6",
84 "t3code:renderer-state:v5",
85 "t3code:renderer-state:v4",
86 "t3code:renderer-state:v3",
87 "codething:renderer-state:v4",
88 "codething:renderer-state:v3",
89 "codething:renderer-state:v2",
90 "codething:renderer-state:v1",
91] as const;
92
93const initialState: AppState = {
94 projects: [],
95 threads: [],
96 activeThreadId: null,
97 runtimeMode: DEFAULT_RUNTIME_MODE,
98 diffOpen: false,
99};
100
101// ── Helpers ──────────────────────────────────────────────────────────
102
103function readPersistedState(): AppState {
104 if (typeof window === "undefined") return initialState;
105
106 try {
107 const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
108 const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
109 const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
110 const raw = rawCurrent ?? rawLegacy;
111 if (!raw) return initialState;
112 const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
113 const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
114 if (!hydrated) return initialState;
115
116 const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
117 const activeThreadId = threads.some((thread) => thread.id === hydrated.activeThreadId)
118 ? hydrated.activeThreadId
119 : (threads[0]?.id ?? null);
120
121 return { ...hydrated, threads, activeThreadId, diffOpen: false };
122 } catch {
123 return initialState;
124 }
125}
126
127function persistState(state: AppState): void {
128 if (typeof window === "undefined") return;
129
130 try {
131 window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
132 for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
133 window.localStorage.removeItem(legacyKey);
134 }
135 } catch {
136 // Ignore quota/storage errors to avoid breaking chat UX.
137 }
138}
139
140function updateThread(
141 threads: Thread[],
142 threadId: string,
143 updater: (t: Thread) => Thread,
144): Thread[] {
145 return threads.map((t) => (t.id === threadId ? updater(t) : t));
146}
147
148function normalizeTerminalIds(terminalIds: string[]): string[] {
149 const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
150 const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
151 if (unique.length > 0) {
152 return unique;
153 }
154 return [DEFAULT_THREAD_TERMINAL_ID];
155}
156
157function normalizeRunningTerminalIds(
158 runningTerminalIds: string[],
159 terminalIds: string[],
160): string[] {
161 if (runningTerminalIds.length === 0) return [];
162 const validTerminalIdSet = new Set(terminalIds);
163 return [...new Set(runningTerminalIds)]
164 .map((id) => id.trim())
165 .filter((id) => id.length > 0 && validTerminalIdSet.has(id));
166}
167
168
169function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
170 return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
171}
172
173function fallbackGroupId(terminalId: string): string {
174 return `group-${terminalId}`;
175}
176
177function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
178 if (!usedGroupIds.has(groupId)) {
179 usedGroupIds.add(groupId);
180 return groupId;
181 }
182 let suffix = 2;
183 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
184 suffix += 1;
185 }
186 const uniqueGroupId = `${groupId}-${suffix}`;
187 usedGroupIds.add(uniqueGroupId);
188 return uniqueGroupId;
189}
190
191function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
192 const validTerminalIdSet = new Set(terminalIds);
193 const assignedTerminalIds = new Set<string>();
194 const usedGroupIds = new Set<string>();
195 const groups: ThreadTerminalGroup[] = [];
196
197 for (const group of thread.terminalGroups) {
198 const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
199 if (!validTerminalIdSet.has(terminalId)) return false;
200 if (assignedTerminalIds.has(terminalId)) return false;
201 return true;
202 });
203 if (groupTerminalIds.length === 0) continue;
204 for (const terminalId of groupTerminalIds) {
205 assignedTerminalIds.add(terminalId);
206 }
207 const baseGroupId =
208 group.id.trim().length > 0
209 ? group.id.trim()
210 : fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
211 groups.push({
212 id: assignUniqueGroupId(baseGroupId, usedGroupIds),
213 terminalIds: groupTerminalIds,
214 });
215 }
216
217 for (const terminalId of terminalIds) {
218 if (assignedTerminalIds.has(terminalId)) continue;
219 groups.push({
220 id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
221 terminalIds: [terminalId],
222 });
223 }
224
225 if (groups.length > 0) {
226 return groups;
227 }
228
229 return [
230 {
231 id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
232 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
233 },
234 ];
235}
236
237function findGroupIndexByTerminalId(
238 terminalGroups: ThreadTerminalGroup[],
239 terminalId: string,
240): number {
241 return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
242}
243
244function normalizeThreadTerminals(thread: Thread): Thread {
245 const terminalIds = normalizeTerminalIds(thread.terminalIds);
246 const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
247 ? thread.activeTerminalId
248 : (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
249 const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
250 const activeGroupIndexFromId = terminalGroups.findIndex(
251 (group) => group.id === thread.activeTerminalGroupId,
252 );
253 const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
254 const activeGroupIndex =
255 activeGroupIndexFromId >= 0
256 ? activeGroupIndexFromId
257 : activeGroupIndexFromTerminal >= 0
258 ? activeGroupIndexFromTerminal
259 : 0;
260 const activeTerminalGroupId =
261 terminalGroups[activeGroupIndex]?.id ??
262 terminalGroups[0]?.id ??
263 fallbackGroupId(activeTerminalId);
264
265 return {
266 ...thread,
267 terminalIds,
268 runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
269 activeTerminalId,
270 terminalGroups,
271 activeTerminalGroupId,
272 };
273}
274
275function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
276 if (!thread.terminalIds.includes(terminalId)) {
277 return thread;
278 }
279
280 const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
281 if (remainingTerminalIds.length === 0) {
282 const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
283 return normalizeThreadTerminals({
284 ...thread,
285 terminalOpen: false,
286 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
287 runningTerminalIds: [],
288 activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
289 terminalGroups: [
290 {
291 id: nextTerminalGroupId,
292 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
293 },
294 ],
295 activeTerminalGroupId: nextTerminalGroupId,
296 });
297 }
298
299 const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
300 const closedTerminalGroup = thread.terminalGroups.find((group) =>
301 group.terminalIds.includes(terminalId),
302 );
303 const closedTerminalGroupIndex = closedTerminalGroup
304 ? closedTerminalGroup.terminalIds.indexOf(terminalId)
305 : -1;
306 const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
307 (id) => id !== terminalId,
308 );
309 const nextActiveTerminalId =
310 thread.activeTerminalId === terminalId
311 ? (remainingTerminalsInClosedGroup[
312 Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
313 ] ??
314 remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
315 remainingTerminalIds[0] ??
316 DEFAULT_THREAD_TERMINAL_ID)
317 : thread.activeTerminalId;
318 const nextTerminalGroups = thread.terminalGroups
319 .map((group) => ({
320 ...group,
321 terminalIds: group.terminalIds.filter((id) => id !== terminalId),
322 }))
323 .filter((group) => group.terminalIds.length > 0);
324
325 return normalizeThreadTerminals({
326 ...thread,
327 terminalIds: remainingTerminalIds,
328 runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
329 activeTerminalId: nextActiveTerminalId,
330 terminalGroups: nextTerminalGroups,
331 });
332}
333
334function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
335 return threads.find((t) => t.session?.sessionId === sessionId);
336}
337
338function getEventTurnId(event: ProviderEvent): string | undefined {
339 if (event.turnId) return event.turnId;
340 const payload = asObject(event.payload);
341 const turn = asObject(payload?.turn);
342 return asString(turn?.id);
343}
344
345function getEventThreadId(event: ProviderEvent): string | undefined {
346 if (event.threadId) return event.threadId;
347 const payload = asObject(event.payload);
348 const payloadThread = asObject(payload?.thread);
349 const payloadMessage = asObject(payload?.msg);
350 return (
351 asString(payload?.threadId) ??
352 asString(payloadThread?.id) ??
353 asString(payload?.conversationId) ??
354 asString(payload?.thread_id) ??
355 asString(payloadMessage?.thread_id)
356 );
357}
358
359function shouldIgnoreForeignThreadEvent(thread: Thread, event: ProviderEvent): boolean {
360 const eventThreadId = getEventThreadId(event);
361 if (!eventThreadId) {
362 return false;
363 }
364
365 const expectedThreadId = thread.session?.threadId ?? thread.codexThreadId;
366 if (!expectedThreadId || eventThreadId === expectedThreadId) {
367 return false;
368 }
369
370 // During connect, accept a thread/started notification as an identity rebind.
371 if (event.method === "thread/started" && thread.session?.status === "connecting") {
372 return false;
373 }
374
375 return true;
376}
377
378function durationMs(startIso: string, endIso: string): number | undefined {
379 const start = Date.parse(startIso);
380 const end = Date.parse(endIso);
381 if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
382 return undefined;
383 }
384
385 return end - start;
386}
387
388function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread> {
389 if (event.method === "turn/started") {
390 return {
391 latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
392 latestTurnStartedAt: event.createdAt,
393 latestTurnCompletedAt: undefined,
394 latestTurnDurationMs: undefined,
395 };
396 }
397
398 if (event.method === "turn/completed") {
399 const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
400 const startedAt =
401 completedTurnId && completedTurnId === thread.latestTurnId
402 ? thread.latestTurnStartedAt
403 : undefined;
404 const elapsed =
405 startedAt && startedAt.length > 0 ? durationMs(startedAt, event.createdAt) : undefined;
406
407 return {
408 latestTurnId: completedTurnId ?? thread.latestTurnId,
409 latestTurnCompletedAt: event.createdAt,
410 latestTurnDurationMs: elapsed,
411 };
412 }
413
414 return {};
415}
416
417// ── Reducer ──────────────────────────────────────────────────────────
418
419export function reducer(state: AppState, action: Action): AppState {
420 switch (action.type) {
421 case "ADD_PROJECT":
422 if (state.projects.some((project) => project.cwd === action.project.cwd)) {
423 return state;
424 }
425 return {
426 ...state,
427 projects: [
428 ...state.projects,
429 {
430 ...action.project,
431 model: resolveModelSlug(action.project.model),
432 scripts: normalizeProjectScripts(action.project.scripts),
433 },
434 ],
435 };
436
437 case "SET_PROJECT_SCRIPTS":
438 return {
439 ...state,
440 projects: state.projects.map((project) =>
441 project.id === action.projectId
442 ? { ...project, scripts: normalizeProjectScripts(action.scripts) }
443 : project,
444 ),
445 };
446
447 case "SYNC_PROJECTS": {
448 const previousByCwd = new Map(
449 state.projects.map((project) => [project.cwd, project] as const),
450 );
451 const nextProjects = action.projects.map((project) => {
452 const previous = previousByCwd.get(project.cwd);
453 const scripts = normalizeProjectScripts(project.scripts);
454 return {
455 ...project,
456 model: resolveModelSlug(previous?.model ?? project.model),
457 expanded: previous?.expanded ?? project.expanded,
458 scripts,
459 };
460 });
461 const previousProjectById = new Map(
462 state.projects.map((project) => [project.id, project] as const),
463 );
464 const nextProjectIdByCwd = new Map(
465 nextProjects.map((project) => [project.cwd, project.id] as const),
466 );
467 const nextThreads = state.threads
468 .map((thread) => {
469 const previousProject = previousProjectById.get(thread.projectId);
470 if (!previousProject) return null;
471 const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
472 if (!mappedProjectId) return null;
473 return normalizeThreadTerminals({
474 ...thread,
475 projectId: mappedProjectId,
476 });
477 })
478 .filter((thread): thread is Thread => thread !== null);
479 const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
480 ? state.activeThreadId
481 : (nextThreads[0]?.id ?? null);
482
483 return {
484 ...state,
485 projects: nextProjects,
486 threads: nextThreads,
487 activeThreadId,
488 };
489 }
490
491 case "TOGGLE_PROJECT":
492 return {
493 ...state,
494 projects: state.projects.map((p) =>
495 p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
496 ),
497 };
498
499 case "DELETE_PROJECT": {
500 const projects = state.projects.filter((project) => project.id !== action.projectId);
501 if (projects.length === state.projects.length) {
502 return state;
503 }
504
505 const threads = state.threads.filter((thread) => thread.projectId !== action.projectId);
506 const activeThreadId = threads.some((thread) => thread.id === state.activeThreadId)
507 ? state.activeThreadId
508 : (threads[0]?.id ?? null);
509
510 return {
511 ...state,
512 projects,
513 threads,
514 activeThreadId,
515 };
516 }
517
518 case "ADD_THREAD": {
519 const nextThread = normalizeThreadTerminals({
520 ...action.thread,
521 model: resolveModelSlug(action.thread.model),
522 lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
523 });
524 return {
525 ...state,
526 threads: [...state.threads, nextThread],
527 activeThreadId: action.thread.id,
528 };
529 }
530
531 case "SET_ACTIVE_THREAD": {
532 const visitedAt = new Date().toISOString();
533 return {
534 ...state,
535 activeThreadId: action.threadId,
536 threads: updateThread(state.threads, action.threadId, (t) => ({
537 ...t,
538 lastVisitedAt: visitedAt,
539 })),
540 };
541 }
542
543 case "TOGGLE_THREAD_TERMINAL":
544 return {
545 ...state,
546 threads: updateThread(state.threads, action.threadId, (t) => ({
547 ...t,
548 terminalOpen: !t.terminalOpen,
549 })),
550 };
551
552 case "SET_THREAD_TERMINAL_OPEN":
553 return {
554 ...state,
555 threads: updateThread(state.threads, action.threadId, (t) => ({
556 ...t,
557 terminalOpen: action.open,
558 })),
559 };
560
561 case "SET_THREAD_TERMINAL_HEIGHT":
562 return {
563 ...state,
564 threads: updateThread(state.threads, action.threadId, (t) => ({
565 ...t,
566 terminalHeight: action.height,
567 })),
568 };
569
570 case "SPLIT_THREAD_TERMINAL":
571 return {
572 ...state,
573 threads: updateThread(state.threads, action.threadId, (thread) => {
574 const normalizedThread = normalizeThreadTerminals(thread);
575 const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
576 if (
577 isNewTerminal &&
578 normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
579 ) {
580 return normalizedThread;
581 }
582 const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
583 ? normalizedThread.terminalIds
584 : [...normalizedThread.terminalIds, action.terminalId];
585 const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
586 ...group,
587 terminalIds: [...group.terminalIds],
588 }));
589 let activeGroupIndex = terminalGroups.findIndex(
590 (group) => group.id === normalizedThread.activeTerminalGroupId,
591 );
592 if (activeGroupIndex < 0) {
593 activeGroupIndex = findGroupIndexByTerminalId(
594 terminalGroups,
595 normalizedThread.activeTerminalId,
596 );
597 }
598 if (activeGroupIndex < 0) {
599 terminalGroups.push({
600 id: fallbackGroupId(normalizedThread.activeTerminalId),
601 terminalIds: [normalizedThread.activeTerminalId],
602 });
603 activeGroupIndex = terminalGroups.length - 1;
604 }
605
606 const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
607 if (existingGroupIndex >= 0) {
608 terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
609 existingGroupIndex
610 ]!.terminalIds.filter((id) => id !== action.terminalId);
611 if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
612 terminalGroups.splice(existingGroupIndex, 1);
613 if (existingGroupIndex < activeGroupIndex) {
614 activeGroupIndex -= 1;
615 }
616 }
617 }
618
619 const destinationGroup = terminalGroups[activeGroupIndex];
620 if (!destinationGroup) {
621 return normalizedThread;
622 }
623 if (!destinationGroup.terminalIds.includes(action.terminalId)) {
624 const anchorIndex = destinationGroup.terminalIds.indexOf(
625 normalizedThread.activeTerminalId,
626 );
627 if (anchorIndex >= 0) {
628 destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
629 } else {
630 destinationGroup.terminalIds.push(action.terminalId);
631 }
632 }
633 return normalizeThreadTerminals({
634 ...normalizedThread,
635 terminalIds,
636 activeTerminalId: action.terminalId,
637 activeTerminalGroupId: destinationGroup.id,
638 terminalGroups,
639 });
640 }),
641 };
642
643 case "NEW_THREAD_TERMINAL":
644 return {
645 ...state,
646 threads: updateThread(state.threads, action.threadId, (thread) => {
647 const normalizedThread = normalizeThreadTerminals(thread);
648 const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
649 if (
650 isNewTerminal &&
651 normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
652 ) {
653 return normalizedThread;
654 }
655 const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
656 ? normalizedThread.terminalIds
657 : [...normalizedThread.terminalIds, action.terminalId];
658 const terminalGroups = normalizedThread.terminalGroups
659 .map((group) => ({
660 ...group,
661 terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
662 }))
663 .filter((group) => group.terminalIds.length > 0);
664 const nextGroupId = fallbackGroupId(action.terminalId);
665 terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
666
667 return normalizeThreadTerminals({
668 ...normalizedThread,
669 terminalIds,
670 activeTerminalId: action.terminalId,
671 activeTerminalGroupId: nextGroupId,
672 terminalGroups,
673 });
674 }),
675 };
676
677 case "SET_THREAD_ACTIVE_TERMINAL":
678 return {
679 ...state,
680 threads: updateThread(state.threads, action.threadId, (thread) => {
681 const normalizedThread = normalizeThreadTerminals(thread);
682 if (!normalizedThread.terminalIds.includes(action.terminalId)) {
683 return thread;
684 }
685 const nextActiveGroupIndex = findGroupIndexByTerminalId(
686 normalizedThread.terminalGroups,
687 action.terminalId,
688 );
689 const activeTerminalGroupId =
690 nextActiveGroupIndex >= 0
691 ? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
692 normalizedThread.activeTerminalGroupId)
693 : normalizedThread.activeTerminalGroupId;
694 return normalizeThreadTerminals({
695 ...normalizedThread,
696 activeTerminalId: action.terminalId,
697 activeTerminalGroupId,
698 });
699 }),
700 };
701
702 case "CLOSE_THREAD_TERMINAL":
703 return {
704 ...state,
705 threads: updateThread(state.threads, action.threadId, (thread) =>
706 closeThreadTerminal(thread, action.terminalId),
707 ),
708 };
709
710 case "TOGGLE_DIFF":
711 return { ...state, diffOpen: !state.diffOpen };
712
713 case "APPLY_TERMINAL_EVENT":
714 if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
715 return state;
716 }
717 return {
718 ...state,
719 threads: updateThread(state.threads, action.event.threadId, (thread) => {
720 const normalizedThread = normalizeThreadTerminals(thread);
721 const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
722 if (action.event.type === "started" || action.event.type === "restarted") {
723 runningTerminalIdSet.delete(action.event.terminalId);
724 } else if (action.event.type === "activity") {
725 if (action.event.hasRunningSubprocess) {
726 runningTerminalIdSet.add(action.event.terminalId);
727 } else {
728 runningTerminalIdSet.delete(action.event.terminalId);
729 }
730 } else if (action.event.type === "exited" || action.event.type === "error") {
731 runningTerminalIdSet.delete(action.event.terminalId);
732 }
733
734 return normalizeThreadTerminals({
735 ...normalizedThread,
736 runningTerminalIds: [...runningTerminalIdSet],
737 });
738 }),
739 };
740
741 case "APPLY_EVENT": {
742 const { event, activeAssistantItemRef } = action;
743 const target = findThreadBySessionId(state.threads, event.sessionId);
744 if (!target) return state;
745 if (shouldIgnoreForeignThreadEvent(target, event)) return state;
746
747 return {
748 ...state,
749 threads: updateThread(state.threads, target.id, (t) => ({
750 ...t,
751 ...(() => {
752 const eventThreadId = getEventThreadId(event);
753 const shouldRebindIdentity =
754 event.method === "thread/started" && t.session?.status === "connecting";
755 return {
756 codexThreadId: shouldRebindIdentity
757 ? (eventThreadId ?? t.codexThreadId)
758 : (t.codexThreadId ?? eventThreadId ?? null),
759 error: event.kind === "error" && event.message ? event.message : t.error,
760 };
761 })(),
762 session: t.session ? evolveSession(t.session, event) : t.session,
763 messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
764 events: [event, ...t.events],
765 ...updateTurnFields(t, event),
766 ...(event.method === "turn/completed" && t.id === state.activeThreadId
767 ? { lastVisitedAt: event.createdAt }
768 : {}),
769 })),
770 };
771 }
772
773 case "UPDATE_SESSION":
774 return {
775 ...state,
776 threads: updateThread(state.threads, action.threadId, (t) => ({
777 ...t,
778 session: action.session,
779 codexThreadId: action.session.threadId ?? t.codexThreadId,
780 events: [],
781 error: null,
782 latestTurnId: undefined,
783 latestTurnStartedAt: undefined,
784 latestTurnCompletedAt: undefined,
785 latestTurnDurationMs: undefined,
786 })),
787 };
788
789 case "PUSH_USER_MESSAGE":
790 return {
791 ...state,
792 threads: updateThread(state.threads, action.threadId, (t) => ({
793 ...t,
794 messages: [
795 ...t.messages,
796 {
797 id: action.id,
798 role: "user" as const,
799 text: action.text,
800 ...(action.attachments && action.attachments.length > 0
801 ? { attachments: action.attachments }
802 : {}),
803 createdAt: new Date().toISOString(),
804 streaming: false,
805 },
806 ],
807 })),
808 };
809
810 case "SET_ERROR":
811 return {
812 ...state,
813 threads: updateThread(state.threads, action.threadId, (t) => ({
814 ...t,
815 error: action.error,
816 })),
817 };
818
819 case "SET_THREAD_TITLE":
820 return {
821 ...state,
822 threads: updateThread(state.threads, action.threadId, (t) => ({
823 ...t,
824 title: action.title,
825 })),
826 };
827
828 case "SET_THREAD_MODEL":
829 return {
830 ...state,
831 threads: updateThread(state.threads, action.threadId, (t) => ({
832 ...t,
833 model: resolveModelSlug(action.model),
834 })),
835 };
836
837 case "SET_THREAD_BRANCH": {
838 return {
839 ...state,
840 threads: updateThread(state.threads, action.threadId, (t) => {
841 // When the effective cwd changes (worktreePath differs), the old
842 // session is no longer valid — clear it so ensureSession creates a
843 // new one with the correct cwd on the next message.
844 const cwdChanged = t.worktreePath !== action.worktreePath;
845 return {
846 ...t,
847 branch: action.branch,
848 worktreePath: action.worktreePath,
849 ...(cwdChanged ? { session: null } : {}),
850 };
851 }),
852 };
853 }
854
855 case "SET_RUNTIME_MODE":
856 return {
857 ...state,
858 runtimeMode: action.mode,
859 };
860
861 case "DELETE_THREAD": {
862 const threads = state.threads.filter((t) => t.id !== action.threadId);
863 const activeThreadId =
864 state.activeThreadId === action.threadId ? (threads[0]?.id ?? null) : state.activeThreadId;
865 return { ...state, threads, activeThreadId };
866 }
867
868 default:
869 return state;
870 }
871}
872
873// ── Context ──────────────────────────────────────────────────────────
874
875const StoreContext = createContext<{
876 state: AppState;
877 dispatch: Dispatch<Action>;
878}>({ state: initialState, dispatch: () => {} });
879
880export function StoreProvider({ children }: { children: ReactNode }) {
881 const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
882
883 useEffect(() => {
884 persistState(state);
885 }, [state]);
886
887 return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
888}
889
890export function useStore() {
891 return useContext(StoreContext);
892}