1
-import { type ReactNode } from "react";
2
-import { create } from "zustand";
3
-
1
+import { Fragment, type ReactNode, createElement, useEffect } from "react";
2
import {
3
DEFAULT_MODEL,
4
ProviderSessionId,
7
type OrchestrationSessionStatus,
8
resolveModelSlug,
9
} from "@t3tools/contracts";
12
-import {
13
- createDefaultThreadTerminalState,
14
- normalizeThreadTerminalState,
15
- reduceThreadTerminalState,
16
- type ThreadTerminalState,
17
-} from "./threadTerminalState";
10
+import { create } from "zustand";
11
import {
12
DEFAULT_RUNTIME_MODE,
13
type ChatMessage,
16
type Thread,
17
} from "./types";
18
26
-// ── Actions ──────────────────────────────────────────────────────────
27
-
28
-type Action =
29
- | { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
30
- | { type: "HYDRATE_THREAD_TERMINALS"; threadId: ThreadId; terminalState: ThreadTerminalState }
31
- | { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
32
- | { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
33
- | { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
34
- | {
35
- type: "SET_THREAD_TERMINAL_ACTIVITY";
36
- threadId: ThreadId;
37
- terminalId: string;
38
- hasRunningSubprocess: boolean;
39
- }
40
- | { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
41
- | { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
42
- | { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
43
- | { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
44
- | { type: "SPLIT_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
45
- | { type: "NEW_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
46
- | { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: ThreadId; terminalId: string }
47
- | { type: "CLOSE_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
48
- | { type: "SET_ERROR"; threadId: ThreadId; error: string | null }
49
- | {
50
- type: "SET_THREAD_BRANCH";
51
- threadId: ThreadId;
52
- branch: string | null;
53
- worktreePath: string | null;
54
- }
55
- | { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
56
-
19
// ── State ────────────────────────────────────────────────────────────
20
21
export interface AppState {
68
};
69
const persistedExpandedProjectCwds = new Set<string>();
70
109
-// ── Helpers ──────────────────────────────────────────────────────────
71
+// ── Persist helpers ──────────────────────────────────────────────────
72
73
function readPersistedState(): AppState {
74
if (typeof window === "undefined") return initialState;
113
-
75
try {
76
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
77
if (!raw) return initialState;
99
100
function persistState(state: AppState): void {
101
if (typeof window === "undefined") return;
141
-
102
try {
103
window.localStorage.setItem(
104
PERSISTED_STATE_KEY,
117
}
118
}
119
120
+// ── Pure helpers ──────────────────────────────────────────────────────
121
+
122
function updateThread(
123
threads: Thread[],
124
threadId: ThreadId,
174
}
175
176
function resolveWsHttpOrigin(): string {
215
- if (typeof window === "undefined") {
216
- return "";
217
- }
177
+ if (typeof window === "undefined") return "";
178
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
179
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
180
const wsCandidate =
183
: typeof envWsUrl === "string" && envWsUrl.length > 0
184
? envWsUrl
185
: null;
226
- if (!wsCandidate) {
227
- return window.location.origin;
228
- }
229
-
186
+ if (!wsCandidate) return window.location.origin;
187
try {
188
const wsUrl = new URL(wsCandidate);
189
const protocol =
209
return `/attachments/${encodeURIComponent(attachmentId)}`;
210
}
211
255
-function threadTerminalSlice(thread: Thread): ThreadTerminalState {
256
- return {
257
- terminalOpen: thread.terminalOpen,
258
- terminalHeight: thread.terminalHeight,
259
- terminalIds: thread.terminalIds,
260
- runningTerminalIds: thread.runningTerminalIds,
261
- activeTerminalId: thread.activeTerminalId,
262
- terminalGroups: thread.terminalGroups,
263
- activeTerminalGroupId: thread.activeTerminalGroupId,
264
- };
265
-}
266
-
267
-function applyTerminalState(thread: Thread, terminal: ThreadTerminalState): Thread {
268
- return { ...thread, ...terminal };
269
-}
270
-
271
-function normalizeThreadTerminals(thread: Thread): Thread {
272
- return applyTerminalState(thread, normalizeThreadTerminalState(threadTerminalSlice(thread)));
273
-}
212
+// ── Pure state transition functions ────────────────────────────────────
213
275
-function syncServerReadModelState(state: AppState, readModel: OrchestrationReadModel): AppState {
214
+export function syncServerReadModel(
215
+ state: AppState,
216
+ readModel: OrchestrationReadModel,
217
+): AppState {
218
const projects = mapProjectsFromReadModel(
219
readModel.projects.filter((project) => project.deletedAt === null),
220
state.projects,
221
);
280
- const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
222
+ const existingThreadById = new Map(
223
+ state.threads.map((thread) => [thread.id, thread] as const),
224
+ );
225
const threads = readModel.threads
226
.filter((thread) => thread.deletedAt === null)
227
.map((thread) => {
228
const existing = existingThreadById.get(thread.id);
285
-
286
-export function reducer(state: AppState, action: Action): AppState {
287
- switch (action.type) {
288
- case "SYNC_SERVER_READ_MODEL": {
289
- const projects = mapProjectsFromReadModel(
290
- action.readModel.projects.filter((project) => project.deletedAt === null),
291
- state.projects,
292
- );
293
- const existingThreadById = new Map(
294
- state.threads.map((thread) => [thread.id, thread] as const),
295
- );
296
- const defaultTerminal = createDefaultThreadTerminalState();
297
- const threads = action.readModel.threads
298
- .filter((thread) => thread.deletedAt === null)
299
- .map((thread) => {
300
- const existing = existingThreadById.get(thread.id);
301
- const terminalSlice: ThreadTerminalState = existing
302
- ? threadTerminalSlice(existing)
303
- : defaultTerminal;
304
-
305
- return normalizeThreadTerminals({
306
- id: thread.id,
307
- codexThreadId: thread.session?.providerThreadId ?? null,
308
- projectId: thread.projectId,
309
- title: thread.title,
310
- model: resolveModelSlug(thread.model),
311
- ...terminalSlice,
312
- session: thread.session
313
- ? {
314
- sessionId:
315
- thread.session.providerSessionId ??
316
- ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
317
- provider: toLegacyProvider(thread.session.providerName),
318
- status: toLegacySessionStatus(thread.session.status),
319
- orchestrationStatus: thread.session.status,
320
- threadId: thread.session.providerThreadId,
321
- activeTurnId: thread.session.activeTurnId ?? undefined,
322
- createdAt: thread.session.updatedAt,
323
- updatedAt: thread.session.updatedAt,
324
- ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
325
- }
326
- : null,
327
- messages: thread.messages.map((message) => {
328
- const attachments = message.attachments?.map((attachment) => ({
329
- type: "image" as const,
330
- id: attachment.id,
331
- name: attachment.name,
332
- mimeType: attachment.mimeType,
333
- sizeBytes: attachment.sizeBytes,
334
- previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
335
- }));
336
- const normalizedMessage: ChatMessage = {
337
- id: message.id,
338
- role: message.role,
339
- text: message.text,
340
- createdAt: message.createdAt,
341
- streaming: message.streaming,
342
- ...(message.streaming ? {} : { completedAt: message.updatedAt }),
343
- ...(attachments && attachments.length > 0 ? { attachments } : {}),
344
- };
345
- return normalizedMessage;
346
- }),
347
- error: thread.session?.lastError ?? null,
348
- createdAt: thread.createdAt,
349
- latestTurn: thread.latestTurn,
350
- lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
351
- branch: thread.branch,
352
- worktreePath: thread.worktreePath,
353
- turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
354
- turnId: checkpoint.turnId,
355
- completedAt: checkpoint.completedAt,
356
- status: checkpoint.status,
357
- assistantMessageId: checkpoint.assistantMessageId ?? undefined,
358
- checkpointTurnCount: checkpoint.checkpointTurnCount,
359
- checkpointRef: checkpoint.checkpointRef,
360
- files: checkpoint.files.map((file) => ({ ...file })),
361
- })),
362
- activities: thread.activities.map((activity) => ({ ...activity })),
363
- });
364
- });
229
return {
366
- ...state,
367
- projects,
368
- threads,
369
- threadsHydrated: true,
370
- };
371
- }
372
-
373
- case "HYDRATE_THREAD_TERMINALS":
374
- return {
375
- ...state,
376
- threads: updateThread(state.threads, action.threadId, (thread) =>
377
- applyTerminalState(thread, normalizeThreadTerminalState(action.terminalState)),
378
- ),
379
- };
380
-
381
- case "MARK_THREAD_VISITED": {
382
- const visitedAt = action.visitedAt ?? new Date().toISOString();
383
- const visitedAtMs = Date.parse(visitedAt);
384
- return {
385
- ...state,
386
- threads: updateThread(state.threads, action.threadId, (thread) => {
387
- const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
388
- if (
389
- Number.isFinite(previousVisitedAtMs) &&
390
- Number.isFinite(visitedAtMs) &&
391
- previousVisitedAtMs >= visitedAtMs
392
- ) {
393
- return thread;
394
- }
395
- return {
396
- ...thread,
397
- lastVisitedAt: visitedAt,
398
- };
399
- }),
400
- };
401
- }
402
-
403
- case "MARK_THREAD_UNREAD": {
404
- return {
405
- ...state,
406
- threads: updateThread(state.threads, action.threadId, (thread) => {
407
- if (!thread.latestTurn?.completedAt) {
408
- return thread;
409
- }
410
- const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
411
- if (Number.isNaN(latestTurnCompletedAtMs)) {
412
- return thread;
413
- }
414
- const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
415
- if (thread.lastVisitedAt === unreadVisitedAt) {
416
- return thread;
417
- }
418
- return {
419
- ...thread,
420
- lastVisitedAt: unreadVisitedAt,
421
- };
422
- }),
423
- };
424
- }
425
-
426
- case "TOGGLE_PROJECT":
427
- return {
428
- ...state,
429
- projects: state.projects.map((p) =>
430
- p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
431
- ),
432
- };
433
-
434
- case "SET_THREAD_TERMINAL_ACTIVITY":
435
- return {
436
- ...state,
437
- threads: updateThread(state.threads, action.threadId, (thread) =>
438
- applyTerminalState(
439
- thread,
440
- reduceThreadTerminalState(threadTerminalSlice(thread), {
441
- type: "set-activity",
442
- terminalId: action.terminalId,
443
- hasRunningSubprocess: action.hasRunningSubprocess,
444
- }),
445
- ),
446
- ),
447
- };
448
-
449
- case "SET_PROJECT_EXPANDED":
450
- return {
451
- ...state,
452
- projects: state.projects.map((p) =>
453
- p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
454
- ),
455
- };
456
-
457
- case "TOGGLE_THREAD_TERMINAL":
458
- return {
459
- ...state,
460
- threads: updateThread(state.threads, action.threadId, (thread) =>
461
- applyTerminalState(
462
- thread,
463
- reduceThreadTerminalState(threadTerminalSlice(thread), {
464
- type: "set-open",
465
- open: !thread.terminalOpen,
466
- }),
467
- ),
468
- ),
469
- };
470
-
471
- case "SET_THREAD_TERMINAL_OPEN":
472
- return {
473
- ...state,
474
- threads: updateThread(state.threads, action.threadId, (thread) =>
475
- applyTerminalState(
476
- thread,
477
- reduceThreadTerminalState(threadTerminalSlice(thread), {
478
- type: "set-open",
479
- open: action.open,
480
- }),
481
- ),
482
- ),
483
- };
484
-
485
- case "SET_THREAD_TERMINAL_HEIGHT":
486
- return {
487
- ...state,
488
- threads: updateThread(state.threads, action.threadId, (thread) =>
489
- applyTerminalState(
490
- thread,
491
- reduceThreadTerminalState(threadTerminalSlice(thread), {
492
- type: "set-height",
493
- height: action.height,
494
- }),
495
- ),
496
- ),
497
- };
498
-
499
- case "SPLIT_THREAD_TERMINAL":
500
- return {
501
- ...state,
502
- threads: updateThread(state.threads, action.threadId, (thread) =>
503
- applyTerminalState(
504
- thread,
505
- reduceThreadTerminalState(threadTerminalSlice(thread), {
506
- type: "split",
507
- terminalId: action.terminalId,
508
- }),
509
- ),
510
- ),
511
- };
512
-
513
- case "NEW_THREAD_TERMINAL":
514
- return {
515
- ...state,
516
- threads: updateThread(state.threads, action.threadId, (thread) =>
517
- applyTerminalState(
518
- thread,
519
- reduceThreadTerminalState(threadTerminalSlice(thread), {
520
- type: "new",
521
- terminalId: action.terminalId,
522
- }),
523
- ),
524
- ),
525
- };
526
-
527
- case "SET_THREAD_ACTIVE_TERMINAL":
528
- return {
529
- ...state,
530
- threads: updateThread(state.threads, action.threadId, (thread) =>
531
- applyTerminalState(
532
- thread,
533
- reduceThreadTerminalState(threadTerminalSlice(thread), {
534
- type: "set-active",
535
- terminalId: action.terminalId,
536
- }),
537
- ),
538
- ),
539
- };
540
-
541
- case "CLOSE_THREAD_TERMINAL":
542
- return {
543
- ...state,
544
- threads: updateThread(state.threads, action.threadId, (thread) =>
545
- applyTerminalState(
546
- thread,
547
- reduceThreadTerminalState(threadTerminalSlice(thread), {
548
- type: "close",
549
- terminalId: action.terminalId,
550
- }),
551
- ),
552
- ),
553
- };
554
-
555
- case "SET_ERROR":
556
- return {
557
- ...state,
558
- threads: updateThread(state.threads, action.threadId, (t) => ({
559
- ...t,
560
- error: action.error,
561
- })),
562
- };
563
-
564
- case "SET_THREAD_BRANCH": {
565
- return {
566
- ...state,
567
- threads: updateThread(state.threads, action.threadId, (t) => {
568
- // When the effective cwd changes (worktreePath differs), the old
569
- // session is no longer valid — clear it so ensureSession creates a
570
- // new one with the correct cwd on the next message.
571
- const cwdChanged = t.worktreePath !== action.worktreePath;
572
- return {
573
- ...t,
574
- branch: action.branch,
575
- worktreePath: action.worktreePath,
576
- ...(cwdChanged ? { session: null } : {}),
230
+ id: thread.id,
231
+ codexThreadId: thread.session?.providerThreadId ?? null,
232
+ projectId: thread.projectId,
233
+ title: thread.title,
234
+ model: resolveModelSlug(thread.model),
235
+ session: thread.session
236
+ ? {
237
+ sessionId:
238
+ thread.session.providerSessionId ??
239
+ ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
240
+ provider: toLegacyProvider(thread.session.providerName),
241
+ status: toLegacySessionStatus(thread.session.status),
242
+ orchestrationStatus: thread.session.status,
243
+ threadId: thread.session.providerThreadId,
244
+ activeTurnId: thread.session.activeTurnId ?? undefined,
245
+ createdAt: thread.session.updatedAt,
246
+ updatedAt: thread.session.updatedAt,
247
+ ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
248
+ }
249
+ : null,
250
+ messages: thread.messages.map((message) => {
251
+ const attachments = message.attachments?.map((attachment) => ({
252
+ type: "image" as const,
253
+ id: attachment.id,
254
+ name: attachment.name,
255
+ mimeType: attachment.mimeType,
256
+ sizeBytes: attachment.sizeBytes,
257
+ previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
258
+ }));
259
+ const normalizedMessage: ChatMessage = {
260
+ id: message.id,
261
+ role: message.role,
262
+ text: message.text,
263
+ createdAt: message.createdAt,
264
+ streaming: message.streaming,
265
+ ...(message.streaming ? {} : { completedAt: message.updatedAt }),
266
+ ...(attachments && attachments.length > 0 ? { attachments } : {}),
267
};
268
return normalizedMessage;
269
}),
283
files: checkpoint.files.map((file) => ({ ...file })),
284
})),
285
activities: thread.activities.map((activity) => ({ ...activity })),
596
- });
286
+ };
287
});
288
return {
289
...state,
293
};
294
}
295
606
-function markThreadVisitedState(state: AppState, threadId: ThreadId, visitedAt?: string): AppState {
607
- const nextVisitedAt = visitedAt ?? new Date().toISOString();
608
- const visitedAtMs = Date.parse(nextVisitedAt);
296
+export function markThreadVisited(
297
+ state: AppState,
298
+ threadId: ThreadId,
299
+ visitedAt?: string,
300
+): AppState {
301
+ const at = visitedAt ?? new Date().toISOString();
302
+ const visitedAtMs = Date.parse(at);
303
return {
304
...state,
305
threads: updateThread(state.threads, threadId, (thread) => {
311
) {
312
return thread;
313
}
620
- return {
621
- ...thread,
622
- lastVisitedAt: nextVisitedAt,
623
- };
314
+ return { ...thread, lastVisitedAt: at };
315
}),
316
};
317
}
318
628
-function markThreadUnreadState(state: AppState, threadId: ThreadId): AppState {
319
+export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
320
return {
321
...state,
322
threads: updateThread(state.threads, threadId, (thread) => {
632
- if (!thread.latestTurn?.completedAt) {
633
- return thread;
634
- }
323
+ if (!thread.latestTurn?.completedAt) return thread;
324
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
636
- if (Number.isNaN(latestTurnCompletedAtMs)) {
637
- return thread;
638
- }
325
+ if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
326
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
640
- if (thread.lastVisitedAt === unreadVisitedAt) {
641
- return thread;
642
- }
643
- return {
644
- ...thread,
645
- lastVisitedAt: unreadVisitedAt,
646
- };
327
+ if (thread.lastVisitedAt === unreadVisitedAt) return thread;
328
+ return { ...thread, lastVisitedAt: unreadVisitedAt };
329
}),
330
};
331
}
332
651
-function toggleProjectState(state: AppState, projectId: Project["id"]): AppState {
333
+export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
334
return {
335
...state,
654
- projects: state.projects.map((project) =>
655
- project.id === projectId ? { ...project, expanded: !project.expanded } : project,
336
+ projects: state.projects.map((p) =>
337
+ p.id === projectId ? { ...p, expanded: !p.expanded } : p,
338
),
339
};
340
}
341
660
-function setThreadTerminalActivityState(
661
- state: AppState,
662
- threadId: ThreadId,
663
- terminalId: string,
664
- hasRunningSubprocess: boolean,
665
-): AppState {
666
- return {
667
- ...state,
668
- threads: updateThread(state.threads, threadId, (thread) =>
669
- setThreadTerminalActivity(thread, terminalId, hasRunningSubprocess),
670
- ),
671
- };
672
-}
673
-
674
-function setProjectExpandedState(
342
+export function setProjectExpanded(
343
state: AppState,
344
projectId: Project["id"],
345
expanded: boolean,
346
): AppState {
347
return {
348
...state,
681
- projects: state.projects.map((project) =>
682
- project.id === projectId ? { ...project, expanded } : project,
349
+ projects: state.projects.map((p) =>
350
+ p.id === projectId ? { ...p, expanded } : p,
351
),
352
};
353
}
354
687
-function toggleThreadTerminalState(state: AppState, threadId: ThreadId): AppState {
688
- return {
689
- ...state,
690
- threads: updateThread(state.threads, threadId, (thread) => ({
691
- ...thread,
692
- terminalOpen: !thread.terminalOpen,
693
- })),
694
- };
695
-}
696
-
697
-function setThreadTerminalOpenState(state: AppState, threadId: ThreadId, open: boolean): AppState {
698
- return {
699
- ...state,
700
- threads: updateThread(state.threads, threadId, (thread) => ({
701
- ...thread,
702
- terminalOpen: open,
703
- })),
704
- };
705
-}
706
-
707
-function setThreadTerminalHeightState(
708
- state: AppState,
709
- threadId: ThreadId,
710
- height: number,
711
-): AppState {
712
- return {
713
- ...state,
714
- threads: updateThread(state.threads, threadId, (thread) => ({
715
- ...thread,
716
- terminalHeight: height,
717
- })),
718
- };
719
-}
720
-
721
-function splitThreadTerminalState(
722
- state: AppState,
723
- threadId: ThreadId,
724
- terminalId: string,
725
-): AppState {
726
- return {
727
- ...state,
728
- threads: updateThread(state.threads, threadId, (thread) => {
729
- const normalizedThread = normalizeThreadTerminals(thread);
730
- const isNewTerminal = !normalizedThread.terminalIds.includes(terminalId);
731
- if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
732
- return normalizedThread;
733
- }
734
- const terminalIds = normalizedThread.terminalIds.includes(terminalId)
735
- ? normalizedThread.terminalIds
736
- : [...normalizedThread.terminalIds, terminalId];
737
- const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
738
- ...group,
739
- terminalIds: [...group.terminalIds],
740
- }));
741
- let activeGroupIndex = terminalGroups.findIndex(
742
- (group) => group.id === normalizedThread.activeTerminalGroupId,
743
- );
744
- if (activeGroupIndex < 0) {
745
- activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalizedThread.activeTerminalId);
746
- }
747
- if (activeGroupIndex < 0) {
748
- terminalGroups.push({
749
- id: fallbackGroupId(normalizedThread.activeTerminalId),
750
- terminalIds: [normalizedThread.activeTerminalId],
751
- });
752
- activeGroupIndex = terminalGroups.length - 1;
753
- }
754
-
755
- const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);
756
- if (existingGroupIndex >= 0) {
757
- terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[existingGroupIndex]!.terminalIds.filter(
758
- (id) => id !== terminalId,
759
- );
760
- if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
761
- terminalGroups.splice(existingGroupIndex, 1);
762
- if (existingGroupIndex < activeGroupIndex) {
763
- activeGroupIndex -= 1;
764
- }
765
- }
766
- }
767
-
768
- const destinationGroup = terminalGroups[activeGroupIndex];
769
- if (!destinationGroup) {
770
- return normalizedThread;
771
- }
772
- if (!destinationGroup.terminalIds.includes(terminalId)) {
773
- const anchorIndex = destinationGroup.terminalIds.indexOf(normalizedThread.activeTerminalId);
774
- if (anchorIndex >= 0) {
775
- destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
776
- } else {
777
- destinationGroup.terminalIds.push(terminalId);
778
- }
779
- }
780
- return normalizeThreadTerminals({
781
- ...normalizedThread,
782
- terminalIds,
783
- activeTerminalId: terminalId,
784
- activeTerminalGroupId: destinationGroup.id,
785
- terminalGroups,
786
- });
787
- }),
788
- };
789
-}
790
-
791
-function newThreadTerminalState(
792
- state: AppState,
793
- threadId: ThreadId,
794
- terminalId: string,
795
-): AppState {
796
- return {
797
- ...state,
798
- threads: updateThread(state.threads, threadId, (thread) => {
799
- const normalizedThread = normalizeThreadTerminals(thread);
800
- const isNewTerminal = !normalizedThread.terminalIds.includes(terminalId);
801
- if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
802
- return normalizedThread;
803
- }
804
- const terminalIds = normalizedThread.terminalIds.includes(terminalId)
805
- ? normalizedThread.terminalIds
806
- : [...normalizedThread.terminalIds, terminalId];
807
- const terminalGroups = normalizedThread.terminalGroups
808
- .map((group) => ({
809
- ...group,
810
- terminalIds: group.terminalIds.filter((id) => id !== terminalId),
811
- }))
812
- .filter((group) => group.terminalIds.length > 0);
813
- const nextGroupId = fallbackGroupId(terminalId);
814
- terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
815
-
816
- return normalizeThreadTerminals({
817
- ...normalizedThread,
818
- terminalIds,
819
- activeTerminalId: terminalId,
820
- activeTerminalGroupId: nextGroupId,
821
- terminalGroups,
822
- });
823
- }),
824
- };
825
-}
826
-
827
-function setThreadActiveTerminalState(
828
- state: AppState,
829
- threadId: ThreadId,
830
- terminalId: string,
831
-): AppState {
832
- return {
833
- ...state,
834
- threads: updateThread(state.threads, threadId, (thread) => {
835
- const normalizedThread = normalizeThreadTerminals(thread);
836
- if (!normalizedThread.terminalIds.includes(terminalId)) {
837
- return thread;
838
- }
839
- const nextActiveGroupIndex = findGroupIndexByTerminalId(
840
- normalizedThread.terminalGroups,
841
- terminalId,
842
- );
843
- const activeTerminalGroupId =
844
- nextActiveGroupIndex >= 0
845
- ? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
846
- normalizedThread.activeTerminalGroupId)
847
- : normalizedThread.activeTerminalGroupId;
848
- return normalizeThreadTerminals({
849
- ...normalizedThread,
850
- activeTerminalId: terminalId,
851
- activeTerminalGroupId,
852
- });
853
- }),
854
- };
855
-}
856
-
857
-function closeThreadTerminalState(
858
- state: AppState,
859
- threadId: ThreadId,
860
- terminalId: string,
861
-): AppState {
862
- return {
863
- ...state,
864
- threads: updateThread(state.threads, threadId, (thread) => closeThreadTerminal(thread, terminalId)),
865
- };
866
-}
867
-
868
-function setThreadErrorState(
869
- state: AppState,
870
- threadId: ThreadId,
871
- error: string | null,
872
-): AppState {
355
+export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
356
return {
357
...state,
875
- threads: updateThread(state.threads, threadId, (thread) => ({
876
- ...thread,
877
- error,
878
- })),
358
+ threads: updateThread(state.threads, threadId, (t) => ({ ...t, error })),
359
};
360
}
361
882
-function setThreadBranchState(
362
+export function setThreadBranch(
363
state: AppState,
364
threadId: ThreadId,
365
branch: string | null,
367
): AppState {
368
return {
369
...state,
890
- threads: updateThread(state.threads, threadId, (thread) => {
891
- // When the effective cwd changes (worktreePath differs), the old
892
- // session is no longer valid — clear it so ensureSession creates a
893
- // new one with the correct cwd on the next message.
894
- const cwdChanged = thread.worktreePath !== worktreePath;
370
+ threads: updateThread(state.threads, threadId, (t) => {
371
+ const cwdChanged = t.worktreePath !== worktreePath;
372
return {
896
- ...thread,
373
+ ...t,
374
branch,
375
worktreePath,
376
...(cwdChanged ? { session: null } : {}),
379
};
380
}
381
905
-function setRuntimeModeState(state: AppState, mode: RuntimeMode): AppState {
906
- return {
907
- ...state,
908
- runtimeMode: mode,
909
- };
382
+export function setRuntimeMode(state: AppState, mode: RuntimeMode): AppState {
383
+ return { ...state, runtimeMode: mode };
384
}
385
912
-function toAppState(store: AppStore): AppState {
913
- return {
914
- projects: store.projects,
915
- threads: store.threads,
916
- threadsHydrated: store.threadsHydrated,
917
- runtimeMode: store.runtimeMode,
918
- };
386
+// ── Zustand store ────────────────────────────────────────────────────
387
+
388
+interface AppStore extends AppState {
389
+ syncServerReadModel: (readModel: OrchestrationReadModel) => void;
390
+ markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
391
+ markThreadUnread: (threadId: ThreadId) => void;
392
+ toggleProject: (projectId: Project["id"]) => void;
393
+ setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
394
+ setError: (threadId: ThreadId, error: string | null) => void;
395
+ setThreadBranch: (
396
+ threadId: ThreadId,
397
+ branch: string | null,
398
+ worktreePath: string | null,
399
+ ) => void;
400
+ setRuntimeMode: (mode: RuntimeMode) => void;
401
}
402
921
-export const useStore = create<AppStore>((set) => {
922
- const setAppState = (updater: (state: AppState) => AppState): void => {
923
- set((store) => {
924
- const currentState = toAppState(store);
925
- const nextState = updater(currentState);
926
- if (nextState === currentState) {
927
- return store;
928
- }
929
- persistState(nextState);
930
- return nextState;
931
- });
932
- };
403
+export const useAppStore = create<AppStore>((set, _get) => ({
404
+ ...readPersistedState(),
405
+ syncServerReadModel: (readModel) =>
406
+ set((state) => syncServerReadModel(state, readModel)),
407
+ markThreadVisited: (threadId, visitedAt) =>
408
+ set((state) => markThreadVisited(state, threadId, visitedAt)),
409
+ markThreadUnread: (threadId) =>
410
+ set((state) => markThreadUnread(state, threadId)),
411
+ toggleProject: (projectId) =>
412
+ set((state) => toggleProject(state, projectId)),
413
+ setProjectExpanded: (projectId, expanded) =>
414
+ set((state) => setProjectExpanded(state, projectId, expanded)),
415
+ setError: (threadId, error) =>
416
+ set((state) => setError(state, threadId, error)),
417
+ setThreadBranch: (threadId, branch, worktreePath) =>
418
+ set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
419
+ setRuntimeMode: (mode) =>
420
+ set((state) => setRuntimeMode(state, mode)),
421
+}));
422
+
423
+// Persist on every state change (only runtimeMode + expandedProjectCwds)
424
+useAppStore.subscribe((state) => persistState(state));
425
+
426
+// ── useStore (state + store API for call sites that want both) ────────────────
427
428
+export function StoreProvider({ children }: { children: ReactNode }) {
429
+ useEffect(() => {
430
+ persistState(useAppStore.getState());
431
+ }, []);
432
+ return createElement(Fragment, null, children);
433
+}
434
+
435
+export function useStore() {
436
+ const state = useAppStore((s) => ({
437
+ projects: s.projects,
438
+ threads: s.threads,
439
+ threadsHydrated: s.threadsHydrated,
440
+ runtimeMode: s.runtimeMode,
441
+ }));
442
return {
935
- ...readPersistedState(),
936
- syncServerReadModel: (readModel) =>
937
- setAppState((state) => syncServerReadModelState(state, readModel)),
938
- markThreadVisited: (threadId, visitedAt) =>
939
- setAppState((state) => markThreadVisitedState(state, threadId, visitedAt)),
940
- markThreadUnread: (threadId) => setAppState((state) => markThreadUnreadState(state, threadId)),
941
- toggleProject: (projectId) => setAppState((state) => toggleProjectState(state, projectId)),
942
- setThreadTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
943
- setAppState((state) =>
944
- setThreadTerminalActivityState(state, threadId, terminalId, hasRunningSubprocess),
945
- ),
946
- setProjectExpanded: (projectId, expanded) =>
947
- setAppState((state) => setProjectExpandedState(state, projectId, expanded)),
948
- toggleThreadTerminal: (threadId) =>
949
- setAppState((state) => toggleThreadTerminalState(state, threadId)),
950
- setThreadTerminalOpen: (threadId, open) =>
951
- setAppState((state) => setThreadTerminalOpenState(state, threadId, open)),
952
- setThreadTerminalHeight: (threadId, height) =>
953
- setAppState((state) => setThreadTerminalHeightState(state, threadId, height)),
954
- splitThreadTerminal: (threadId, terminalId) =>
955
- setAppState((state) => splitThreadTerminalState(state, threadId, terminalId)),
956
- newThreadTerminal: (threadId, terminalId) =>
957
- setAppState((state) => newThreadTerminalState(state, threadId, terminalId)),
958
- setThreadActiveTerminal: (threadId, terminalId) =>
959
- setAppState((state) => setThreadActiveTerminalState(state, threadId, terminalId)),
960
- closeThreadTerminal: (threadId, terminalId) =>
961
- setAppState((state) => closeThreadTerminalState(state, threadId, terminalId)),
962
- setThreadError: (threadId, error) =>
963
- setAppState((state) => setThreadErrorState(state, threadId, error)),
964
- setThreadBranch: (threadId, branch, worktreePath) =>
965
- setAppState((state) => setThreadBranchState(state, threadId, branch, worktreePath)),
966
- setRuntimeMode: (mode) => setAppState((state) => setRuntimeModeState(state, mode)),
443
+ state,
444
+ dispatch: useAppStore.getState(),
445
};
968
-});
969
-
970
-export function StoreProvider({ children }: { children: ReactNode }) {
971
- return children;
446
}