This repository was archived by the owner on Jun 24, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.store.ts
More file actions
13875 lines (13390 loc) · 492 KB
/
Copy pathapp.store.ts
File metadata and controls
13875 lines (13390 loc) · 492 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { toast } from "sonner";
import {
listActiveWorkspaceTurns,
listLatestWorkspaceTurns,
type PersistedTurnSummary,
} from "@/lib/db/turns.db";
import {
createNotification as createPersistedNotification,
listNotifications as listPersistedNotifications,
markAllNotificationsRead as markAllPersistedNotificationsRead,
markNotificationRead as markPersistedNotificationRead,
} from "@/lib/db/notifications.db";
import { workspaceFsAdapter } from "@/lib/fs";
import { formatWithEslint } from "@/components/layout/editor-language-intelligence";
import {
listWorkspaceSummaries,
loadWorkspaceEditorTabBodies,
loadTaskMessagesPage,
loadWorkspaceShell,
loadWorkspaceShellForRestore,
loadWorkspaceShellSummary,
loadWorkspaceSnapshot,
closeWorkspacePersistence,
loadProjectRegistrySnapshot,
saveProjectRegistrySnapshot,
type TaskProviderSessionState,
type WorkspaceShell,
type WorkspaceSummary,
} from "@/lib/db/workspaces.db";
import type { PersistenceBootstrapPhase } from "@/lib/persistence/bootstrap-status";
import type {
CanonicalRetrievedContextPart,
ClaudeSettingSource,
NormalizedProviderEvent,
ProviderId,
ProviderTurnRequest,
StaveAutoRoleRuntimeOverridesMap,
} from "@/lib/providers/provider.types";
import type { ConnectedToolStatusEntry } from "@/lib/providers/connected-tool-status";
import { getRepoMapContextCache } from "@/lib/fs/repo-map-context-cache";
import { buildCurrentTaskAwarenessRetrievedContext } from "@/lib/task-context/current-task-awareness";
import { buildReferencedTaskRetrievedContext } from "@/lib/task-context/referenced-task-context";
import {
buildWorkspaceContinueSummaryFilePath,
buildWorkspaceContinueSummaryMarkdown,
} from "@/lib/workspace-continue";
import type { ScriptTrigger } from "@/lib/workspace-scripts";
import type {
AppNotification,
AppNotificationCreateInput,
} from "@/lib/notifications/notification.types";
import {
isNotificationUnread,
sortNotificationsNewestFirst,
workspaceHasActiveTurns,
} from "@/lib/notifications/notification.types";
import { buildNotificationToastOptions } from "@/lib/notifications/notification.utils";
import {
DEFAULT_NOTIFICATION_SOUND_PRESET,
DEFAULT_NOTIFICATION_SOUND_MODE,
DEFAULT_NOTIFICATION_SOUND_VOLUME,
normalizeNotificationSoundMode,
normalizeNotificationSoundPreset,
normalizeNotificationSoundVolume,
playCustomNotificationSound,
playNotificationSound,
type NotificationSoundMode,
type NotificationSoundPreset,
} from "@/lib/notifications/notification-sound";
import { buildCanonicalConversationRequest } from "@/lib/providers/canonical-request";
import {
getDefaultModelForProvider,
inferProviderIdFromModel,
listProviderIds,
normalizeModelSelection,
upgradeSettingsScopedClaudeOpusModel,
} from "@/lib/providers/model-catalog";
import { normalizeModelShortcutKeys } from "@/lib/providers/model-shortcuts";
import {
DEFAULT_APP_SHORTCUT_KEYS,
normalizeAppShortcutKeys,
type AppShortcutKeys,
} from "@/lib/app-shortcuts";
import {
DEFAULT_PROMPT_RESPONSE_STYLE,
DEFAULT_PROMPT_PR_DESCRIPTION,
DEFAULT_PROMPT_SUPERVISOR_BREAKDOWN,
DEFAULT_PROMPT_SUPERVISOR_SYNTHESIS,
DEFAULT_PROMPT_PREPROCESSOR_CLASSIFIER,
DEFAULT_PROMPT_INLINE_COMPLETION,
DEFAULT_PROMPT_WORKSPACE_TURN_SUMMARY,
normalizeResponseStylePrompt,
} from "@/lib/providers/prompt-defaults";
import {
normalizeThinkingPhraseAnimationStyle,
type ThinkingPhraseAnimationStyle,
} from "@/lib/thinking-phrases";
import {
buildStaveAutoModelSettingsPatch,
createDefaultStaveAutoRoleRuntimeOverrides,
DEFAULT_STAVE_AUTO_MODEL_PRESET_ID,
normalizeStaveAutoRoleRuntimeOverrides,
} from "@/lib/providers/stave-auto-profile";
import {
canTakeOverTask,
getArchiveFallbackTaskId,
isTaskArchived,
isTaskManaged,
normalizeSuggestedTaskTitle,
reorderTasksWithinFilter,
type TaskFilter,
} from "@/lib/tasks";
import {
cloneDefaultTaskPresets,
normalizePersistedTaskPresets,
type TaskPreset,
} from "@/lib/task-presets";
import {
DEFAULT_TERMINAL_FONT_FAMILY,
DEFAULT_TERMINAL_FONT_SIZE,
LEGACY_TERMINAL_FONT_FAMILY,
} from "@/lib/terminal/defaults";
import {
getCliSessionTabDefaultTitle,
getTerminalTabDefaultTitle,
buildTerminalSessionSlotKey,
type CliSessionContextMode,
type WorkspaceActiveSurface,
type WorkspaceCliSessionTab,
type WorkspaceTerminalTab,
} from "@/lib/terminal/types";
import { resolveSkillSelections } from "@/lib/skills/catalog";
import type { SkillCatalogEntry, SkillCatalogRoot } from "@/lib/skills/types";
import { replayProviderEventsToTaskState } from "@/lib/session/provider-event-replay";
import {
DEFAULT_PROVIDER_TIMEOUT_MS,
PROVIDER_TIMEOUT_OPTIONS,
} from "@/lib/providers/runtime-option-contract";
import {
applyProviderTurnActivityEvents,
clearProviderTurnActivity,
markProviderTurnInteractionResolved,
markProviderTurnStalled,
resolveProviderTurnStallThresholdMs,
startProviderTurnActivity,
type ProviderTurnActivitySnapshot,
} from "@/lib/providers/turn-status";
import { resolveWorkspaceRelativeFilePath } from "@/lib/workspace-file-path";
import {
createEmptyWorkspaceInformation,
createWorkspaceConfluencePage,
createWorkspaceFigmaResource,
createWorkspaceInfoCustomField,
createWorkspaceJiraIssue,
createWorkspaceLinkedPullRequest,
createWorkspaceSlackThread,
createWorkspaceTodoItem,
type WorkspaceInformationState,
} from "@/lib/workspace-information";
import {
buildWorkspaceTurnSummaryPrompt,
createWorkspaceTurnSummary,
parseWorkspaceTurnSummaryResponse,
} from "@/lib/workspace-turn-summary";
import {
buildStaveMuseContextSnapshot,
buildStaveMuseLocalActionResponse,
buildStaveMuseSummaryResponse,
createEmptyStaveMuseState,
findStaveMuseWorkspaceMention,
getStaveMuseRuntimeCwd,
formatStaveMuseTargetLabel,
resolveStaveMuseLocalAction,
STAVE_MUSE_SESSION_ID,
type StaveMuseDefaultTarget,
type StaveMuseLocalAction,
type StaveMuseLocalActionContext,
type StaveMuseProjectSummary,
type StaveMuseState,
type StaveMuseTaskSummary,
type StaveMuseWorkspaceSummary,
} from "@/lib/stave-muse";
import {
buildStaveMuseInstructionContextPart,
buildStaveMuseRouterPrompt,
DEFAULT_STAVE_MUSE_CHAT_PROMPT,
DEFAULT_STAVE_MUSE_PLANNER_PROMPT,
DEFAULT_STAVE_MUSE_ROUTER_PROMPT,
} from "@/lib/stave-muse-prompts";
import {
buildStaveMuseConnectedToolPreflightMessage,
buildStaveMuseProviderUnavailableMessage,
resolveRequestedStaveMuseConnectedTools,
} from "@/lib/stave-muse-connected-tools";
import {
DEFAULT_STAVE_MUSE_ROUTING_DECISION,
isStaveMuseExplicitTaskRequest,
parseStaveMuseRoutingDecision,
resolveStaveMuseFastPathDecision,
type StaveMuseRoutingDecision,
} from "@/lib/stave-muse-routing";
import {
findLatestPendingApproval,
findLatestPendingApprovalPart,
findLatestPendingUserInput,
findPendingApprovalMessageByRequestId,
findLatestPendingUserInputPart,
interruptPendingToolInteractionsInMessages,
updateApprovalPartsByRequestId,
updateUserInputPartsByRequestId,
} from "@/store/provider-message.utils";
import {
applyProjectBasePromptToRuntimeOptions,
buildProviderRuntimeOptions,
normalizeClaudeSettingSources,
normalizeClaudeTaskBudgetTokens,
normalizeCodexApprovalPolicy,
} from "@/store/provider-runtime-options";
import {
buildMessageId,
buildPendingProviderTurnState,
buildRecentTimestamp,
createFileContextPart,
createUserTextPart,
} from "@/store/chat-state-helpers";
import {
createProviderTurnEventController,
runProviderTurn,
} from "@/store/provider-turn-runtime";
import {
buildColiseumMergedFollowUp,
buildReviewerPrompt,
clearReviewerFromGroup,
collectActiveColiseumTaskIds,
extractBranchSummary,
planColiseumFanOut,
planReviewerLaunch,
promoteColiseumChampion,
stripColiseumBranchesFromRecords,
unpickColiseumChampion as unpickColiseumChampionUtil,
validateColiseumBranches,
type ColiseumBranchSpec,
} from "@/store/coliseum.utils";
import {
applyPendingProviderEventsToStoreState,
createWorkspaceSessionStateFromAppState,
saveActiveWorkspaceRuntimeCache,
} from "@/store/workspace-runtime-state";
import type {
Attachment,
ChatMessage,
ClaudePermissionMode,
ClaudePermissionModeBeforePlan,
ColiseumGroupState,
ColiseumReviewerVerdict,
EditorTab,
PromptDraft,
Task,
} from "@/types/chat";
import {
arePromptDraftRuntimeOverridesEqual,
resolvePromptDraftModelForProvider,
resolvePromptDraftRuntimeState,
} from "@/store/prompt-draft-runtime";
import {
resolveWorkspacePlanPersistenceText,
persistWorkspacePlanFile,
} from "@/lib/plans";
import {
appendInterruptedTurnNotices,
buildWorkspaceSessionStateFromShell,
buildWorkspaceSessionState,
createEmptyWorkspaceState,
createWorkspaceSnapshot,
defaultWorkspaceName,
interruptActiveTaskTurns,
persistWorkspaceSnapshot,
scheduleWorkspaceSnapshotPersist,
starterWorkspaceId,
type WorkspaceSessionState,
} from "@/store/workspace-session-state";
import {
TASK_MESSAGES_PAGE_SIZE,
resolveInitialLatestTaskMessagesPageSize,
} from "@/store/task-message-loading";
import {
normalizeComparablePath,
parseGitWorktrees,
} from "@/lib/source-control-worktrees";
import {
type LayoutState,
WORKSPACE_SIDEBAR_MIN_WIDTH,
MIN_EDITOR_PANEL_WIDTH,
DEFAULT_EDITOR_PANEL_WIDTH,
mergeLayoutPatch,
normalizeLayoutState,
isDiffEditorTab,
resolveEditorDiffMode,
} from "@/store/layout.utils";
import {
type ThemeTokenName,
type ThemeModeName,
type ThemeTokenValues,
type ThemeOverrideValues,
type CustomThemeDefinition,
type SidebarArtworkMode,
THEME_TOKEN_NAMES,
PRESET_THEME_TOKENS,
BUILTIN_CUSTOM_THEMES,
DEFAULT_SIDEBAR_ARTWORK_MODE,
applyThemeClass,
applyThemeOverrides,
applyCustomTheme,
applyFontOverrides,
resolveDarkModeForTheme,
findCustomThemeById,
listAllCustomThemes,
MAX_USER_THEMES,
normalizeSidebarArtworkMode,
SIDEBAR_ARTWORK_OPTIONS,
} from "@/lib/themes";
import {
type RecentProjectState,
normalizeProjectBasePrompt,
normalizeWorkspaceInitCommand,
normalizeProjectWorkspaceInitCommand,
normalizeProjectWorkspaceRootNodeModulesSymlinkPreference,
resolveProjectBasePrompt,
resolveProjectWorkspaceInitCommand,
resolveProjectWorkspaceRootNodeModulesSymlinkPreference,
summarizeTerminalCommandDetail,
summarizeWorkspaceInitCommand,
buildWorkspaceRootNodeModulesSymlinkCommand,
buildWorkspaceCreationNotice,
isDefaultWorkspaceName,
registerTaskWorkspaceOwnership,
retainTaskWorkspaceOwnership,
resolveWorkspaceName,
removeWorkspaceRuntimeCacheEntries,
areStringArraysEqual,
moveArrayItem,
sanitizeBranchName,
toWorkspaceFolderName,
resolveProjectNameFromPath,
normalizeProjectDisplayName,
hashProjectPath,
buildProjectDefaultWorkspaceId,
buildImportedWorktreeWorkspaceId,
resolveImportedWorktreeName,
resolveCurrentProjectDefaultWorkspaceId,
normalizeCurrentProjectState,
cloneRecentProjectState,
normalizeRecentProjectStates,
upsertRecentProjectState,
captureCurrentProjectState,
resolveProjectForWorkspaceId,
resolveWorkspaceRemoteBaseBranchTarget,
resolveTaskWorkspaceContext,
} from "@/store/project.utils";
import {
type WorkspacePrInfo,
type GitHubPrPayload,
derivePrStatus,
} from "@/lib/pr-status";
import {
resolveLanguage,
normalizeProviderTimeoutMs,
isImageFilePath,
canSendEditorContextToTask,
canSendWorkspaceFileToTask,
updateMessageById,
applyApprovalState,
applyUserInputState,
} from "@/store/editor.utils";
const LOCAL_ABORT_SYSTEM_EVENT_CONTENT =
"Generation was stopped locally before completion.";
export {
WORKSPACE_SIDEBAR_MIN_WIDTH,
MIN_EDITOR_PANEL_WIDTH,
DEFAULT_EDITOR_PANEL_WIDTH,
} from "@/store/layout.utils";
export type { LayoutState } from "@/store/layout.utils";
export type AppShellMode = "stave" | "zen";
export {
THEME_TOKEN_NAMES,
PRESET_THEME_TOKENS,
BUILTIN_CUSTOM_THEMES,
MAX_USER_THEMES,
SIDEBAR_ARTWORK_OPTIONS,
} from "@/lib/themes";
export {
parseCustomThemeFile,
exportCustomThemeJson,
listAllCustomThemes,
} from "@/lib/themes";
export type {
ThemeTokenName,
ThemeModeName,
ThemeTokenValues,
ThemeOverrideValues,
CustomThemeDefinition,
SidebarArtworkMode,
ThemeValidationResult,
} from "@/lib/themes";
export type { RecentProjectState } from "@/store/project.utils";
type NotificationContextOpenResult =
| { status: "opened" }
| { status: "archived-task"; taskId: string; taskTitle: string };
interface WorkspaceSwitchMetric {
token: number;
startedAt: number;
cacheHit: boolean;
shellResolvedAt?: number;
setRootResolvedAt?: number;
}
interface SkillCatalogState {
status: "idle" | "loading" | "ready" | "error";
workspacePath: string | null;
sharedSkillsHome: string | null;
fetchedAt: string | null;
skills: SkillCatalogEntry[];
roots: SkillCatalogRoot[];
detail: string;
}
type SendUserMessageResult =
| { status: "blocked" }
| { status: "queued"; taskId: string; workspaceId: string }
| { status: "started"; taskId: string; workspaceId: string; turnId: string };
type StartColiseumResult =
| { status: "blocked"; reason: string }
| {
status: "started";
parentTaskId: string;
workspaceId: string;
branchTaskIds: string[];
};
const APP_STORE_KEY = "stave-store";
const EMPTY_PROMPT_DRAFT: PromptDraft = {
text: "",
attachedFilePaths: [],
attachments: [],
};
const workspaceSwitchMetricsByWorkspaceId = new Map<
string,
WorkspaceSwitchMetric
>();
let workspaceSwitchMetricTokenCounter = 0;
export {
DEFAULT_PROVIDER_TIMEOUT_MS,
PROVIDER_TIMEOUT_OPTIONS,
} from "@/lib/providers/runtime-option-contract";
function hasPromptDraftPayload(
draft: Pick<PromptDraft, "text" | "attachedFilePaths" | "attachments">,
) {
return (
draft.text.trim().length > 0 ||
draft.attachedFilePaths.length > 0 ||
draft.attachments.length > 0
);
}
function buildClearedPromptDraft(draft?: PromptDraft | null): PromptDraft {
return {
text: "",
attachedFilePaths: [],
attachments: [],
...(draft?.runtimeOverrides
? { runtimeOverrides: draft.runtimeOverrides }
: {}),
};
}
function normalizePromptDraftForStorage(draft: PromptDraft): PromptDraft {
if (hasPromptDraftPayload(draft) || !draft.queuedNextTurn) {
return draft;
}
if (draft.queuedNextTurn.content?.trim()) {
return draft;
}
const { queuedNextTurn: _unused, ...nextDraft } = draft;
return nextDraft;
}
function arePromptDraftQueuedNextTurnEqual(
left?: PromptDraft["queuedNextTurn"],
right?: PromptDraft["queuedNextTurn"],
) {
return (
left?.queuedAt === right?.queuedAt &&
left?.sourceTurnId === right?.sourceTurnId &&
left?.content === right?.content
);
}
/**
* Mirror the reviewer task's assistant message text into the group's
* `reviewerVerdict.content` so the arena's ColiseumReviewerCard can subscribe
* directly to `group.reviewerVerdict` — the reviewer task is hidden from the
* task tree by `coliseumParentTaskId` and never rendered as a chat column, so
* its messages record must be translated back onto the parent-scoped group
* state. Also drives the `running` → `complete` / `error` transition.
*
* Called from the reviewer's flushEvents callback AFTER
* `applyPendingProviderEventsToStoreState` so we read the already-applied
* assistant text from `state.messagesByTask[reviewerTaskId]`.
*
* Keeping this in its own helper keeps the launch action readable and means
* tests can exercise mirroring logic without the full dispatch path later.
*/
function mirrorReviewerVerdict(args: {
set: (updater: (state: AppState) => Partial<AppState>) => void;
get: () => AppState;
parentTaskId: string;
reviewerTaskId: string;
workspaceId: string;
pendingEvents: NormalizedProviderEvent[];
}) {
const state = args.get();
const sessionMessages =
state.activeWorkspaceId === args.workspaceId
? state.messagesByTask
: state.workspaceRuntimeCacheById[args.workspaceId]?.messagesByTask;
if (!sessionMessages) return;
const messages = sessionMessages[args.reviewerTaskId] ?? [];
const assistant = [...messages].reverse().find((m) => m.role === "assistant");
const accumulatedText =
assistant?.parts
.filter(
(p): p is Extract<typeof p, { type: "text" }> => p.type === "text",
)
.map((p) => p.text)
.join("") ?? "";
const group =
state.activeWorkspaceId === args.workspaceId
? state.activeColiseumsByTask[args.parentTaskId]
: state.workspaceRuntimeCacheById[args.workspaceId]
?.activeColiseumsByTask[args.parentTaskId];
if (!group || !group.reviewerVerdict) return;
// Detect lifecycle transitions by inspecting the events we just applied.
const sawError = args.pendingEvents.some((event) => event.type === "error");
const sawDone = args.pendingEvents.some((event) => event.type === "done");
const nextStatus: ColiseumReviewerVerdict["status"] = sawError
? "error"
: sawDone
? "complete"
: group.reviewerVerdict.status;
const nextCompletedAt =
(sawDone || sawError) && !group.reviewerVerdict.completedAt
? buildRecentTimestamp()
: group.reviewerVerdict.completedAt;
const errorEvent = args.pendingEvents.find(
(event): event is Extract<NormalizedProviderEvent, { type: "error" }> =>
event.type === "error",
);
const errorMessage = sawError
? (errorEvent?.message ??
group.reviewerVerdict.errorMessage ??
"Reviewer failed.")
: group.reviewerVerdict.errorMessage;
const nextVerdict: ColiseumReviewerVerdict = {
...group.reviewerVerdict,
content: accumulatedText,
status: nextStatus,
...(nextCompletedAt ? { completedAt: nextCompletedAt } : {}),
...(errorMessage ? { errorMessage } : {}),
};
// Skip the set if nothing actually changed to keep subscribers quiet.
if (
nextVerdict.content === group.reviewerVerdict.content &&
nextVerdict.status === group.reviewerVerdict.status &&
nextVerdict.completedAt === group.reviewerVerdict.completedAt &&
nextVerdict.errorMessage === group.reviewerVerdict.errorMessage
) {
return;
}
const nextGroup: ColiseumGroupState = {
...group,
reviewerVerdict: nextVerdict,
};
args.set((current) => {
if (args.workspaceId === current.activeWorkspaceId) {
return {
activeColiseumsByTask: {
...current.activeColiseumsByTask,
[args.parentTaskId]: nextGroup,
},
} as Partial<AppState>;
}
const cached = current.workspaceRuntimeCacheById[args.workspaceId];
if (!cached) return current;
return {
workspaceRuntimeCacheById: {
...current.workspaceRuntimeCacheById,
[args.workspaceId]: {
...cached,
activeColiseumsByTask: {
...cached.activeColiseumsByTask,
[args.parentTaskId]: nextGroup,
},
},
},
} as Partial<AppState>;
});
}
function resolveTaskRuntimeTarget(args: {
state: Pick<
AppState,
| "activeTaskId"
| "activeWorkspaceId"
| "taskWorkspaceIdById"
| "tasks"
| "workspaceRuntimeCacheById"
| "messagesByTask"
| "messageCountByTask"
| "promptDraftByTask"
| "workspaceInformation"
| "editorTabs"
| "activeEditorTabId"
| "terminalTabs"
| "activeTerminalTabId"
| "layout"
| "cliSessionTabs"
| "activeCliSessionTabId"
| "activeSurface"
| "activeTurnIdsByTask"
| "providerSessionByTask"
| "nativeSessionReadyByTask"
| "activeColiseumsByTask"
>;
taskId: string;
}) {
const activeTask =
args.state.tasks.find((task) => task.id === args.taskId) ?? null;
if (activeTask) {
return {
workspaceId: args.state.activeWorkspaceId,
isActiveWorkspace: true,
session: createWorkspaceSessionStateFromAppState(args.state),
task: activeTask,
};
}
const mappedWorkspaceId = args.state.taskWorkspaceIdById[args.taskId];
if (mappedWorkspaceId && mappedWorkspaceId !== args.state.activeWorkspaceId) {
const mappedSession =
args.state.workspaceRuntimeCacheById[mappedWorkspaceId];
const mappedTask =
mappedSession?.tasks.find((task) => task.id === args.taskId) ?? null;
if (mappedSession && mappedTask) {
return {
workspaceId: mappedWorkspaceId,
isActiveWorkspace: false,
session: mappedSession,
task: mappedTask,
};
}
}
for (const [workspaceId, session] of Object.entries(
args.state.workspaceRuntimeCacheById,
)) {
const task =
session.tasks.find((candidate) => candidate.id === args.taskId) ?? null;
if (task) {
return {
workspaceId,
isActiveWorkspace: false,
session,
task,
};
}
}
return null;
}
function getWorkspaceSessionForState(args: {
state: Pick<
AppState,
| "activeTaskId"
| "activeWorkspaceId"
| "tasks"
| "messagesByTask"
| "messageCountByTask"
| "promptDraftByTask"
| "workspaceInformation"
| "editorTabs"
| "activeEditorTabId"
| "terminalTabs"
| "activeTerminalTabId"
| "layout"
| "cliSessionTabs"
| "activeCliSessionTabId"
| "activeSurface"
| "activeTurnIdsByTask"
| "providerSessionByTask"
| "nativeSessionReadyByTask"
| "activeColiseumsByTask"
| "workspaceRuntimeCacheById"
>;
workspaceId: string;
}) {
if (args.workspaceId === args.state.activeWorkspaceId) {
return createWorkspaceSessionStateFromAppState(args.state);
}
return args.state.workspaceRuntimeCacheById[args.workspaceId] ?? null;
}
function getDraftImageContexts(args: {
promptDraft: PromptDraft;
imageContexts?: Array<{
dataUrl: string;
label: string;
mimeType: string;
}>;
}): Array<{
dataUrl: string;
label: string;
mimeType: string;
}> {
if ((args.imageContexts?.length ?? 0) > 0) {
return args.imageContexts ?? [];
}
return args.promptDraft.attachments
.filter(
(attachment): attachment is Extract<Attachment, { kind: "image" }> =>
attachment.kind === "image",
)
.map((attachment) => ({
dataUrl: attachment.dataUrl,
label: attachment.label,
mimeType: "image/png",
}));
}
async function getDraftFileContexts(args: {
promptDraft: PromptDraft;
session: Pick<WorkspaceSessionState, "editorTabs">;
workspaceRootPath?: string | null;
fileContexts?: Array<{
filePath: string;
content: string;
language: string;
instruction?: string;
}>;
}): Promise<
Array<{
filePath: string;
content: string;
language: string;
instruction?: string;
}>
> {
if ((args.fileContexts?.length ?? 0) > 0) {
return args.fileContexts ?? [];
}
if (args.promptDraft.attachedFilePaths.length === 0) {
return [];
}
const nextFileContexts: Array<{
filePath: string;
content: string;
language: string;
instruction?: string;
}> = [];
const seenFilePaths = new Set<string>();
const readFile = window.api?.fs?.readFile;
for (const filePath of args.promptDraft.attachedFilePaths) {
if (!filePath || seenFilePaths.has(filePath)) {
continue;
}
seenFilePaths.add(filePath);
const openTab = args.session.editorTabs.find(
(tab) => tab.filePath === filePath && tab.kind !== "image",
);
if (openTab) {
nextFileContexts.push({
filePath: openTab.filePath,
content: openTab.content,
language: openTab.language,
});
continue;
}
if (!args.workspaceRootPath || !readFile) {
continue;
}
const result = await readFile({
rootPath: args.workspaceRootPath,
filePath,
});
if (!result.ok) {
continue;
}
nextFileContexts.push({
filePath,
content: result.content,
language: resolveLanguage({ filePath }),
});
}
return nextFileContexts;
}
function isWorkspaceSwitchMetricLoggingEnabled() {
return (
typeof import.meta !== "undefined" &&
Boolean((import.meta as ImportMeta & { env?: { DEV?: boolean } }).env?.DEV)
);
}
function getWorkspaceSwitchMetricNow() {
return typeof performance !== "undefined" &&
typeof performance.now === "function"
? performance.now()
: Date.now();
}
function roundWorkspaceSwitchDuration(value: number) {
return Math.round(value * 100) / 100;
}
function registerWorkspaceSwitchMetric(args: {
workspaceId: string;
metric: WorkspaceSwitchMetric;
}) {
if (!isWorkspaceSwitchMetricLoggingEnabled()) {
return;
}
workspaceSwitchMetricsByWorkspaceId.set(args.workspaceId, args.metric);
}
function logWorkspaceSwitchMetric(args: {
workspaceId: string;
token?: number;
phase: "active" | "files" | "messages";
extra?: Record<string, unknown>;
}) {
if (!isWorkspaceSwitchMetricLoggingEnabled()) {
return;
}
const metric = workspaceSwitchMetricsByWorkspaceId.get(args.workspaceId);
if (!metric || (args.token !== undefined && metric.token !== args.token)) {
return;
}
const now = getWorkspaceSwitchMetricNow();
console.info("[workspace-switch]", {
workspaceId: args.workspaceId,
phase: args.phase,
cacheHit: metric.cacheHit,
totalMs: roundWorkspaceSwitchDuration(now - metric.startedAt),
...(metric.shellResolvedAt !== undefined
? {
shellMs: roundWorkspaceSwitchDuration(
metric.shellResolvedAt - metric.startedAt,
),
}
: {}),
...(metric.setRootResolvedAt !== undefined
? {
setRootMs: roundWorkspaceSwitchDuration(
metric.setRootResolvedAt - metric.startedAt,
),
}
: {}),
...(args.extra ?? {}),
});
}
export interface AppSettings {
appShellMode: AppShellMode;
showPresetBar: boolean;
themeMode: "light" | "dark" | "system";
/** ID of the active custom theme preset, or `null` for the default. */
customThemeId: string | null;
/** Ambient artwork rendered behind the left project sidebar glass. */
sidebarArtworkMode: SidebarArtworkMode;
/**
* When `true`, an animated "border beam" highlight travels around the
* prompt input and active-workspace rows while a task is streaming. Purely
* decorative — honors `prefers-reduced-motion`.
*/
borderBeamEnabled: boolean;
/**
* Size preset passed to the `border-beam` library. `md` is a full border
* glow (default), `sm` is a compact button-sized glow, `line` traces a
* bottom-only sweep with breathe/spike animations.
*/
borderBeamSize: "sm" | "md" | "line";
/**
* Color palette preset passed to the `border-beam` library. These are the
* library's own presets — do not remap onto our theme tokens.
*/
borderBeamVariant: "colorful" | "mono" | "ocean" | "sunset";
/** User-installed custom theme definitions (persisted in localStorage). */
userCustomThemes: CustomThemeDefinition[];
themeOverrides: Record<ThemeModeName, ThemeOverrideValues>;
language: string;
updateMode: "auto" | "manual";
httpProxy: string;
smartSuggestions: boolean;
chatSendPreview: boolean;
chatStreamingEnabled: boolean;
messageFontSize: number;
messageCodeFontSize: number;
messageFontFamily: string;
messageMonoFontFamily: string;
messageKoreanFontFamily: string;
/** Zoom scale for the workspace information panel (0.8 – 1.3, default 1). */
infoPanelScale: number;
reasoningExpansionMode: "auto" | "manual";
showInterimMessages: boolean;
thinkingPhraseAnimationStyle: ThinkingPhraseAnimationStyle;
claudeFastModeVisible: boolean;
codexFastModeVisible: boolean;
modelClaude: string;
modelCodex: string;
modelStave: string;
/**
* User-configurable presets rendered in the preset bar between the task
* tab strip and the chat panel. Each preset either seeds a new task with a
* fixed provider + model, or launches a native CLI session.
*/
taskPresets: TaskPreset[];
/** Role-based defaults used by Stave Auto. */
staveAutoClassifierModel: string;
staveAutoSupervisorModel: string;
staveAutoPlanModel: string;
staveAutoAnalyzeModel: string;
staveAutoImplementModel: string;
staveAutoQuickEditModel: string;
staveAutoGeneralModel: string;
staveAutoVerifyModel: string;
staveAutoOrchestrationMode: "off" | "auto" | "aggressive";
staveAutoMaxSubtasks: number;
staveAutoMaxParallelSubtasks: number;
staveAutoAllowCrossProviderWorkers: boolean;
staveAutoFastMode: boolean;
staveAutoRoleRuntimeOverrides: StaveAutoRoleRuntimeOverridesMap;
/** Control-plane defaults used by the global Stave Muse widget. */
museDefaultTarget: StaveMuseDefaultTarget;
museRouterModel: string;
museChatModel: string;
musePlannerModel: string;
museRouterPrompt: string;
museChatPrompt: string;
musePlannerPrompt: string;
museAutoHandoffToTask: boolean;
museAllowDirectWorkspaceInfoEdits: boolean;
rulesPresetPrimary: string;
rulesPresetSecondary: string;
permissionMode: "require-approval" | "auto-safe";
subagentsEnabled: boolean;
subagentsProfile: string;
skillsEnabled: boolean;
skillsAutoSuggest: boolean;
sharedSkillsHome: string;
commandPaletteShowRecent: boolean;
commandPalettePinnedCommandIds: string[];
commandPaletteHiddenCommandIds: string[];
commandPaletteRecentCommandIds: string[];
/** Cmd/Ctrl+K shell chord bindings for navigation and panel actions. */
appShortcutKeys: AppShortcutKeys;
/** Alt+1..0 prompt-model bindings, stored as `provider:model` keys. */
modelShortcutKeys: string[];
reviewStrictMode: boolean;
reviewChecklistPreset: string;
terminalFontSize: number;
terminalFontFamily: string;
terminalCursorStyle: "block" | "bar" | "underline";
terminalLineHeight: number;
editorFontSize: number;
editorFontFamily: string;
editorWordWrap: boolean;
editorMinimap: boolean;