10
resolveModelSlug,
11
} from "@t3tools/contracts";
12
import {
13
- DEFAULT_THREAD_TERMINAL_HEIGHT,
14
- DEFAULT_THREAD_TERMINAL_ID,
13
+ createDefaultThreadTerminalState,
14
+ normalizeThreadTerminalState,
15
+ reduceThreadTerminalState,
16
+ type ThreadTerminalState,
17
+} from "./threadTerminalState";
18
+import {
19
DEFAULT_RUNTIME_MODE,
16
- MAX_THREAD_TERMINAL_COUNT,
20
type ChatMessage,
21
type Project,
22
type RuntimeMode,
23
type Thread,
21
- type ThreadTerminalGroup,
24
} from "./types";
25
26
// ── Actions ──────────────────────────────────────────────────────────
27
28
type Action =
29
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
28
- | {
29
- type: "HYDRATE_THREAD_TERMINALS";
30
- threadId: ThreadId;
31
- terminalState: {
32
- terminalOpen: boolean;
33
- terminalHeight: number;
34
- terminalIds: string[];
35
- runningTerminalIds: string[];
36
- activeTerminalId: string;
37
- terminalGroups: ThreadTerminalGroup[];
38
- activeTerminalGroupId: string;
39
- };
40
- }
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"] }
252
return `/attachments/${encodeURIComponent(attachmentId)}`;
253
}
254
265
-function normalizeTerminalIds(terminalIds: string[]): string[] {
266
- const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
267
- const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
268
- if (unique.length > 0) {
269
- return unique;
270
- }
271
- return [DEFAULT_THREAD_TERMINAL_ID];
272
-}
273
-
274
-function normalizeRunningTerminalIds(
275
- runningTerminalIds: string[],
276
- terminalIds: string[],
277
-): string[] {
278
- if (runningTerminalIds.length === 0) return [];
279
- const validTerminalIdSet = new Set(terminalIds);
280
- return [...new Set(runningTerminalIds)]
281
- .map((id) => id.trim())
282
- .filter((id) => id.length > 0 && validTerminalIdSet.has(id));
283
-}
284
-
285
-function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
286
- return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
287
-}
288
-
289
-function fallbackGroupId(terminalId: string): string {
290
- return `group-${terminalId}`;
291
-}
292
-
293
-function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
294
- if (!usedGroupIds.has(groupId)) {
295
- usedGroupIds.add(groupId);
296
- return groupId;
297
- }
298
- let suffix = 2;
299
- while (usedGroupIds.has(`${groupId}-${suffix}`)) {
300
- suffix += 1;
301
- }
302
- const uniqueGroupId = `${groupId}-${suffix}`;
303
- usedGroupIds.add(uniqueGroupId);
304
- return uniqueGroupId;
305
-}
306
-
307
-function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
308
- const validTerminalIdSet = new Set(terminalIds);
309
- const assignedTerminalIds = new Set<string>();
310
- const usedGroupIds = new Set<string>();
311
- const groups: ThreadTerminalGroup[] = [];
312
-
313
- for (const group of thread.terminalGroups) {
314
- const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
315
- if (!validTerminalIdSet.has(terminalId)) return false;
316
- if (assignedTerminalIds.has(terminalId)) return false;
317
- return true;
318
- });
319
- if (groupTerminalIds.length === 0) continue;
320
- for (const terminalId of groupTerminalIds) {
321
- assignedTerminalIds.add(terminalId);
322
- }
323
- const baseGroupId =
324
- group.id.trim().length > 0
325
- ? group.id.trim()
326
- : fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
327
- groups.push({
328
- id: assignUniqueGroupId(baseGroupId, usedGroupIds),
329
- terminalIds: groupTerminalIds,
330
- });
331
- }
332
-
333
- for (const terminalId of terminalIds) {
334
- if (assignedTerminalIds.has(terminalId)) continue;
335
- groups.push({
336
- id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
337
- terminalIds: [terminalId],
338
- });
339
- }
340
-
341
- if (groups.length > 0) {
342
- return groups;
343
- }
344
-
345
- return [
346
- {
347
- id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
348
- terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
349
- },
350
- ];
351
-}
352
-
353
-function findGroupIndexByTerminalId(
354
- terminalGroups: ThreadTerminalGroup[],
355
- terminalId: string,
356
-): number {
357
- return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
358
-}
359
-
360
-function normalizeThreadTerminals(thread: Thread): Thread {
361
- const terminalIds = normalizeTerminalIds(thread.terminalIds);
362
- const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
363
- ? thread.activeTerminalId
364
- : (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
365
- const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
366
- const activeGroupIndexFromId = terminalGroups.findIndex(
367
- (group) => group.id === thread.activeTerminalGroupId,
368
- );
369
- const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
370
- const activeGroupIndex =
371
- activeGroupIndexFromId >= 0
372
- ? activeGroupIndexFromId
373
- : activeGroupIndexFromTerminal >= 0
374
- ? activeGroupIndexFromTerminal
375
- : 0;
376
- const activeTerminalGroupId =
377
- terminalGroups[activeGroupIndex]?.id ??
378
- terminalGroups[0]?.id ??
379
- fallbackGroupId(activeTerminalId);
380
-
255
+function threadTerminalSlice(thread: Thread): ThreadTerminalState {
256
return {
382
- ...thread,
383
- terminalIds,
384
- runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
385
- activeTerminalId,
386
- terminalGroups,
387
- activeTerminalGroupId,
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
391
-function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
392
- if (!thread.terminalIds.includes(terminalId)) {
393
- return thread;
394
- }
395
-
396
- const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
397
- if (remainingTerminalIds.length === 0) {
398
- const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
399
- return normalizeThreadTerminals({
400
- ...thread,
401
- terminalOpen: false,
402
- terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
403
- runningTerminalIds: [],
404
- activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
405
- terminalGroups: [
406
- {
407
- id: nextTerminalGroupId,
408
- terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
409
- },
410
- ],
411
- activeTerminalGroupId: nextTerminalGroupId,
412
- });
413
- }
414
-
415
- const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
416
- const closedTerminalGroup = thread.terminalGroups.find((group) =>
417
- group.terminalIds.includes(terminalId),
418
- );
419
- const closedTerminalGroupIndex = closedTerminalGroup
420
- ? closedTerminalGroup.terminalIds.indexOf(terminalId)
421
- : -1;
422
- const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
423
- (id) => id !== terminalId,
424
- );
425
- const nextActiveTerminalId =
426
- thread.activeTerminalId === terminalId
427
- ? (remainingTerminalsInClosedGroup[
428
- Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
429
- ] ??
430
- remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
431
- remainingTerminalIds[0] ??
432
- DEFAULT_THREAD_TERMINAL_ID)
433
- : thread.activeTerminalId;
434
- const nextTerminalGroups = thread.terminalGroups
435
- .map((group) => ({
436
- ...group,
437
- terminalIds: group.terminalIds.filter((id) => id !== terminalId),
438
- }))
439
- .filter((group) => group.terminalIds.length > 0);
440
-
441
- return normalizeThreadTerminals({
442
- ...thread,
443
- terminalIds: remainingTerminalIds,
444
- runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
445
- activeTerminalId: nextActiveTerminalId,
446
- terminalGroups: nextTerminalGroups,
447
- });
267
+function applyTerminalState(thread: Thread, terminal: ThreadTerminalState): Thread {
268
+ return { ...thread, ...terminal };
269
}
270
450
-function setThreadTerminalActivity(
451
- thread: Thread,
452
- terminalId: string,
453
- hasRunningSubprocess: boolean,
454
-): Thread {
455
- const normalizedThread = normalizeThreadTerminals(thread);
456
- if (!normalizedThread.terminalIds.includes(terminalId)) {
457
- return normalizedThread;
458
- }
459
- const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
460
- if (hasRunningSubprocess) {
461
- runningTerminalIds.add(terminalId);
462
- } else {
463
- runningTerminalIds.delete(terminalId);
464
- }
465
- return normalizeThreadTerminals({
466
- ...normalizedThread,
467
- runningTerminalIds: [...runningTerminalIds],
468
- });
271
+function normalizeThreadTerminals(thread: Thread): Thread {
272
+ return applyTerminalState(thread, normalizeThreadTerminalState(threadTerminalSlice(thread)));
273
}
274
275
function syncServerReadModelState(state: AppState, readModel: OrchestrationReadModel): AppState {
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,
308
projectId: thread.projectId,
309
title: thread.title,
310
model: resolveModelSlug(thread.model),
503
- terminalOpen: existing?.terminalOpen ?? false,
504
- terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
505
- terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
506
- runningTerminalIds: existing?.runningTerminalIds ?? [],
507
- activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
508
- terminalGroups: existing?.terminalGroups ?? [
509
- {
510
- id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
511
- terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
512
- },
513
- ],
514
- activeTerminalGroupId:
515
- existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
311
+ ...terminalSlice,
312
session: thread.session
313
? {
314
sessionId:
374
return {
375
...state,
376
threads: updateThread(state.threads, action.threadId, (thread) =>
581
- normalizeThreadTerminals({
582
- ...thread,
583
- terminalOpen: action.terminalState.terminalOpen,
584
- terminalHeight: action.terminalState.terminalHeight,
585
- terminalIds: action.terminalState.terminalIds,
586
- runningTerminalIds: action.terminalState.runningTerminalIds,
587
- activeTerminalId: action.terminalState.activeTerminalId,
588
- terminalGroups: action.terminalState.terminalGroups,
589
- activeTerminalGroupId: action.terminalState.activeTerminalGroupId,
590
- }),
377
+ applyTerminalState(thread, normalizeThreadTerminalState(action.terminalState)),
378
),
379
};
380
435
return {
436
...state,
437
threads: updateThread(state.threads, action.threadId, (thread) =>
651
- setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
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
457
case "TOGGLE_THREAD_TERMINAL":
458
return {
459
...state,
666
- threads: updateThread(state.threads, action.threadId, (t) => ({
667
- ...t,
668
- terminalOpen: !t.terminalOpen,
669
- })),
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,
675
- threads: updateThread(state.threads, action.threadId, (t) => ({
676
- ...t,
677
- terminalOpen: action.open,
678
- })),
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,
686
- terminalHeight: action.height,
560
+ error: action.error,
561
})),
562
};
563
690
- case "SPLIT_THREAD_TERMINAL":
564
+ case "SET_THREAD_BRANCH": {
565
return {
566
...state,
693
- threads: updateThread(state.threads, action.threadId, (thread) => {
694
- const normalizedThread = normalizeThreadTerminals(thread);
695
- const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
696
- if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
697
- return normalizedThread;
698
- }
699
- const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
700
- ? normalizedThread.terminalIds
701
- : [...normalizedThread.terminalIds, action.terminalId];
702
- const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
703
- ...group,
704
- terminalIds: [...group.terminalIds],
705
- }));
706
- const normalizedMessage: ChatMessage = {
707
- id: message.id,
708
- role: message.role,
709
- text: message.text,
710
- createdAt: message.createdAt,
711
- streaming: message.streaming,
712
- ...(message.streaming ? {} : { completedAt: message.updatedAt }),
713
- ...(attachments && attachments.length > 0 ? { attachments } : {}),
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 } : {}),
577
};
578
return normalizedMessage;
579
}),