Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

store.ts

876 lines29.1 KB

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