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

store.ts

826 lines27.6 KB

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;
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 }
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 }
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));
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 });
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 }
190​
191function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
192 return providerName === "claudeCode" ? "claudeCode" : "codex";
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 }
224​
225function toAttachmentPreviewUrl(rawUrl: string): string {
226 if (rawUrl.startsWith("/")) {
227 return `${resolveWsHttpOrigin()}${rawUrl}`;
228 }
229 return rawUrl;
231​
232function attachmentPreviewRoutePath(attachmentId: string): string {
233 return `/attachments/${encodeURIComponent(attachmentId)}`;
235​
236function normalizeTerminalIds(terminalIds: string[]): string[] {
237 const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
238 const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
239 if (unique.length > 0) {
240 return unique;
241 }
242 return [DEFAULT_THREAD_TERMINAL_ID];
244​
245function normalizeRunningTerminalIds(
246 runningTerminalIds: string[],
247 terminalIds: string[],
248): string[] {
249 if (runningTerminalIds.length === 0) return [];
250 const validTerminalIdSet = new Set(terminalIds);
251 return [...new Set(runningTerminalIds)]
252 .map((id) => id.trim())
253 .filter((id) => id.length > 0 && validTerminalIdSet.has(id));
255​
256function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
257 return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
259​
260function fallbackGroupId(terminalId: string): string {
261 return `group-${terminalId}`;
263​
264function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
265 if (!usedGroupIds.has(groupId)) {
266 usedGroupIds.add(groupId);
267 return groupId;
268 }
269 let suffix = 2;
270 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
271 suffix += 1;
272 }
273 const uniqueGroupId = `${groupId}-${suffix}`;
274 usedGroupIds.add(uniqueGroupId);
275 return uniqueGroupId;
277​
278function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
279 const validTerminalIdSet = new Set(terminalIds);
280 const assignedTerminalIds = new Set<string>();
281 const usedGroupIds = new Set<string>();
282 const groups: ThreadTerminalGroup[] = [];
283​
284 for (const group of thread.terminalGroups) {
285 const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
286 if (!validTerminalIdSet.has(terminalId)) return false;
287 if (assignedTerminalIds.has(terminalId)) return false;
288 return true;
289 });
290 if (groupTerminalIds.length === 0) continue;
291 for (const terminalId of groupTerminalIds) {
292 assignedTerminalIds.add(terminalId);
293 }
294 const baseGroupId =
295 group.id.trim().length > 0
296 ? group.id.trim()
297 : fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
298 groups.push({
299 id: assignUniqueGroupId(baseGroupId, usedGroupIds),
300 terminalIds: groupTerminalIds,
301 });
302 }
303​
304 for (const terminalId of terminalIds) {
305 if (assignedTerminalIds.has(terminalId)) continue;
306 groups.push({
307 id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
308 terminalIds: [terminalId],
309 });
310 }
311​
312 if (groups.length > 0) {
313 return groups;
314 }
315​
316 return [
317 {
318 id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
319 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
320 },
321 ];
323​
324function findGroupIndexByTerminalId(
325 terminalGroups: ThreadTerminalGroup[],
326 terminalId: string,
327): number {
328 return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
330​
331function normalizeThreadTerminals(thread: Thread): Thread {
332 const terminalIds = normalizeTerminalIds(thread.terminalIds);
333 const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
334 ? thread.activeTerminalId
335 : (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
336 const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
337 const activeGroupIndexFromId = terminalGroups.findIndex(
338 (group) => group.id === thread.activeTerminalGroupId,
339 );
340 const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
341 const activeGroupIndex =
342 activeGroupIndexFromId >= 0
343 ? activeGroupIndexFromId
344 : activeGroupIndexFromTerminal >= 0
345 ? activeGroupIndexFromTerminal
346 : 0;
347 const activeTerminalGroupId =
348 terminalGroups[activeGroupIndex]?.id ??
349 terminalGroups[0]?.id ??
350 fallbackGroupId(activeTerminalId);
351​
352 return {
353 ...thread,
354 terminalIds,
355 runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
356 activeTerminalId,
357 terminalGroups,
358 activeTerminalGroupId,
359 };
361​
362function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
363 if (!thread.terminalIds.includes(terminalId)) {
364 return thread;
365 }
366​
367 const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
368 if (remainingTerminalIds.length === 0) {
369 const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
370 return normalizeThreadTerminals({
371 ...thread,
372 terminalOpen: false,
373 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
374 runningTerminalIds: [],
375 activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
376 terminalGroups: [
377 {
378 id: nextTerminalGroupId,
379 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
380 },
381 ],
382 activeTerminalGroupId: nextTerminalGroupId,
383 });
384 }
385​
386 const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
387 const closedTerminalGroup = thread.terminalGroups.find((group) =>
388 group.terminalIds.includes(terminalId),
389 );
390 const closedTerminalGroupIndex = closedTerminalGroup
391 ? closedTerminalGroup.terminalIds.indexOf(terminalId)
392 : -1;
393 const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
394 (id) => id !== terminalId,
395 );
396 const nextActiveTerminalId =
397 thread.activeTerminalId === terminalId
398 ? (remainingTerminalsInClosedGroup[
399 Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
400 ] ??
401 remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
402 remainingTerminalIds[0] ??
403 DEFAULT_THREAD_TERMINAL_ID)
404 : thread.activeTerminalId;
405 const nextTerminalGroups = thread.terminalGroups
406 .map((group) => ({
407 ...group,
408 terminalIds: group.terminalIds.filter((id) => id !== terminalId),
409 }))
410 .filter((group) => group.terminalIds.length > 0);
411​
412 return normalizeThreadTerminals({
413 ...thread,
414 terminalIds: remainingTerminalIds,
415 runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
416 activeTerminalId: nextActiveTerminalId,
417 terminalGroups: nextTerminalGroups,
418 });
420​
421function setThreadTerminalActivity(
422 thread: Thread,
423 terminalId: string,
424 hasRunningSubprocess: boolean,
425): Thread {
426 const normalizedThread = normalizeThreadTerminals(thread);
427 if (!normalizedThread.terminalIds.includes(terminalId)) {
428 return normalizedThread;
429 }
430 const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
431 if (hasRunningSubprocess) {
432 runningTerminalIds.add(terminalId);
433 } else {
434 runningTerminalIds.delete(terminalId);
435 }
436 return normalizeThreadTerminals({
437 ...normalizedThread,
438 runningTerminalIds: [...runningTerminalIds],
439 });
441​
442// ── Reducer ──────────────────────────────────────────────────────────
443​
444export function reducer(state: AppState, action: Action): AppState {
445 switch (action.type) {
446 case "SYNC_SERVER_READ_MODEL": {
447 const projects = mapProjectsFromReadModel(
448 action.readModel.projects.filter((project) => project.deletedAt === null),
449 state.projects,
450 );
451 const existingThreadById = new Map(
452 state.threads.map((thread) => [thread.id, thread] as const),
453 );
454 const threads = action.readModel.threads
455 .filter((thread) => thread.deletedAt === null)
456 .map((thread) => {
457 const existing = existingThreadById.get(thread.id);
458​
459 return normalizeThreadTerminals({
460 id: thread.id,
461 codexThreadId: thread.session?.providerThreadId ?? null,
462 projectId: thread.projectId,
463 title: thread.title,
464 model: resolveModelSlug(thread.model),
465 terminalOpen: existing?.terminalOpen ?? false,
466 terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
467 terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
468 runningTerminalIds: existing?.runningTerminalIds ?? [],
469 activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
470 terminalGroups: existing?.terminalGroups ?? [
471 {
472 id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
473 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
474 },
475 ],
476 activeTerminalGroupId:
477 existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
478 session: thread.session
479 ? {
480 sessionId:
481 thread.session.providerSessionId ??
482 ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
483 provider: toLegacyProvider(thread.session.providerName),
484 status: toLegacySessionStatus(thread.session.status),
485 orchestrationStatus: thread.session.status,
486 threadId: thread.session.providerThreadId,
487 activeTurnId: thread.session.activeTurnId ?? undefined,
488 createdAt: thread.session.updatedAt,
489 updatedAt: thread.session.updatedAt,
490 ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
491 }
492 : null,
493 messages: thread.messages.map((message) => {
494 const attachments = message.attachments?.map((attachment) => ({
495 type: "image" as const,
496 id: attachment.id,
497 name: attachment.name,
498 mimeType: attachment.mimeType,
499 sizeBytes: attachment.sizeBytes,
500 previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
501 }));
502 const normalizedMessage: ChatMessage = {
503 id: message.id,
504 role: message.role,
505 text: message.text,
506 createdAt: message.createdAt,
507 streaming: message.streaming,
508 ...(message.streaming ? {} : { completedAt: message.updatedAt }),
509 ...(attachments && attachments.length > 0 ? { attachments } : {}),
510 };
511 return normalizedMessage;
512 }),
513 error: thread.session?.lastError ?? null,
514 createdAt: thread.createdAt,
515 latestTurn: thread.latestTurn,
516 lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
517 branch: thread.branch,
518 worktreePath: thread.worktreePath,
519 turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
520 turnId: checkpoint.turnId,
521 completedAt: checkpoint.completedAt,
522 status: checkpoint.status,
523 assistantMessageId: checkpoint.assistantMessageId ?? undefined,
524 checkpointTurnCount: checkpoint.checkpointTurnCount,
525 checkpointRef: checkpoint.checkpointRef,
526 files: checkpoint.files.map((file) => ({ ...file })),
527 })),
528 activities: thread.activities.map((activity) => ({ ...activity })),
529 });
530 });
531 return {
532 ...state,
533 projects,
534 threads,
535 threadsHydrated: true,
536 };
537 }
538​
539 case "MARK_THREAD_VISITED": {
540 const visitedAt = action.visitedAt ?? new Date().toISOString();
541 const visitedAtMs = Date.parse(visitedAt);
542 return {
543 ...state,
544 threads: updateThread(state.threads, action.threadId, (thread) => {
545 const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
546 if (
547 Number.isFinite(previousVisitedAtMs) &&
548 Number.isFinite(visitedAtMs) &&
549 previousVisitedAtMs >= visitedAtMs
550 ) {
551 return thread;
552 }
553 return {
554 ...thread,
555 lastVisitedAt: visitedAt,
556 };
557 }),
558 };
559 }
560​
561 case "MARK_THREAD_UNREAD": {
562 return {
563 ...state,
564 threads: updateThread(state.threads, action.threadId, (thread) => {
565 if (!thread.latestTurn?.completedAt) {
566 return thread;
567 }
568 const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
569 if (Number.isNaN(latestTurnCompletedAtMs)) {
570 return thread;
571 }
572 const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
573 if (thread.lastVisitedAt === unreadVisitedAt) {
574 return thread;
575 }
576 return {
577 ...thread,
578 lastVisitedAt: unreadVisitedAt,
579 };
580 }),
581 };
582 }
583​
584 case "TOGGLE_PROJECT":
585 return {
586 ...state,
587 projects: state.projects.map((p) =>
588 p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
589 ),
590 };
591​
592 case "SET_THREAD_TERMINAL_ACTIVITY":
593 return {
594 ...state,
595 threads: updateThread(state.threads, action.threadId, (thread) =>
596 setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
597 ),
598 };
599​
600 case "SET_PROJECT_EXPANDED":
601 return {
602 ...state,
603 projects: state.projects.map((p) =>
604 p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
605 ),
606 };
607​
608 case "TOGGLE_THREAD_TERMINAL":
609 return {
610 ...state,
611 threads: updateThread(state.threads, action.threadId, (t) => ({
612 ...t,
613 terminalOpen: !t.terminalOpen,
614 })),
615 };
616​
617 case "SET_THREAD_TERMINAL_OPEN":
618 return {
619 ...state,
620 threads: updateThread(state.threads, action.threadId, (t) => ({
621 ...t,
622 terminalOpen: action.open,
623 })),
624 };
625​
626 case "SET_THREAD_TERMINAL_HEIGHT":
627 return {
628 ...state,
629 threads: updateThread(state.threads, action.threadId, (t) => ({
630 ...t,
631 terminalHeight: action.height,
632 })),
633 };
634​
635 case "SPLIT_THREAD_TERMINAL":
636 return {
637 ...state,
638 threads: updateThread(state.threads, action.threadId, (thread) => {
639 const normalizedThread = normalizeThreadTerminals(thread);
640 const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
641 if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
642 return normalizedThread;
643 }
644 const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
645 ? normalizedThread.terminalIds
646 : [...normalizedThread.terminalIds, action.terminalId];
647 const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
648 ...group,
649 terminalIds: [...group.terminalIds],
650 }));
651 let activeGroupIndex = terminalGroups.findIndex(
652 (group) => group.id === normalizedThread.activeTerminalGroupId,
653 );
654 if (activeGroupIndex < 0) {
655 activeGroupIndex = findGroupIndexByTerminalId(
656 terminalGroups,
657 normalizedThread.activeTerminalId,
658 );
659 }
660 if (activeGroupIndex < 0) {
661 terminalGroups.push({
662 id: fallbackGroupId(normalizedThread.activeTerminalId),
663 terminalIds: [normalizedThread.activeTerminalId],
664 });
665 activeGroupIndex = terminalGroups.length - 1;
666 }
667​
668 const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
669 if (existingGroupIndex >= 0) {
670 terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
671 existingGroupIndex
672 ]!.terminalIds.filter((id) => id !== action.terminalId);
673 if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
674 terminalGroups.splice(existingGroupIndex, 1);
675 if (existingGroupIndex < activeGroupIndex) {
676 activeGroupIndex -= 1;
677 }
678 }
679 }
680​
681 const destinationGroup = terminalGroups[activeGroupIndex];
682 if (!destinationGroup) {
683 return normalizedThread;
684 }
685 if (!destinationGroup.terminalIds.includes(action.terminalId)) {
686 const anchorIndex = destinationGroup.terminalIds.indexOf(
687 normalizedThread.activeTerminalId,
688 );
689 if (anchorIndex >= 0) {
690 destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
691 } else {
692 destinationGroup.terminalIds.push(action.terminalId);
693 }
694 }
695 return normalizeThreadTerminals({
696 ...normalizedThread,
697 terminalIds,
698 activeTerminalId: action.terminalId,
699 activeTerminalGroupId: destinationGroup.id,
700 terminalGroups,
701 });
702 }),
703 };
704​
705 case "NEW_THREAD_TERMINAL":
706 return {
707 ...state,
708 threads: updateThread(state.threads, action.threadId, (thread) => {
709 const normalizedThread = normalizeThreadTerminals(thread);
710 const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
711 if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
712 return normalizedThread;
713 }
714 const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
715 ? normalizedThread.terminalIds
716 : [...normalizedThread.terminalIds, action.terminalId];
717 const terminalGroups = normalizedThread.terminalGroups
718 .map((group) => ({
719 ...group,
720 terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
721 }))
722 .filter((group) => group.terminalIds.length > 0);
723 const nextGroupId = fallbackGroupId(action.terminalId);
724 terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
725​
726 return normalizeThreadTerminals({
727 ...normalizedThread,
728 terminalIds,
729 activeTerminalId: action.terminalId,
730 activeTerminalGroupId: nextGroupId,
731 terminalGroups,
732 });
733 }),
734 };
735​
736 case "SET_THREAD_ACTIVE_TERMINAL":
737 return {
738 ...state,
739 threads: updateThread(state.threads, action.threadId, (thread) => {
740 const normalizedThread = normalizeThreadTerminals(thread);
741 if (!normalizedThread.terminalIds.includes(action.terminalId)) {
742 return thread;
743 }
744 const nextActiveGroupIndex = findGroupIndexByTerminalId(
745 normalizedThread.terminalGroups,
746 action.terminalId,
747 );
748 const activeTerminalGroupId =
749 nextActiveGroupIndex >= 0
750 ? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
751 normalizedThread.activeTerminalGroupId)
752 : normalizedThread.activeTerminalGroupId;
753 return normalizeThreadTerminals({
754 ...normalizedThread,
755 activeTerminalId: action.terminalId,
756 activeTerminalGroupId,
757 });
758 }),
759 };
760​
761 case "CLOSE_THREAD_TERMINAL":
762 return {
763 ...state,
764 threads: updateThread(state.threads, action.threadId, (thread) =>
765 closeThreadTerminal(thread, action.terminalId),
766 ),
767 };
768​
769 case "SET_ERROR":
770 return {
771 ...state,
772 threads: updateThread(state.threads, action.threadId, (t) => ({
773 ...t,
774 error: action.error,
775 })),
776 };
777​
778 case "SET_THREAD_BRANCH": {
779 return {
780 ...state,
781 threads: updateThread(state.threads, action.threadId, (t) => {
782 // When the effective cwd changes (worktreePath differs), the old
783 // session is no longer valid — clear it so ensureSession creates a
784 // new one with the correct cwd on the next message.
785 const cwdChanged = t.worktreePath !== action.worktreePath;
786 return {
787 ...t,
788 branch: action.branch,
789 worktreePath: action.worktreePath,
790 ...(cwdChanged ? { session: null } : {}),
791 };
792 }),
793 };
794 }
795​
796 case "SET_RUNTIME_MODE":
797 return {
798 ...state,
799 runtimeMode: action.mode,
800 };
801​
802 default:
803 return state;
804 }
806​
807// ── Context ──────────────────────────────────────────────────────────
808​
809const StoreContext = createContext<{
810 state: AppState;
811 dispatch: Dispatch<Action>;
812}>({ state: initialState, dispatch: () => {} });
813​
814export function StoreProvider({ children }: { children: ReactNode }) {
815 const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
816​
817 useEffect(() => {
818 persistState(state);
819 }, [state]);
820​
821 return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
823​
824export function useStore() {
825 return useContext(StoreContext);