-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsession_actions.go
More file actions
1288 lines (1211 loc) · 37.7 KB
/
session_actions.go
File metadata and controls
1288 lines (1211 loc) · 37.7 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
package main
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
const sessionDeleteBackupVersion = 1
type sessionRolloutFile struct {
Path string
FirstLine string
Separator string
Record map[string]any
SessionID string
Title string
CWD string
CreatedAtMs int64
UpdatedAtMs int64
}
type sessionSQLiteRow struct {
Columns []string `json:"columns"`
Values map[string]any `json:"values"`
}
type sessionLookupResult struct {
RequestedID string
CanonicalID string
Variants []string
Files []sessionRolloutFile
DBRows []sessionSQLiteRow
}
type deletedSessionManifest struct {
Version int `json:"version"`
SessionID string `json:"session_id"`
DeletedAt string `json:"deleted_at"`
Files []deletedSessionFileBackup `json:"files"`
Rows []sessionSQLiteRow `json:"rows"`
}
type deletedSessionFileBackup struct {
OriginalPath string `json:"original_path"`
BackupName string `json:"backup_name"`
}
type sessionSortKey struct {
SessionID string
UpdatedAt int64
UpdatedAtMs int64
CreatedAtMs int64
}
type sessionMarkdownExport struct {
Filename string
Markdown string
}
type sessionMarkdownMessage struct {
Role string
Text string
Timestamp string
}
func isSessionDataRoute(path string) bool {
switch path {
case "/delete", "/undo", "/archived-thread", "/move-thread-workspace", "/move-thread-projectless", "/export-markdown", "/thread-sort-key", "/thread-sort-keys":
return true
default:
return false
}
}
func handleSessionDataRoute(path string, payload map[string]any) map[string]any {
if payload == nil {
payload = map[string]any{}
}
switch path {
case "/delete":
return deleteSessionDataRoute(payload)
case "/undo":
return undoSessionDataRoute(payload)
case "/archived-thread":
return archivedThreadDataRoute(payload)
case "/move-thread-workspace":
return moveThreadWorkspaceDataRoute(payload)
case "/move-thread-projectless":
return moveThreadProjectlessDataRoute(payload)
case "/export-markdown":
return exportMarkdownDataRoute(payload)
case "/thread-sort-key":
return threadSortKeyDataRoute(payload)
case "/thread-sort-keys":
return threadSortKeysDataRoute(payload)
default:
return unsupportedBridgeDataRoute(path, payload)
}
}
func deleteSessionDataRoute(payload map[string]any) map[string]any {
sessionID := strings.TrimSpace(stringFromAny(payload["session_id"]))
if sessionID == "" {
return map[string]any{"status": "failed", "message": "删除失败:未找到会话 ID"}
}
home := codexHomeDir()
lookup, err := lookupSession(home, sessionID, "", false)
if err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "删除失败:" + err.Error()}
}
undoToken, err := createSessionDeleteBackup(lookup)
if err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "删除失败:创建备份失败:" + err.Error()}
}
dbPath := filepath.Join(home, "state_5.sqlite")
if err := deleteSQLiteThreadRows(dbPath, lookup.allIDs()); err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "删除失败:更新会话索引失败:" + err.Error()}
}
for _, file := range lookup.Files {
if err := os.Remove(file.Path); err != nil && !errors.Is(err, os.ErrNotExist) {
_ = restoreSQLiteThreadRows(dbPath, lookup.DBRows)
return map[string]any{"status": "failed", "session_id": sessionID, "message": "删除失败:移除会话文件失败:" + err.Error(), "undo_token": undoToken}
}
}
return map[string]any{
"status": "local_deleted",
"session_id": lookup.canonicalOr(sessionID),
"message": "已删除本地会话。",
"undo_token": undoToken,
}
}
func undoSessionDataRoute(payload map[string]any) map[string]any {
token := strings.TrimSpace(stringFromAny(payload["undo_token"]))
if token == "" {
return map[string]any{"status": "failed", "message": "撤销失败:缺少撤销令牌"}
}
backupDir, err := sessionDeleteBackupDir(token)
if err != nil {
return map[string]any{"status": "failed", "message": "撤销失败:" + err.Error()}
}
var manifest deletedSessionManifest
if err := readJSON(filepath.Join(backupDir, "manifest.json"), &manifest); err != nil {
return map[string]any{"status": "failed", "message": "撤销失败:备份不存在或已损坏"}
}
for _, file := range manifest.Files {
source := filepath.Join(backupDir, file.BackupName)
if err := copyFileIfExists(source, file.OriginalPath); err != nil {
return map[string]any{"status": "failed", "session_id": manifest.SessionID, "message": "撤销失败:恢复会话文件失败:" + err.Error()}
}
}
if err := restoreSQLiteThreadRows(filepath.Join(codexHomeDir(), "state_5.sqlite"), manifest.Rows); err != nil {
return map[string]any{"status": "failed", "session_id": manifest.SessionID, "message": "撤销失败:恢复会话索引失败:" + err.Error()}
}
return map[string]any{"status": "ok", "session_id": manifest.SessionID, "message": "已恢复会话。"}
}
func archivedThreadDataRoute(payload map[string]any) map[string]any {
title := strings.TrimSpace(stringFromAny(payload["title"]))
if title == "" {
return map[string]any{"status": "failed", "message": "未找到归档会话标题"}
}
lookup, err := lookupSession(codexHomeDir(), "", title, true)
if err != nil {
return map[string]any{"status": "failed", "message": "未找到归档会话:" + err.Error()}
}
sessionID := lookup.canonicalOr("")
if sessionID == "" {
return map[string]any{"status": "failed", "message": "未找到归档会话 ID"}
}
return map[string]any{"status": "ok", "session_id": sessionID, "title": title}
}
func moveThreadWorkspaceDataRoute(payload map[string]any) map[string]any {
sessionID := strings.TrimSpace(stringFromAny(payload["session_id"]))
targetCWD := toDesktopWorkspacePath(stringFromAny(payload["target_cwd"]))
if sessionID == "" {
return map[string]any{"status": "failed", "message": "移动失败:未找到会话 ID"}
}
if strings.TrimSpace(targetCWD) == "" {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "移动失败:目标项目路径为空"}
}
home := codexHomeDir()
lookup, err := lookupSession(home, sessionID, "", false)
if err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "移动失败:" + err.Error()}
}
for _, file := range lookup.Files {
if err := rewriteRolloutWorkspace(file, targetCWD); err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "移动失败:更新会话文件失败:" + err.Error()}
}
}
if err := updateSQLiteThreadWorkspace(filepath.Join(home, "state_5.sqlite"), lookup.allIDs(), targetCWD); err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "移动失败:更新会话索引失败:" + err.Error()}
}
if err := updateCodexGlobalStateForWorkspaceMove(home, lookup, targetCWD); err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "移动失败:更新 Codex 全局状态失败:" + err.Error()}
}
key := sortKeyForSession(home, sessionID)
result := sortKeyPayload(key)
result["status"] = "moved"
result["session_id"] = lookup.canonicalOr(sessionID)
result["target_cwd"] = targetCWD
result["message"] = "已移动到项目。"
return result
}
func moveThreadProjectlessDataRoute(payload map[string]any) map[string]any {
sessionID := strings.TrimSpace(stringFromAny(payload["session_id"]))
if sessionID == "" {
return map[string]any{"status": "failed", "message": "移动失败:未找到会话 ID"}
}
home := codexHomeDir()
lookup, err := lookupSession(home, sessionID, "", false)
if err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "移动失败:" + err.Error()}
}
if err := updateCodexGlobalStateForProjectlessMove(home, lookup); err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "移动失败:更新 Codex 全局状态失败:" + err.Error()}
}
key := sortKeyForSession(home, sessionID)
result := sortKeyPayload(key)
result["status"] = "moved"
result["session_id"] = lookup.canonicalOr(sessionID)
result["target_cwd"] = ""
result["message"] = "已移动到普通对话。"
return result
}
func exportMarkdownDataRoute(payload map[string]any) map[string]any {
sessionID := strings.TrimSpace(stringFromAny(payload["session_id"]))
title := strings.TrimSpace(stringFromAny(payload["title"]))
if sessionID == "" && title == "" {
return map[string]any{"status": "failed", "message": "导出失败:未找到会话"}
}
home := codexHomeDir()
lookup, err := lookupSession(home, sessionID, title, false)
if err != nil {
return map[string]any{"status": "failed", "session_id": sessionID, "message": "导出失败:" + err.Error()}
}
export, err := buildSessionMarkdownExport(lookup)
if err != nil {
return map[string]any{"status": "failed", "session_id": lookup.canonicalOr(sessionID), "message": "导出失败:" + err.Error()}
}
return map[string]any{
"status": "exported",
"session_id": lookup.canonicalOr(sessionID),
"filename": export.Filename,
"markdown": export.Markdown,
"message": "已导出 Markdown。",
}
}
func threadSortKeyDataRoute(payload map[string]any) map[string]any {
sessionID := strings.TrimSpace(stringFromAny(payload["session_id"]))
key := sortKeyForSession(codexHomeDir(), sessionID)
result := sortKeyPayload(key)
result["status"] = "ok"
result["session_id"] = sessionID
return result
}
func threadSortKeysDataRoute(payload map[string]any) map[string]any {
rawSessions, _ := payload["sessions"].([]any)
sortKeys := make([]any, 0, len(rawSessions))
for _, item := range rawSessions {
sessionMap, _ := item.(map[string]any)
sessionID := strings.TrimSpace(stringFromAny(sessionMap["session_id"]))
key := sortKeyForSession(codexHomeDir(), sessionID)
value := sortKeyPayload(key)
value["session_id"] = sessionID
sortKeys = append(sortKeys, value)
}
return map[string]any{"status": "ok", "sort_keys": sortKeys, "sessions": sortKeys}
}
func lookupSession(home, sessionID, title string, archivedOnly bool) (sessionLookupResult, error) {
var lookup sessionLookupResult
lookup.RequestedID = strings.TrimSpace(sessionID)
lookup.Variants = sessionIDVariants(sessionID)
dbPath := filepath.Join(home, "state_5.sqlite")
var rows []sessionSQLiteRow
var err error
if len(lookup.Variants) > 0 {
rows, err = sqliteThreadRowsByIDs(dbPath, lookup.Variants)
} else if strings.TrimSpace(title) != "" {
rows, err = sqliteThreadRowsByTitle(dbPath, title, archivedOnly)
}
if err != nil {
return lookup, err
}
lookup.DBRows = rows
for _, row := range rows {
id := strings.TrimSpace(stringFromAny(row.Values["id"]))
if id != "" {
lookup.Variants = appendSessionIDVariants(lookup.Variants, id)
if lookup.CanonicalID == "" {
lookup.CanonicalID = bareSessionID(id)
}
}
}
var files []sessionRolloutFile
seenFiles := map[string]bool{}
for _, row := range rows {
path := normalizeRolloutPath(home, stringFromAny(row.Values["rollout_path"]))
if path == "" || seenFiles[path] || !fileExists(path) {
continue
}
file, err := readRolloutFile(path)
if err != nil {
continue
}
files = append(files, file)
seenFiles[path] = true
}
walked, err := findRolloutFiles(home, lookup.Variants)
if err != nil {
return lookup, err
}
for _, file := range walked {
if seenFiles[file.Path] {
continue
}
files = append(files, file)
seenFiles[file.Path] = true
}
sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path })
lookup.Files = files
for _, file := range files {
if file.SessionID != "" {
lookup.Variants = appendSessionIDVariants(lookup.Variants, file.SessionID)
if lookup.CanonicalID == "" {
lookup.CanonicalID = bareSessionID(file.SessionID)
}
}
}
if lookup.CanonicalID == "" && len(lookup.Variants) > 0 {
lookup.CanonicalID = bareSessionID(lookup.Variants[0])
}
if len(lookup.DBRows) == 0 && len(lookup.Files) == 0 {
return lookup, errors.New("未在本地索引或会话文件中找到该会话")
}
return lookup, nil
}
func (l sessionLookupResult) canonicalOr(fallback string) string {
if strings.TrimSpace(l.CanonicalID) != "" {
return l.CanonicalID
}
if len(l.Variants) > 0 {
return bareSessionID(l.Variants[0])
}
return bareSessionID(fallback)
}
func (l sessionLookupResult) allIDs() []string {
ids := append([]string{}, l.Variants...)
for _, row := range l.DBRows {
ids = appendSessionIDVariants(ids, stringFromAny(row.Values["id"]))
}
for _, file := range l.Files {
ids = appendSessionIDVariants(ids, file.SessionID)
}
return uniqueNonEmptyStrings(ids)
}
func sessionIDVariants(sessionID string) []string {
sessionID = strings.TrimSpace(sessionID)
if sessionID == "" {
return nil
}
bare := bareSessionID(sessionID)
return uniqueNonEmptyStrings([]string{sessionID, bare, "local:" + bare})
}
func appendSessionIDVariants(ids []string, sessionID string) []string {
return append(ids, sessionIDVariants(sessionID)...)
}
func bareSessionID(sessionID string) string {
sessionID = strings.TrimSpace(sessionID)
return strings.TrimPrefix(sessionID, "local:")
}
func uniqueNonEmptyStrings(values []string) []string {
seen := map[string]bool{}
out := make([]string, 0, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
if value == "" || seen[value] {
continue
}
seen[value] = true
out = append(out, value)
}
return out
}
func normalizeRolloutPath(home, value string) string {
value = strings.TrimSpace(value)
if value == "" {
return ""
}
value = toDesktopWorkspacePath(value)
if strings.HasPrefix(value, "~/") {
if userHome, err := os.UserHomeDir(); err == nil && userHome != "" {
return filepath.Join(userHome, value[2:])
}
}
if filepath.IsAbs(value) {
return value
}
return filepath.Join(home, value)
}
func readRolloutFile(path string) (sessionRolloutFile, error) {
data, err := os.ReadFile(path)
if err != nil {
return sessionRolloutFile{}, err
}
firstLine, separator := splitFirstLine(string(data))
var record map[string]any
if err := json.Unmarshal([]byte(firstLine), &record); err != nil {
return sessionRolloutFile{}, err
}
payload, _ := record["payload"].(map[string]any)
file := sessionRolloutFile{
Path: path,
FirstLine: firstLine,
Separator: separator,
Record: record,
SessionID: strings.TrimSpace(stringFromAny(payload["id"])),
Title: firstString(payload["title"], record["title"]),
CWD: toDesktopWorkspacePath(stringFromAny(payload["cwd"])),
CreatedAtMs: timestampMsFromAny(firstString(payload["timestamp"], record["timestamp"])),
UpdatedAtMs: timestampMsFromAny(firstString(record["timestamp"], payload["timestamp"])),
}
if file.CreatedAtMs == 0 {
file.CreatedAtMs = uuidV7TimestampMs(file.SessionID)
}
if file.UpdatedAtMs == 0 {
if info, statErr := os.Stat(path); statErr == nil {
file.UpdatedAtMs = info.ModTime().UnixMilli()
}
}
return file, nil
}
func findRolloutFiles(home string, ids []string) ([]sessionRolloutFile, error) {
if len(ids) == 0 {
return nil, nil
}
var files []sessionRolloutFile
idSet := map[string]bool{}
for _, id := range ids {
for _, variant := range sessionIDVariants(id) {
idSet[variant] = true
idSet[bareSessionID(variant)] = true
}
}
for _, dirname := range []string{"sessions", "archived_sessions"} {
root := filepath.Join(home, dirname)
if !isDir(root) {
continue
}
err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
name := entry.Name()
if !strings.HasPrefix(name, "rollout-") || !strings.HasSuffix(name, ".jsonl") {
return nil
}
file, err := readRolloutFile(path)
if err != nil {
return nil
}
if idSet[file.SessionID] || idSet[bareSessionID(file.SessionID)] {
files = append(files, file)
}
return nil
})
if err != nil {
return nil, err
}
}
return files, nil
}
func rewriteRolloutWorkspace(file sessionRolloutFile, targetCWD string) error {
record := file.Record
payload, ok := record["payload"].(map[string]any)
if !ok {
return errors.New("会话文件缺少 payload")
}
if toDesktopWorkspacePath(stringFromAny(payload["cwd"])) == targetCWD {
return nil
}
payload["cwd"] = targetCWD
nextFirstLine, err := json.Marshal(record)
if err != nil {
return err
}
return atomicWrite(file.Path, append(nextFirstLine, []byte(file.Separator)...))
}
func buildSessionMarkdownExport(lookup sessionLookupResult) (sessionMarkdownExport, error) {
if len(lookup.Files) == 0 {
return sessionMarkdownExport{}, errors.New("未找到可导出的会话文件")
}
file := lookup.Files[len(lookup.Files)-1]
messages, err := rolloutMarkdownMessages(file.Path)
if err != nil {
return sessionMarkdownExport{}, err
}
if len(messages) == 0 {
return sessionMarkdownExport{}, errors.New("会话中没有可导出的用户或助手消息")
}
title := firstString(file.Title, lookup.CanonicalID, lookup.RequestedID, "Codex Conversation")
sessionID := firstString(file.SessionID, lookup.canonicalOr(""))
var builder strings.Builder
builder.WriteString("# ")
builder.WriteString(markdownLine(title))
builder.WriteString("\n\n")
if sessionID != "" {
builder.WriteString("- Session ID: `")
builder.WriteString(markdownInlineCode(sessionID))
builder.WriteString("`\n")
}
if file.CWD != "" {
builder.WriteString("- Workspace: `")
builder.WriteString(markdownInlineCode(file.CWD))
builder.WriteString("`\n")
}
builder.WriteString("- Exported: ")
builder.WriteString(time.Now().UTC().Format(time.RFC3339))
builder.WriteString("\n\n")
for _, message := range messages {
builder.WriteString("## ")
builder.WriteString(markdownRoleLabel(message.Role))
if message.Timestamp != "" {
builder.WriteString(" · ")
builder.WriteString(markdownLine(message.Timestamp))
}
builder.WriteString("\n\n")
builder.WriteString(strings.TrimSpace(message.Text))
builder.WriteString("\n\n")
}
return sessionMarkdownExport{
Filename: exportMarkdownFilename(title, time.Now()),
Markdown: strings.TrimRight(builder.String(), "\n") + "\n",
}, nil
}
func rolloutMarkdownMessages(path string) ([]sessionMarkdownMessage, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var messages []sessionMarkdownMessage
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
var record map[string]any
if err := json.Unmarshal([]byte(line), &record); err != nil {
continue
}
message := markdownMessageFromRolloutRecord(record)
if message.Role == "" || strings.TrimSpace(message.Text) == "" {
continue
}
messages = append(messages, message)
}
return messages, nil
}
func markdownMessageFromRolloutRecord(record map[string]any) sessionMarkdownMessage {
payload, _ := record["payload"].(map[string]any)
if payload == nil {
payload = record
}
timestamp := firstString(record["timestamp"], payload["timestamp"])
switch stringFromAny(record["type"]) {
case "event_msg":
switch stringFromAny(payload["type"]) {
case "user_message", "user_input":
return sessionMarkdownMessage{Role: "user", Text: stringFromAny(payload["message"]), Timestamp: timestamp}
case "agent_message":
if phase := strings.TrimSpace(stringFromAny(payload["phase"])); phase != "" && phase != "final_answer" && phase != "commentary" {
return sessionMarkdownMessage{}
}
return sessionMarkdownMessage{Role: "assistant", Text: stringFromAny(payload["message"]), Timestamp: timestamp}
default:
return sessionMarkdownMessage{}
}
case "response_item":
if stringFromAny(payload["type"]) != "message" {
return sessionMarkdownMessage{}
}
role := strings.TrimSpace(stringFromAny(payload["role"]))
if role != "user" && role != "assistant" {
return sessionMarkdownMessage{}
}
text := markdownTextFromContent(payload["content"])
return sessionMarkdownMessage{Role: role, Text: text, Timestamp: timestamp}
default:
return sessionMarkdownMessage{}
}
}
func markdownTextFromContent(value any) string {
items, ok := value.([]any)
if !ok {
return stringFromAny(value)
}
var parts []string
for _, item := range items {
content, _ := item.(map[string]any)
if content == nil {
continue
}
switch stringFromAny(content["type"]) {
case "input_text", "output_text", "text":
if text := strings.TrimSpace(stringFromAny(content["text"])); text != "" {
parts = append(parts, text)
}
}
}
return strings.Join(parts, "\n\n")
}
func markdownRoleLabel(role string) string {
switch role {
case "user":
return "User"
case "assistant":
return "Assistant"
default:
return markdownLine(role)
}
}
func markdownLine(value string) string {
value = strings.ReplaceAll(value, "\r", " ")
value = strings.ReplaceAll(value, "\n", " ")
return strings.TrimSpace(value)
}
func markdownInlineCode(value string) string {
return strings.ReplaceAll(value, "`", "'")
}
func exportMarkdownFilename(title string, exportedAt time.Time) string {
name := sanitizeExportFilename(title)
if name == "" {
name = "codex-conversation"
}
return fmt.Sprintf("%s-%s.md", name, exportedAt.Format("20060102-150405"))
}
func sanitizeExportFilename(value string) string {
value = strings.TrimSpace(value)
var builder strings.Builder
lastDash := false
for _, r := range value {
if r < 32 || r == ' ' || r == '\t' || strings.ContainsRune(`<>:"/\|?*`, r) {
if !lastDash {
builder.WriteRune('-')
lastDash = true
}
} else {
builder.WriteRune(r)
lastDash = false
}
if builder.Len() >= 80 {
break
}
}
return strings.Trim(builder.String(), "-._ ")
}
func codexGlobalStatePath(home string) string {
return filepath.Join(home, ".codex-global-state.json")
}
func readCodexGlobalState(home string) (map[string]any, error) {
path := codexGlobalStatePath(home)
state := map[string]any{}
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return state, nil
}
return nil, err
}
if strings.TrimSpace(string(data)) == "" {
return state, nil
}
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
if state == nil {
state = map[string]any{}
}
return state, nil
}
func writeCodexGlobalState(home string, state map[string]any) error {
return atomicWriteJSON(codexGlobalStatePath(home), state)
}
func updateCodexGlobalStateForProjectlessMove(home string, lookup sessionLookupResult) error {
return updateCodexGlobalStateForSession(home, lookup, "", true)
}
func updateCodexGlobalStateForWorkspaceMove(home string, lookup sessionLookupResult, targetCWD string) error {
return updateCodexGlobalStateForSession(home, lookup, targetCWD, false)
}
func updateCodexGlobalStateForSession(home string, lookup sessionLookupResult, targetCWD string, projectless bool) error {
state, err := readCodexGlobalState(home)
if err != nil {
return err
}
ids := lookup.allIDs()
canonical := lookup.canonicalOr("")
if canonical != "" {
ids = appendSessionIDVariants(ids, canonical)
}
ids = uniqueNonEmptyStrings(ids)
bareIDs := uniqueBareSessionIDs(ids)
idSet := map[string]bool{}
for _, id := range ids {
idSet[id] = true
idSet[bareSessionID(id)] = true
}
if projectless {
existing := stringsFromAnySlice(state["projectless-thread-ids"])
state["projectless-thread-ids"] = uniqueNonEmptyStrings(append(existing, bareIDs...))
} else {
var next []string
for _, id := range stringsFromAnySlice(state["projectless-thread-ids"]) {
if !idSet[id] {
next = append(next, id)
}
}
if len(next) > 0 {
state["projectless-thread-ids"] = next
} else {
delete(state, "projectless-thread-ids")
}
}
removeGlobalStateMapEntries(state, "thread-workspace-root-hints", idSet)
removeGlobalStateMapEntries(state, "thread-project-assignments", idSet)
if !projectless && strings.TrimSpace(targetCWD) != "" {
ensureGlobalStateWorkspaceRoot(state, "electron-saved-workspace-roots", targetCWD)
ensureGlobalStateWorkspaceRoot(state, "project-order", targetCWD)
hints := mapFromAny(state["thread-workspace-root-hints"])
for _, id := range bareIDs {
hints[id] = targetCWD
}
state["thread-workspace-root-hints"] = hints
}
return writeCodexGlobalState(home, state)
}
func ensureGlobalStateWorkspaceRoot(state map[string]any, key, targetCWD string) {
targetCWD = toDesktopWorkspacePath(targetCWD)
if strings.TrimSpace(targetCWD) == "" {
return
}
roots := pathArray(state[key])
state[key] = dedupePaths(append(roots, targetCWD))
}
func removeGlobalStateMapEntries(state map[string]any, key string, ids map[string]bool) {
values := mapFromAny(state[key])
if len(values) == 0 {
return
}
for id := range ids {
delete(values, id)
}
if len(values) == 0 {
delete(state, key)
return
}
state[key] = values
}
func mapFromAny(value any) map[string]any {
typed, ok := value.(map[string]any)
if !ok || typed == nil {
return map[string]any{}
}
next := map[string]any{}
for key, item := range typed {
next[key] = item
}
return next
}
func stringsFromAnySlice(value any) []string {
switch items := value.(type) {
case []any:
values := make([]string, 0, len(items))
for _, item := range items {
if text := strings.TrimSpace(stringFromAny(item)); text != "" {
values = append(values, text)
}
}
return values
case []string:
values := make([]string, 0, len(items))
for _, item := range items {
if text := strings.TrimSpace(item); text != "" {
values = append(values, text)
}
}
return values
default:
return nil
}
}
func uniqueBareSessionIDs(ids []string) []string {
values := make([]string, 0, len(ids))
for _, id := range ids {
values = append(values, bareSessionID(id))
}
return uniqueNonEmptyStrings(values)
}
func createSessionDeleteBackup(lookup sessionLookupResult) (string, error) {
root := filepath.Join(stateDir(), "deleted-sessions")
if err := os.MkdirAll(root, 0o755); err != nil {
return "", err
}
tokenBase := time.Now().Format("20060102150405")
if id := sanitizeBackupTokenPart(lookup.canonicalOr("session")); id != "" {
tokenBase += "-" + id
}
token := tokenBase
backupDir := filepath.Join(root, token)
for suffix := 2; fileExists(backupDir); suffix++ {
token = fmt.Sprintf("%s-%d", tokenBase, suffix)
backupDir = filepath.Join(root, token)
}
if err := os.MkdirAll(backupDir, 0o755); err != nil {
return "", err
}
manifest := deletedSessionManifest{
Version: sessionDeleteBackupVersion,
SessionID: lookup.canonicalOr(""),
DeletedAt: time.Now().UTC().Format(time.RFC3339Nano),
Rows: lookup.DBRows,
}
for index, file := range lookup.Files {
backupName := filepath.Join("files", fmt.Sprintf("%02d-%s", index+1, filepath.Base(file.Path)))
if err := copyFileIfExists(file.Path, filepath.Join(backupDir, backupName)); err != nil {
return "", err
}
manifest.Files = append(manifest.Files, deletedSessionFileBackup{OriginalPath: file.Path, BackupName: backupName})
}
if len(manifest.Files) == 0 && len(manifest.Rows) == 0 {
return "", errors.New("没有可备份的会话数据")
}
if err := atomicWriteJSON(filepath.Join(backupDir, "manifest.json"), manifest); err != nil {
return "", err
}
return token, nil
}
func sanitizeBackupTokenPart(value string) string {
value = bareSessionID(value)
var builder strings.Builder
for _, r := range value {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
builder.WriteRune(r)
}
if builder.Len() >= 32 {
break
}
}
return builder.String()
}
func sessionDeleteBackupDir(token string) (string, error) {
token = strings.TrimSpace(token)
if token == "" || filepath.Base(token) != token || strings.Contains(token, string(filepath.Separator)) {
return "", errors.New("撤销令牌无效")
}
return filepath.Join(stateDir(), "deleted-sessions", token), nil
}
func sqliteThreadRowsByIDs(dbPath string, ids []string) ([]sessionSQLiteRow, error) {
ids = uniqueNonEmptyStrings(ids)
if len(ids) == 0 || !fileExists(dbPath) {
return nil, nil
}
db, err := openSQLite(dbPath)
if err != nil {
return nil, err
}
defer db.Close()
columns, err := sqliteTableColumns(db, "threads")
if err != nil || len(columns) == 0 || !containsString(columns, "id") {
return nil, err
}
query := "SELECT * FROM threads WHERE id IN (" + sqlitePlaceholders(len(ids)) + ")"
return querySessionSQLiteRows(db, query, stringsToAny(ids)...)
}
func sqliteThreadRowsByTitle(dbPath, title string, archivedOnly bool) ([]sessionSQLiteRow, error) {
title = strings.TrimSpace(title)
if title == "" || !fileExists(dbPath) {
return nil, nil
}
db, err := openSQLite(dbPath)
if err != nil {
return nil, err
}
defer db.Close()
columns, err := sqliteTableColumns(db, "threads")
if err != nil || len(columns) == 0 || !containsString(columns, "title") {
return nil, err
}
where := "WHERE COALESCE(title, '') = ?"
if archivedOnly && containsString(columns, "archived") {
where += " AND COALESCE(archived, 0) <> 0"
}
order := sqliteSortOrder(columns)
rows, err := querySessionSQLiteRows(db, "SELECT * FROM threads "+where+order+" LIMIT 5", title)
if err != nil || len(rows) > 0 {
return rows, err
}
// Archived rows can be rendered with trimmed or decorated text in the UI, so keep a conservative normalized fallback.
return sqliteThreadRowsByNormalizedTitle(db, title, archivedOnly, columns)
}
func sqliteThreadRowsByNormalizedTitle(db *sql.DB, title string, archivedOnly bool, columns []string) ([]sessionSQLiteRow, error) {
where := ""
if archivedOnly && containsString(columns, "archived") {
where = "WHERE COALESCE(archived, 0) <> 0"
}
order := sqliteSortOrder(columns)
rows, err := querySessionSQLiteRows(db, "SELECT * FROM threads "+where+order+" LIMIT 200")
if err != nil {
return nil, err
}
target := normalizedSessionTitle(title)
for _, row := range rows {
if normalizedSessionTitle(stringFromAny(row.Values["title"])) == target {
return []sessionSQLiteRow{row}, nil
}
}
return nil, nil
}
func normalizedSessionTitle(title string) string {
return strings.Join(strings.Fields(strings.TrimSpace(title)), " ")
}
func sqliteTableColumns(db *sql.DB, table string) ([]string, error) {
rows, err := db.Query("PRAGMA table_info(" + quoteSQLiteIdentifier(table) + ")")
if err != nil {
return nil, err
}
defer rows.Close()
var columns []string
for rows.Next() {
var cid int
var name, columnType string
var notNull int
var defaultValue any
var pk int
if err := rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &pk); err != nil {
return nil, err
}
columns = append(columns, name)
}
return columns, rows.Err()
}
func querySessionSQLiteRows(db *sql.DB, query string, args ...any) ([]sessionSQLiteRow, error) {