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