-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathuseDesktopState.ts
More file actions
5734 lines (5098 loc) · 207 KB
/
Copy pathuseDesktopState.ts
File metadata and controls
5734 lines (5098 loc) · 207 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 { computed, ref } from 'vue'
import {
archiveThread,
forkThread,
getAvailableCollaborationModes,
getAccountRateLimits,
renameThread,
getAvailableModelIds,
getCurrentModelConfig,
getPendingServerRequests,
getSkillsList,
getThreadDetail,
getOlderThreadMessages,
getBackgroundThreadListLimit,
interruptThreadTurn,
pickCodexRateLimitSnapshot,
replyToServerRequest,
revertThreadFileChanges,
rollbackThread,
getThreadGroupsPage,
getThreadQueueState,
getWorkspaceRootsState,
setCodexSpeedMode,
setThreadQueueState,
setWorkspaceRootsState,
getThreadTitleCache,
persistThreadTitle,
generateThreadTitle,
resumeThread,
startThread,
subscribeCodexNotifications,
startThreadTurn,
type RpcNotification,
type SkillInfo,
type ThreadQueueState,
type WorkspaceRootsState,
} from '../api/codexGateway'
import { CodexApiError } from '../api/codexErrors'
import { normalizeFileChangeStatus, toUiFileChanges } from '../api/normalizers/v2'
import { REASONING_EFFORTS } from '../types/codex'
import type {
CollaborationModeKind,
CollaborationModeOption,
CommandExecutionData,
UiPendingRequestState,
ReasoningEffort,
SpeedMode,
UiFileChange,
UiLiveOverlay,
UiMessage,
UiPlanData,
UiPlanStep,
UiProjectGroup,
UiRateLimitSnapshot,
UiServerRequest,
UiServerRequestReply,
UiThreadTokenUsage,
UiTokenUsageBreakdown,
UiThread,
} from '../types/codex'
import { getPathParent, isProjectlessChatPath, normalizePathForUi, toProjectName } from '../pathUtils.js'
function flattenThreads(groups: UiProjectGroup[]): UiThread[] {
return groups.flatMap((group) => group.threads)
}
export function findAdjacentThreadId(threads: UiThread[], threadId: string): string {
const targetIndex = threads.findIndex((thread) => thread.id === threadId)
if (targetIndex < 0) return ''
return threads[targetIndex + 1]?.id ?? threads[targetIndex - 1]?.id ?? ''
}
const READ_STATE_STORAGE_KEY = 'codex-web-local.thread-read-state.v1'
const UNREAD_CUTOFF_STORAGE_KEY = 'codex-web-local.thread-unread-cutoff.v1'
const THREAD_TOKEN_USAGE_STORAGE_KEY = 'codex-web-local.thread-token-usage.v1'
const THREAD_TERMINAL_OPEN_STORAGE_KEY = 'codex-web-local.thread-terminal-open.v1'
const SELECTED_THREAD_STORAGE_KEY = 'codex-web-local.selected-thread-id.v1'
const SELECTED_MODEL_BY_CONTEXT_STORAGE_KEY = 'codex-web-local.selected-model-by-context.v1'
const LEGACY_SELECTED_MODEL_STORAGE_KEY = 'codex-web-local.selected-model-id.v1'
const PROJECT_ORDER_STORAGE_KEY = 'codex-web-local.project-order.v1'
const PROJECT_DISPLAY_NAME_STORAGE_KEY = 'codex-web-local.project-display-name.v1'
const COLLABORATION_MODE_STORAGE_KEY = 'codex-web-local.collaboration-mode-by-context.v1'
const LEGACY_COLLABORATION_MODE_STORAGE_KEY = 'codex-web-local.collaboration-mode.v1'
const NEW_THREAD_COLLABORATION_MODE_CONTEXT = '__new-thread__'
const NEW_THREAD_PROVIDER_MODEL_CONTEXT_PREFIX = '__new-thread-provider__::'
const EVENT_SYNC_DEBOUNCE_MS = 220
const BACKGROUND_THREAD_PAGINATION_DELAY_MS = 10_000
const RATE_LIMIT_REFRESH_DEBOUNCE_MS = 500
const TURN_START_FOLLOW_UP_SYNC_DELAY_MS = 3000
const RECENT_THREAD_MESSAGE_LOAD_REUSE_MS = 2000
const RECENT_THREAD_LIST_LOAD_REUSE_MS = 2000
const RECENT_SKILLS_LOAD_REUSE_MS = 2000
const REASONING_EFFORT_OPTIONS: readonly ReasoningEffort[] = REASONING_EFFORTS
const GLOBAL_SERVER_REQUEST_SCOPE = '__global__'
const MODEL_FALLBACK_ID = 'gpt-5.4-mini'
const OPENCODE_ZEN_DEFAULT_MODEL = 'big-pickle'
const CODEX_CLI_MISSING_MESSAGE = 'Codex CLI not found. Install @openai/codex or set CODEXUI_CODEX_COMMAND.'
type SelectThreadResult = 'ok' | 'not-found' | 'error'
function isCodexCliMissingError(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error ?? '')
return message.includes('Codex CLI is not available')
}
function isThreadNotFoundError(error: unknown): boolean {
if (error instanceof CodexApiError && error.status === 404) return true
const message = error instanceof Error ? error.message : String(error ?? '')
return /\b404\b|thread.*not found|conversation.*not found|no such thread|no rollout found for thread id/i.test(message)
}
function loadReadStateMap(): Record<string, string> {
if (typeof window === 'undefined') return {}
try {
const raw = window.localStorage.getItem(READ_STATE_STORAGE_KEY)
if (!raw) return {}
const parsed = JSON.parse(raw) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
return parsed as Record<string, string>
} catch {
return {}
}
}
function saveReadStateMap(state: Record<string, string>): void {
if (typeof window === 'undefined') return
window.localStorage.setItem(READ_STATE_STORAGE_KEY, JSON.stringify(state))
}
function loadUnreadCutoffIso(): string {
if (typeof window === 'undefined') return ''
const existing = window.localStorage.getItem(UNREAD_CUTOFF_STORAGE_KEY)
if (existing) return existing
const initialCutoff = new Date().toISOString()
window.localStorage.setItem(UNREAD_CUTOFF_STORAGE_KEY, initialCutoff)
return initialCutoff
}
function saveUnreadCutoffIso(cutoffIso: string): void {
if (typeof window === 'undefined') return
window.localStorage.setItem(UNREAD_CUTOFF_STORAGE_KEY, cutoffIso)
}
function isThreadUpdatedAfterCutoff(updatedAtIso: string, cutoffIso: string): boolean {
if (!updatedAtIso || !cutoffIso) return false
const updatedAtMs = new Date(updatedAtIso).getTime()
const cutoffMs = new Date(cutoffIso).getTime()
if (!Number.isFinite(updatedAtMs) || !Number.isFinite(cutoffMs)) return false
return updatedAtMs > cutoffMs
}
export function isThreadUnreadByLastRead(
updatedAtIso: string,
threadReadStateIso: string | undefined,
unreadCutoffIso: string,
): boolean {
const effectiveLastReadIso = threadReadStateIso ?? unreadCutoffIso
return isThreadUpdatedAfterCutoff(updatedAtIso, effectiveLastReadIso)
}
function normalizeCollaborationMode(value: unknown): CollaborationModeKind {
return value === 'plan' ? 'plan' : 'default'
}
function normalizeStoredModelId(value: unknown): string {
return typeof value === 'string' ? value.trim() : ''
}
function createStringKeyedRecord<T>(): Record<string, T> {
return Object.create(null) as Record<string, T>
}
function cloneStringKeyedRecord<T>(record: Record<string, T>): Record<string, T> {
const next = createStringKeyedRecord<T>()
for (const [key, value] of Object.entries(record)) {
next[key] = value
}
return next
}
function omitStringKeyedRecordKey<T>(record: Record<string, T>, key: string): Record<string, T> {
if (!(key in record)) return record
const next = createStringKeyedRecord<T>()
for (const [entryKey, value] of Object.entries(record)) {
if (entryKey !== key) {
next[entryKey] = value
}
}
return next
}
function pruneThreadContextStateMap<T>(
stateMap: Record<string, T>,
threadIds: Set<string>,
): Record<string, T> {
let changed = false
const next = createStringKeyedRecord<T>()
for (const [contextId, value] of Object.entries(stateMap)) {
if (
contextId === NEW_THREAD_COLLABORATION_MODE_CONTEXT
|| contextId.startsWith(NEW_THREAD_PROVIDER_MODEL_CONTEXT_PREFIX)
|| threadIds.has(contextId)
) {
next[contextId] = value
continue
}
changed = true
}
return changed ? next : stateMap
}
function normalizeProviderContextId(providerId: string): string {
const normalized = providerId.trim().toLowerCase().replace(/_/g, '-')
if (!normalized || normalized === 'openai') return 'codex'
return normalized
}
function isNewThreadContextId(contextId: string): boolean {
return contextId === NEW_THREAD_COLLABORATION_MODE_CONTEXT
}
function toProviderModelContextId(providerId: string): string {
const normalizedProviderId = normalizeProviderContextId(providerId)
if (!normalizedProviderId) return ''
return `${NEW_THREAD_PROVIDER_MODEL_CONTEXT_PREFIX}${normalizedProviderId}`
}
function toThreadContextId(threadId: string): string {
const normalizedThreadId = threadId.trim()
return normalizedThreadId || NEW_THREAD_COLLABORATION_MODE_CONTEXT
}
function loadSelectedModelMap(): Record<string, string> {
if (typeof window === 'undefined') return createStringKeyedRecord<string>()
try {
const raw = window.localStorage.getItem(SELECTED_MODEL_BY_CONTEXT_STORAGE_KEY)
if (raw) {
const parsed = JSON.parse(raw) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return createStringKeyedRecord<string>()
const next = createStringKeyedRecord<string>()
for (const [contextId, value] of Object.entries(parsed as Record<string, unknown>)) {
if (typeof contextId !== 'string' || contextId.length === 0) continue
const normalizedModelId = normalizeStoredModelId(value)
if (normalizedModelId) {
next[contextId] = normalizedModelId
}
}
return next
}
} catch {
// Fall back to the legacy global preference below.
}
const legacyModelId = normalizeStoredModelId(window.localStorage.getItem(LEGACY_SELECTED_MODEL_STORAGE_KEY))
const next = createStringKeyedRecord<string>()
if (legacyModelId) {
next[NEW_THREAD_COLLABORATION_MODE_CONTEXT] = legacyModelId
}
return next
}
function readSelectedModel(
state: Record<string, string>,
threadId: string,
): string {
const contextId = toThreadContextId(threadId)
const contextModelId = normalizeStoredModelId(state[contextId])
if (contextModelId) return contextModelId
return normalizeStoredModelId(state[NEW_THREAD_COLLABORATION_MODE_CONTEXT])
}
function saveSelectedModelMap(state: Record<string, string>): void {
if (typeof window === 'undefined') return
try {
if (Object.keys(state).length === 0) {
window.localStorage.removeItem(SELECTED_MODEL_BY_CONTEXT_STORAGE_KEY)
} else {
window.localStorage.setItem(SELECTED_MODEL_BY_CONTEXT_STORAGE_KEY, JSON.stringify(state))
}
window.localStorage.removeItem(LEGACY_SELECTED_MODEL_STORAGE_KEY)
} catch {
// Keep in-memory selection working even if localStorage writes fail.
}
}
function loadSelectedCollaborationModeMap(): Record<string, CollaborationModeKind> {
if (typeof window === 'undefined') return createStringKeyedRecord<CollaborationModeKind>()
try {
const raw = window.localStorage.getItem(COLLABORATION_MODE_STORAGE_KEY)
if (raw) {
const parsed = JSON.parse(raw) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return createStringKeyedRecord<CollaborationModeKind>()
}
const next = createStringKeyedRecord<CollaborationModeKind>()
for (const [contextId, value] of Object.entries(parsed as Record<string, unknown>)) {
if (typeof contextId !== 'string' || contextId.length === 0) continue
const normalizedMode = normalizeCollaborationMode(value)
if (normalizedMode === 'plan') {
next[contextId] = normalizedMode
}
}
return next
}
} catch {
// Fall back to the legacy global preference below.
}
return createStringKeyedRecord<CollaborationModeKind>()
}
function readSelectedCollaborationMode(
state: Record<string, CollaborationModeKind>,
threadId: string,
): CollaborationModeKind {
const contextId = toThreadContextId(threadId)
return normalizeCollaborationMode(state[contextId])
}
function writeSelectedCollaborationModeForContext(
state: Record<string, CollaborationModeKind>,
threadId: string,
mode: CollaborationModeKind,
): Record<string, CollaborationModeKind> {
const contextId = toThreadContextId(threadId)
if (isNewThreadContextId(contextId)) {
return omitStringKeyedRecordKey(state, contextId)
}
if (mode === 'plan') {
const next = cloneStringKeyedRecord(state)
next[contextId] = 'plan'
return next
}
return omitStringKeyedRecordKey(state, contextId)
}
function saveSelectedCollaborationModeMap(state: Record<string, CollaborationModeKind>): void {
if (typeof window === 'undefined') return
try {
if (Object.keys(state).length === 0) {
window.localStorage.removeItem(COLLABORATION_MODE_STORAGE_KEY)
} else {
window.localStorage.setItem(COLLABORATION_MODE_STORAGE_KEY, JSON.stringify(state))
}
window.localStorage.removeItem(LEGACY_COLLABORATION_MODE_STORAGE_KEY)
} catch {
// Keep in-memory mode selection working even if localStorage writes fail.
}
}
function clamp(value: number, minValue: number, maxValue: number): number {
return Math.min(Math.max(value, minValue), maxValue)
}
function normalizeStoredTokenCount(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) {
return Math.max(0, Math.trunc(value))
}
if (typeof value === 'string' && value.trim().length > 0) {
const parsed = Number(value)
if (Number.isFinite(parsed)) {
return Math.max(0, Math.trunc(parsed))
}
}
return null
}
function normalizeTokenUsageBreakdown(value: unknown): UiThreadTokenUsage['last'] | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
const record = value as Record<string, unknown>
return {
totalTokens: normalizeStoredTokenCount(record.totalTokens) ?? 0,
inputTokens: normalizeStoredTokenCount(record.inputTokens) ?? 0,
cachedInputTokens: normalizeStoredTokenCount(record.cachedInputTokens) ?? 0,
outputTokens: normalizeStoredTokenCount(record.outputTokens) ?? 0,
reasoningOutputTokens: normalizeStoredTokenCount(record.reasoningOutputTokens) ?? 0,
}
}
function normalizeThreadTokenUsage(value: unknown): UiThreadTokenUsage | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
const record = value as Record<string, unknown>
const total = normalizeTokenUsageBreakdown(record.total)
const last = normalizeTokenUsageBreakdown(record.last)
if (!total || !last) return null
const modelContextWindow = normalizeStoredTokenCount(record.modelContextWindow)
const currentContextTokens = last.totalTokens
const remainingContextTokens = typeof modelContextWindow === 'number'
? Math.max(modelContextWindow - currentContextTokens, 0)
: null
const remainingContextPercent = typeof modelContextWindow === 'number' && modelContextWindow > 0
? clamp(Math.round((remainingContextTokens ?? 0) / modelContextWindow * 100), 0, 100)
: null
return {
total,
last,
modelContextWindow,
currentContextTokens,
remainingContextTokens,
remainingContextPercent,
}
}
function loadThreadTokenUsageMap(): Record<string, UiThreadTokenUsage> {
if (typeof window === 'undefined') return {}
try {
const raw = window.localStorage.getItem(THREAD_TOKEN_USAGE_STORAGE_KEY)
if (!raw) return {}
const parsed = JSON.parse(raw) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
const normalizedMap: Record<string, UiThreadTokenUsage> = {}
for (const [threadId, usage] of Object.entries(parsed as Record<string, unknown>)) {
if (!threadId) continue
const normalizedUsage = normalizeThreadTokenUsage(usage)
if (normalizedUsage) {
normalizedMap[threadId] = normalizedUsage
}
}
return normalizedMap
} catch {
return {}
}
}
function saveThreadTokenUsageMap(state: Record<string, UiThreadTokenUsage>): void {
if (typeof window === 'undefined') return
window.localStorage.setItem(THREAD_TOKEN_USAGE_STORAGE_KEY, JSON.stringify(state))
}
function loadThreadTerminalOpenMap(): Record<string, boolean> {
if (typeof window === 'undefined') return {}
try {
const raw = window.localStorage.getItem(THREAD_TERMINAL_OPEN_STORAGE_KEY)
if (!raw) return {}
const parsed = JSON.parse(raw) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
const normalizedMap: Record<string, boolean> = {}
for (const [threadId, isOpen] of Object.entries(parsed as Record<string, unknown>)) {
if (threadId && typeof isOpen === 'boolean') {
normalizedMap[threadId] = isOpen
}
}
return normalizedMap
} catch {
return {}
}
}
function saveThreadTerminalOpenMap(state: Record<string, boolean>): void {
if (typeof window === 'undefined') return
window.localStorage.setItem(THREAD_TERMINAL_OPEN_STORAGE_KEY, JSON.stringify(state))
}
function loadSelectedThreadId(): string {
if (typeof window === 'undefined') return ''
const raw = window.localStorage.getItem(SELECTED_THREAD_STORAGE_KEY)
return raw ?? ''
}
function saveSelectedThreadId(threadId: string): void {
if (typeof window === 'undefined') return
if (!threadId) {
window.localStorage.removeItem(SELECTED_THREAD_STORAGE_KEY)
return
}
window.localStorage.setItem(SELECTED_THREAD_STORAGE_KEY, threadId)
}
function loadProjectOrder(): string[] {
if (typeof window === 'undefined') return []
try {
const raw = window.localStorage.getItem(PROJECT_ORDER_STORAGE_KEY)
if (!raw) return []
const parsed = JSON.parse(raw) as unknown
if (!Array.isArray(parsed)) return []
const order: string[] = []
for (const item of parsed) {
if (typeof item !== 'string' || item.length === 0) continue
const normalizedItem = toProjectName(item)
if (normalizedItem.length > 0 && !order.includes(normalizedItem)) {
order.push(normalizedItem)
}
}
return order
} catch {
return []
}
}
function saveProjectOrder(order: string[]): void {
if (typeof window === 'undefined') return
window.localStorage.setItem(PROJECT_ORDER_STORAGE_KEY, JSON.stringify(order))
}
function loadProjectDisplayNames(): Record<string, string> {
if (typeof window === 'undefined') return {}
try {
const raw = window.localStorage.getItem(PROJECT_DISPLAY_NAME_STORAGE_KEY)
if (!raw) return {}
const parsed = JSON.parse(raw) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
const displayNames: Record<string, string> = {}
for (const [projectName, displayName] of Object.entries(parsed as Record<string, unknown>)) {
const normalizedProjectName = typeof projectName === 'string' ? toProjectName(projectName) : ''
if (normalizedProjectName.length > 0 && typeof displayName === 'string') {
displayNames[normalizedProjectName] = displayName
}
}
return displayNames
} catch {
return {}
}
}
function saveProjectDisplayNames(displayNames: Record<string, string>): void {
if (typeof window === 'undefined') return
window.localStorage.setItem(PROJECT_DISPLAY_NAME_STORAGE_KEY, JSON.stringify(displayNames))
}
function mergeProjectOrder(previousOrder: string[], incomingGroups: UiProjectGroup[]): string[] {
const nextOrder: string[] = []
for (const projectName of previousOrder) {
if (!nextOrder.includes(projectName)) {
nextOrder.push(projectName)
}
}
for (const group of incomingGroups) {
if (!nextOrder.includes(group.projectName)) {
nextOrder.push(group.projectName)
}
}
return areStringArraysEqual(previousOrder, nextOrder) ? previousOrder : nextOrder
}
function orderGroupsByProjectOrder(incoming: UiProjectGroup[], projectOrder: string[]): UiProjectGroup[] {
const incomingByName = new Map(incoming.map((group) => [group.projectName, group]))
const ordered: UiProjectGroup[] = projectOrder
.map((projectName) => incomingByName.get(projectName) ?? null)
.filter((group): group is UiProjectGroup => group !== null)
for (const group of incoming) {
if (!projectOrder.includes(group.projectName)) {
ordered.push(group)
}
}
return ordered
}
function areStringArraysEqual(first?: string[], second?: string[]): boolean {
const left = Array.isArray(first) ? first : []
const right = Array.isArray(second) ? second : []
if (left.length !== right.length) return false
for (let index = 0; index < left.length; index += 1) {
if (left[index] !== right[index]) return false
}
return true
}
function reorderStringArray(items: string[], fromIndex: number, toIndex: number): string[] {
if (fromIndex < 0 || fromIndex >= items.length || toIndex < 0 || toIndex >= items.length) {
return items
}
if (fromIndex === toIndex) {
return items
}
const next = [...items]
const [moved] = next.splice(fromIndex, 1)
next.splice(toIndex, 0, moved)
return next
}
function areCommandExecutionsEqual(first?: CommandExecutionData, second?: CommandExecutionData): boolean {
if (!first && !second) return true
if (!first || !second) return false
return first.status === second.status && first.aggregatedOutput === second.aggregatedOutput && first.exitCode === second.exitCode
}
function arePlanStepsEqual(first: UiPlanStep[] = [], second: UiPlanStep[] = []): boolean {
if (first.length !== second.length) return false
for (let index = 0; index < first.length; index += 1) {
if (first[index]?.step !== second[index]?.step || first[index]?.status !== second[index]?.status) {
return false
}
}
return true
}
function arePlanDataEqual(first?: UiPlanData, second?: UiPlanData): boolean {
if (!first && !second) return true
if (!first || !second) return false
return (
first.explanation === second.explanation &&
first.isStreaming === second.isStreaming &&
arePlanStepsEqual(first.steps, second.steps)
)
}
function isUnsupportedChatGptModelError(error: unknown): boolean {
if (!(error instanceof Error)) return false
const message = error.message.toLowerCase()
return (
message.includes('not supported when using codex with a chatgpt account') ||
message.includes('model is not supported') ||
message.includes('requires a newer version of codex')
)
}
function areMessageFieldsEqual(first: UiMessage, second: UiMessage): boolean {
return (
first.id === second.id &&
first.role === second.role &&
first.text === second.text &&
areStringArraysEqual(first.images, second.images) &&
areUiFileChangesEqual(first.fileChanges, second.fileChanges) &&
first.fileChangeStatus === second.fileChangeStatus &&
first.messageType === second.messageType &&
first.rawPayload === second.rawPayload &&
first.isUnhandled === second.isUnhandled &&
areCommandExecutionsEqual(first.commandExecution, second.commandExecution) &&
arePlanDataEqual(first.plan, second.plan) &&
first.turnId === second.turnId &&
first.turnIndex === second.turnIndex &&
first.isAutomationRun === second.isAutomationRun &&
first.automationDisplayName === second.automationDisplayName
)
}
function areMessageArraysEqual(first: UiMessage[], second: UiMessage[]): boolean {
if (first.length !== second.length) return false
for (let index = 0; index < first.length; index += 1) {
if (first[index] !== second[index]) return false
}
return true
}
function mergeMessages(
previous: UiMessage[],
incoming: UiMessage[],
options: { preserveMissing?: boolean } = {},
): UiMessage[] {
const previousById = new Map(previous.map((message) => [message.id, message]))
const incomingById = new Map(incoming.map((message) => [message.id, message]))
const mergedIncoming = incoming.map((incomingMessage) => {
const previousMessage = previousById.get(incomingMessage.id)
if (previousMessage && areMessageFieldsEqual(previousMessage, incomingMessage)) {
return previousMessage
}
return incomingMessage
})
if (options.preserveMissing !== true) {
return areMessageArraysEqual(previous, mergedIncoming) ? previous : mergedIncoming
}
const mergedFromPrevious = previous
.map((previousMessage) => {
const nextMessage = incomingById.get(previousMessage.id)
if (!nextMessage) {
return previousMessage
}
if (areMessageFieldsEqual(previousMessage, nextMessage)) {
return previousMessage
}
return nextMessage
})
.filter((message) => !isOptimisticUserMessage(message) || !hasEquivalentUserMessage(message, incoming))
const previousIdSet = new Set(previous.map((message) => message.id))
const appended = mergedIncoming.filter((message) => !previousIdSet.has(message.id))
const merged = [...mergedFromPrevious, ...appended]
return areMessageArraysEqual(previous, merged) ? previous : merged
}
function areUiFileChangesEqual(first?: UiFileChange[], second?: UiFileChange[]): boolean {
if (!first && !second) return true
if (!first || !second) return false
if (first.length !== second.length) return false
for (let index = 0; index < first.length; index += 1) {
const firstChange = first[index]
const secondChange = second[index]
if (
firstChange.path !== secondChange.path ||
firstChange.operation !== secondChange.operation ||
firstChange.movedToPath !== secondChange.movedToPath ||
firstChange.diff !== secondChange.diff ||
firstChange.addedLineCount !== secondChange.addedLineCount ||
firstChange.removedLineCount !== secondChange.removedLineCount
) {
return false
}
}
return true
}
function normalizeMessageText(value: string): string {
return value.replace(/\s+/gu, ' ').trim()
}
function isOptimisticUserMessage(message: UiMessage): boolean {
return message.messageType === 'userMessage.optimistic'
}
function hasOptimisticUserMessages(messages: UiMessage[]): boolean {
return messages.some(isOptimisticUserMessage)
}
function hasEquivalentUserMessage(target: UiMessage, messages: UiMessage[]): boolean {
if (target.role !== 'user') return false
const targetText = normalizeMessageText(target.text)
const targetImages = Array.isArray(target.images) ? target.images : []
const targetFileCount = Array.isArray(target.fileAttachments) ? target.fileAttachments.length : 0
const targetSkillCount = Array.isArray(target.skills) ? target.skills.length : 0
return messages.some((message) => {
if (message === target || message.role !== 'user' || isOptimisticUserMessage(message)) return false
const messageText = normalizeMessageText(message.text)
const messageImages = Array.isArray(message.images) ? message.images : []
const messageFileCount = Array.isArray(message.fileAttachments) ? message.fileAttachments.length : 0
const messageSkillCount = Array.isArray(message.skills) ? message.skills.length : 0
return (
messageText === targetText &&
areStringArraysEqual(messageImages, targetImages) &&
messageFileCount === targetFileCount &&
messageSkillCount === targetSkillCount
)
})
}
function removeRedundantLiveAgentMessages(previous: UiMessage[], incoming: UiMessage[]): UiMessage[] {
const incomingMessageIds = new Set(incoming.map((message) => message.id))
const incomingAssistantTexts = new Set(
incoming
.filter((message) => message.role === 'assistant')
.map((message) => normalizeMessageText(message.text))
.filter((text) => text.length > 0),
)
if (incomingAssistantTexts.size === 0) {
return previous
}
const next = previous.filter((message) => {
if (message.messageType !== 'agentMessage.live') return true
if (incomingMessageIds.has(message.id)) return false
const normalized = normalizeMessageText(message.text)
if (normalized.length === 0) return false
return !incomingAssistantTexts.has(normalized)
})
return next.length === previous.length ? previous : next
}
function removePersistedLiveMessages(previous: UiMessage[], incoming: UiMessage[]): UiMessage[] {
const incomingIds = new Set(incoming.map((message) => message.id))
const next = previous.filter((message) => !incomingIds.has(message.id))
return next.length === previous.length ? previous : next
}
function upsertMessage(previous: UiMessage[], nextMessage: UiMessage): UiMessage[] {
const existingIndex = previous.findIndex((message) => message.id === nextMessage.id)
if (existingIndex < 0) {
return [...previous, nextMessage]
}
const existing = previous[existingIndex]
if (areMessageFieldsEqual(existing, nextMessage)) {
return previous
}
const next = [...previous]
next.splice(existingIndex, 1, nextMessage)
return next
}
type TurnSummaryState = {
turnId: string
durationMs: number
}
type TurnActivityState = {
label: string
details: string[]
}
type TurnErrorState = {
message: string
transient: boolean
}
type TurnStartedInfo = {
threadId: string
turnId: string
startedAtMs: number
}
type TurnCompletedInfo = {
threadId: string
turnId: string
completedAtMs: number
startedAtMs?: number
}
const WORKED_MESSAGE_TYPE = 'worked'
function parseIsoTimestamp(value: string): number | null {
if (!value) return null
const ms = new Date(value).getTime()
return Number.isNaN(ms) ? null : ms
}
function formatTurnDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs <= 0) {
return '<1s'
}
const totalSeconds = Math.max(1, Math.round(durationMs / 1000))
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds % 60
const parts: string[] = []
if (hours > 0) {
parts.push(`${hours}h`)
}
if (minutes > 0 || hours > 0) {
parts.push(`${minutes}m`)
}
const displaySeconds = seconds > 0 || parts.length === 0 ? seconds : 0
parts.push(`${displaySeconds}s`)
return parts.join(' ')
}
function areTurnSummariesEqual(first?: TurnSummaryState, second?: TurnSummaryState): boolean {
if (!first && !second) return true
if (!first || !second) return false
return first.turnId === second.turnId && first.durationMs === second.durationMs
}
function areTurnActivitiesEqual(first?: TurnActivityState, second?: TurnActivityState): boolean {
if (!first && !second) return true
if (!first || !second) return false
if (first.label !== second.label) return false
if (first.details.length !== second.details.length) return false
for (let index = 0; index < first.details.length; index += 1) {
if (first.details[index] !== second.details[index]) return false
}
return true
}
function buildTurnSummaryMessage(summary: TurnSummaryState): UiMessage {
return {
id: `turn-summary:${summary.turnId}`,
role: 'system',
text: `Worked for ${formatTurnDuration(summary.durationMs)}`,
messageType: WORKED_MESSAGE_TYPE,
turnId: summary.turnId,
}
}
function findLastAssistantMessageIndex(messages: UiMessage[]): number {
for (let index = messages.length - 1; index >= 0; index -= 1) {
if (messages[index].role === 'assistant') {
return index
}
}
return -1
}
function insertTurnSummaryMessage(messages: UiMessage[], summary: TurnSummaryState): UiMessage[] {
const summaryMessage = buildTurnSummaryMessage(summary)
const sanitizedMessages = messages.filter((message) => message.messageType !== WORKED_MESSAGE_TYPE)
const insertIndex = findLastAssistantMessageIndex(sanitizedMessages)
if (insertIndex < 0) {
return [...sanitizedMessages, summaryMessage]
}
const next = [...sanitizedMessages]
next.splice(insertIndex, 0, summaryMessage)
return next
}
function omitKey<TValue>(record: Record<string, TValue>, key: string): Record<string, TValue> {
if (!(key in record)) return record
const next = { ...record }
delete next[key]
return next
}
function omitKeys<TValue>(record: Record<string, TValue>, keys: Set<string>): Record<string, TValue> {
if (keys.size === 0) return record
let changed = false
const next: Record<string, TValue> = {}
for (const [key, value] of Object.entries(record)) {
if (keys.has(key)) {
changed = true
continue
}
next[key] = value
}
return changed ? next : record
}
function areThreadFieldsEqual(first: UiThread, second: UiThread): boolean {
return (
first.id === second.id &&
first.title === second.title &&
first.projectName === second.projectName &&
first.cwd === second.cwd &&
first.createdAtIso === second.createdAtIso &&
first.updatedAtIso === second.updatedAtIso &&
first.preview === second.preview &&
first.unread === second.unread &&
first.inProgress === second.inProgress &&
first.pendingRequestState === second.pendingRequestState
)
}
function areThreadArraysEqual(first: UiThread[], second: UiThread[]): boolean {
if (first.length !== second.length) return false
for (let index = 0; index < first.length; index += 1) {
if (first[index] !== second[index]) return false
}
return true
}
function areGroupArraysEqual(first: UiProjectGroup[], second: UiProjectGroup[]): boolean {
if (first.length !== second.length) return false
for (let index = 0; index < first.length; index += 1) {
if (first[index] !== second[index]) return false
}
return true
}
function pruneThreadStateMap<T>(stateMap: Record<string, T>, threadIds: Set<string>): Record<string, T> {
const nextEntries = Object.entries(stateMap).filter(([threadId]) => threadIds.has(threadId))
if (nextEntries.length === Object.keys(stateMap).length) {
return stateMap
}
return Object.fromEntries(nextEntries) as Record<string, T>
}
export function removeThreadFromGroups(groups: UiProjectGroup[], threadId: string): UiProjectGroup[] {
const normalizedThreadId = threadId.trim()
if (!normalizedThreadId) return groups
let changed = false
const nextGroups: UiProjectGroup[] = []
for (const group of groups) {
const nextThreads = group.threads.filter((thread) => thread.id !== normalizedThreadId)
const removedFromGroup = nextThreads.length !== group.threads.length
if (removedFromGroup) {
changed = true
}
if (nextThreads.length > 0) {
nextGroups.push(removedFromGroup ? { ...group, threads: nextThreads } : group)
} else if (group.threads.length === 0) {
nextGroups.push(group)
}
}
return changed ? nextGroups : groups
}
function mergeThreadGroups(