-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsession_actions_test.go
More file actions
279 lines (256 loc) · 10.4 KB
/
session_actions_test.go
File metadata and controls
279 lines (256 loc) · 10.4 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
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func TestMoveThreadWorkspaceUpdatesRolloutAndSQLite(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
sessionID := "019a61dd-9748-7743-9ce9-92b8663a935b"
rolloutPath := filepath.Join(home, ".codex", "sessions", "2026", "05", "28", "rollout-"+sessionID+".jsonl")
writeTestFile(t, rolloutPath, testSessionRolloutLine(sessionID, "/old/project", "Move me")+"\n{\"type\":\"user_message\"}\n")
createTestThreadsTable(t, filepath.Join(home, ".codex", "state_5.sqlite"), sessionID, rolloutPath, "/old/project", "Move me")
writeTestGlobalState(t, home, map[string]any{
"projectless-thread-ids": []any{sessionID, "keep-me"},
"thread-workspace-root-hints": map[string]any{sessionID: "/old/project", "keep-me": "/keep"},
"electron-saved-workspace-roots": []any{"/existing/project"},
"project-order": []any{"/existing/project"},
})
result := handleSessionDataRoute("/move-thread-workspace", map[string]any{"session_id": "local:" + sessionID, "target_cwd": "/new/project"})
if result["status"] != "moved" {
t.Fatalf("move should succeed: %#v", result)
}
data, _ := os.ReadFile(rolloutPath)
firstLine, _ := splitFirstLine(string(data))
var record map[string]any
if err := json.Unmarshal([]byte(firstLine), &record); err != nil {
t.Fatalf("rollout first line should stay json: %v", err)
}
payload := record["payload"].(map[string]any)
if got := stringFromAny(payload["cwd"]); got != "/new/project" {
t.Fatalf("rollout cwd mismatch: %q", got)
}
if got := testThreadCWD(t, filepath.Join(home, ".codex", "state_5.sqlite"), sessionID); got != "/new/project" {
t.Fatalf("sqlite cwd mismatch: %q", got)
}
state := readTestGlobalState(t, home)
if containsAnyString(state["projectless-thread-ids"], sessionID) {
t.Fatalf("projectless ids should remove moved session: %#v", state["projectless-thread-ids"])
}
hints := state["thread-workspace-root-hints"].(map[string]any)
if got := stringFromAny(hints[sessionID]); got != "/new/project" {
t.Fatalf("workspace hint mismatch: %q", got)
}
if got := stringFromAny(hints["keep-me"]); got != "/keep" {
t.Fatalf("unrelated workspace hint should remain: %q", got)
}
if !containsAnyString(state["electron-saved-workspace-roots"], "/new/project") {
t.Fatalf("saved workspace roots should include target project: %#v", state["electron-saved-workspace-roots"])
}
if !containsAnyString(state["project-order"], "/new/project") {
t.Fatalf("project order should include target project: %#v", state["project-order"])
}
}
func TestMoveThreadProjectlessUpdatesGlobalState(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
sessionID := "019a61dd-9748-7743-9ce9-92b8663a935b"
rolloutPath := filepath.Join(home, ".codex", "sessions", "2026", "05", "28", "rollout-"+sessionID+".jsonl")
writeTestFile(t, rolloutPath, testSessionRolloutLine(sessionID, "/project", "Move to chats")+"\n")
createTestThreadsTable(t, filepath.Join(home, ".codex", "state_5.sqlite"), sessionID, rolloutPath, "/project", "Move to chats")
writeTestGlobalState(t, home, map[string]any{
"projectless-thread-ids": []any{"keep-me"},
"thread-workspace-root-hints": map[string]any{sessionID: "/project", "keep-me": "/keep"},
})
result := handleSessionDataRoute("/move-thread-projectless", map[string]any{"session_id": "local:" + sessionID})
if result["status"] != "moved" {
t.Fatalf("projectless move should succeed: %#v", result)
}
state := readTestGlobalState(t, home)
if !containsAnyString(state["projectless-thread-ids"], sessionID) {
t.Fatalf("projectless ids should include moved session: %#v", state["projectless-thread-ids"])
}
hints := state["thread-workspace-root-hints"].(map[string]any)
if _, ok := hints[sessionID]; ok {
t.Fatalf("workspace hint should be removed for projectless session: %#v", hints)
}
if got := stringFromAny(hints["keep-me"]); got != "/keep" {
t.Fatalf("unrelated workspace hint should remain: %q", got)
}
}
func TestExportMarkdownFromRollout(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
sessionID := "019a61dd-9748-7743-9ce9-92b8663a935b"
rolloutPath := filepath.Join(home, ".codex", "sessions", "2026", "05", "28", "rollout-"+sessionID+".jsonl")
lines := []string{
testSessionRolloutLine(sessionID, "/project", "Export Me"),
testRolloutResponseMessage("user", "请总结这个项目"),
testRolloutResponseMessage("assistant", "项目已经整理完成。"),
`{"type":"response_item","payload":{"type":"function_call","name":"exec_command","arguments":"secret tool output"}}`,
`{"type":"response_item","payload":{"type":"reasoning","encrypted_content":"secret reasoning"}}`,
}
writeTestFile(t, rolloutPath, strings.Join(lines, "\n")+"\n")
createTestThreadsTable(t, filepath.Join(home, ".codex", "state_5.sqlite"), sessionID, rolloutPath, "/project", "Export Me")
result := handleSessionDataRoute("/export-markdown", map[string]any{"session_id": sessionID})
if result["status"] != "exported" {
t.Fatalf("export should succeed: %#v", result)
}
if filename := stringFromAny(result["filename"]); !strings.HasSuffix(filename, ".md") {
t.Fatalf("filename should be markdown: %q", filename)
}
markdown := stringFromAny(result["markdown"])
for _, expected := range []string{"# Export Me", "Session ID", "## User", "请总结这个项目", "## Assistant", "项目已经整理完成。"} {
if !strings.Contains(markdown, expected) {
t.Fatalf("markdown missing %q:\n%s", expected, markdown)
}
}
for _, unexpected := range []string{"secret tool output", "secret reasoning"} {
if strings.Contains(markdown, unexpected) {
t.Fatalf("markdown should not include %q:\n%s", unexpected, markdown)
}
}
}
func TestDeleteThreadAndUndoRestoresRolloutAndSQLite(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
sessionID := "019a61dd-9748-7743-9ce9-92b8663a935b"
dbPath := filepath.Join(home, ".codex", "state_5.sqlite")
rolloutPath := filepath.Join(home, ".codex", "sessions", "2026", "05", "28", "rollout-"+sessionID+".jsonl")
contents := testSessionRolloutLine(sessionID, "/project", "Delete me") + "\n{\"type\":\"user_message\"}\n"
writeTestFile(t, rolloutPath, contents)
createTestThreadsTable(t, dbPath, sessionID, rolloutPath, "/project", "Delete me")
deleted := handleSessionDataRoute("/delete", map[string]any{"session_id": sessionID, "title": "Delete me"})
if deleted["status"] != "local_deleted" {
t.Fatalf("delete should succeed: %#v", deleted)
}
if fileExists(rolloutPath) {
t.Fatal("rollout file should be removed after delete")
}
if count := testThreadCount(t, dbPath, sessionID); count != 0 {
t.Fatalf("sqlite row should be removed, count=%d", count)
}
token := stringFromAny(deleted["undo_token"])
if token == "" {
t.Fatal("delete should return undo token")
}
restored := handleSessionDataRoute("/undo", map[string]any{"undo_token": token})
if restored["status"] != "ok" {
t.Fatalf("undo should succeed: %#v", restored)
}
restoredData, err := os.ReadFile(rolloutPath)
if err != nil {
t.Fatalf("rollout file should be restored: %v", err)
}
if string(restoredData) != contents {
t.Fatalf("restored rollout mismatch:\n%s", string(restoredData))
}
if count := testThreadCount(t, dbPath, sessionID); count != 1 {
t.Fatalf("sqlite row should be restored, count=%d", count)
}
}
func testSessionRolloutLine(sessionID, cwd, title string) string {
data, _ := json.Marshal(map[string]any{
"type": "session_meta",
"payload": map[string]any{
"id": sessionID,
"cwd": cwd,
"title": title,
"model_provider": "CodexPlusPlus",
"timestamp": "2026-05-28T10:00:00Z",
},
"timestamp": "2026-05-28T10:00:00Z",
})
return string(data)
}
func testRolloutResponseMessage(role, text string) string {
data, _ := json.Marshal(map[string]any{
"type": "response_item",
"timestamp": "2026-05-28T10:01:00Z",
"payload": map[string]any{
"type": "message",
"role": role,
"content": []any{
map[string]any{"type": "output_text", "text": text},
},
},
})
return string(data)
}
func createTestThreadsTable(t *testing.T, dbPath, sessionID, rolloutPath, cwd, title string) {
t.Helper()
db, err := openSQLite(dbPath)
if err != nil {
t.Fatalf("failed to open test sqlite db: %v", err)
}
defer db.Close()
if _, err := db.Exec(`CREATE TABLE threads (
id TEXT PRIMARY KEY,
rollout_path TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
model_provider TEXT NOT NULL,
cwd TEXT NOT NULL,
title TEXT NOT NULL,
archived INTEGER NOT NULL DEFAULT 0,
created_at_ms INTEGER,
updated_at_ms INTEGER
)`); err != nil {
t.Fatalf("failed to create threads table: %v", err)
}
if _, err := db.Exec(`INSERT INTO threads (id, rollout_path, created_at, updated_at, model_provider, cwd, title, archived, created_at_ms, updated_at_ms)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`, sessionID, rolloutPath, 1779962400, 1779962500, "CodexPlusPlus", cwd, title, 1779962400000, 1779962500000); err != nil {
t.Fatalf("failed to insert thread row: %v", err)
}
}
func writeTestGlobalState(t *testing.T, home string, state map[string]any) {
t.Helper()
if err := atomicWriteJSON(filepath.Join(home, ".codex", ".codex-global-state.json"), state); err != nil {
t.Fatalf("failed to write global state: %v", err)
}
}
func readTestGlobalState(t *testing.T, home string) map[string]any {
t.Helper()
var state map[string]any
if err := readJSON(filepath.Join(home, ".codex", ".codex-global-state.json"), &state); err != nil {
t.Fatalf("failed to read global state: %v", err)
}
return state
}
func containsAnyString(value any, expected string) bool {
for _, item := range value.([]any) {
if stringFromAny(item) == expected {
return true
}
}
return false
}
func testThreadCWD(t *testing.T, dbPath, sessionID string) string {
t.Helper()
db, err := openSQLite(dbPath)
if err != nil {
t.Fatalf("failed to open test sqlite db: %v", err)
}
defer db.Close()
var cwd string
if err := db.QueryRow(`SELECT cwd FROM threads WHERE id = ?`, sessionID).Scan(&cwd); err != nil {
t.Fatalf("failed to read cwd: %v", err)
}
return cwd
}
func testThreadCount(t *testing.T, dbPath, sessionID string) int {
t.Helper()
db, err := openSQLite(dbPath)
if err != nil {
t.Fatalf("failed to open test sqlite db: %v", err)
}
defer db.Close()
var count int
if err := db.QueryRow(`SELECT COUNT(*) FROM threads WHERE id = ?`, sessionID).Scan(&count); err != nil {
t.Fatalf("failed to count thread rows: %v", err)
}
return count
}