-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathcreate-with-session-id-resume-loads-correct-session.ts
More file actions
364 lines (312 loc) · 9.46 KB
/
Copy pathcreate-with-session-id-resume-loads-correct-session.ts
File metadata and controls
364 lines (312 loc) · 9.46 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
import fs from "fs/promises"
import os from "os"
import path from "path"
import readline from "readline"
import { fileURLToPath } from "url"
import { randomUUID } from "crypto"
import { execa } from "execa"
import type { TaskSessionEntry } from "@roo-code/core/cli"
type StreamEvent = {
type?: string
subtype?: string
requestId?: string
command?: string
taskId?: string
content?: string
code?: string
success?: boolean
done?: boolean
}
const RESUME_TIMEOUT_MS = 180_000
const __dirname = path.dirname(fileURLToPath(import.meta.url))
function parseStreamEvent(line: string): StreamEvent | null {
const trimmed = line.trim()
if (!trimmed.startsWith("{")) {
return null
}
try {
return JSON.parse(trimmed) as StreamEvent
} catch {
return null
}
}
async function listSessions(cliRoot: string, workspacePath: string): Promise<TaskSessionEntry[]> {
const result = await execa("pnpm", ["dev", "list", "sessions", "--workspace", workspacePath, "--format", "json"], {
cwd: cliRoot,
reject: false,
})
if (result.exitCode !== 0) {
throw new Error(`list sessions failed with exit code ${result.exitCode}: ${result.stderr || result.stdout}`)
}
const stdoutLines = result.stdout.split("\n")
const jsonStartIndex = stdoutLines.findIndex((line) => line.trim().startsWith("{"))
if (jsonStartIndex === -1) {
throw new Error(`list sessions output did not contain JSON payload: ${result.stdout}`)
}
const jsonPayload = stdoutLines.slice(jsonStartIndex).join("\n").trim()
let parsed: unknown
try {
parsed = JSON.parse(jsonPayload)
} catch (error) {
throw new Error(
`failed to parse list sessions output as JSON: ${error instanceof Error ? error.message : String(error)}`,
)
}
if (
typeof parsed !== "object" ||
parsed === null ||
!("sessions" in parsed) ||
!Array.isArray((parsed as { sessions?: unknown }).sessions)
) {
throw new Error("list sessions output missing sessions array")
}
return (parsed as { sessions: TaskSessionEntry[] }).sessions
}
async function createSessionWithCustomId(
cliRoot: string,
workspacePath: string,
sessionId: string,
prompt: string,
): Promise<void> {
const result = await execa(
"pnpm",
[
"dev",
"--print",
"--provider",
"openrouter",
"--output-format",
"stream-json",
"--workspace",
workspacePath,
"--create-with-session-id",
sessionId,
prompt,
],
{
cwd: cliRoot,
reject: false,
},
)
if (result.exitCode !== 0) {
throw new Error(
`create-with-session-id failed for ${sessionId} with exit code ${result.exitCode}: ${result.stderr || result.stdout}`,
)
}
const lines = result.stdout.split("\n")
const events = lines.map(parseStreamEvent).filter((event): event is StreamEvent => Boolean(event))
const errorEvent = events.find((event) => event.type === "error")
if (errorEvent) {
throw new Error(
`create-with-session-id emitted error for ${sessionId}: code=${errorEvent.code ?? "none"} content=${errorEvent.content ?? ""}`,
)
}
const completion = events.find((event) => event.type === "result" && event.done === true)
if (!completion) {
throw new Error(`create-with-session-id did not emit final result for ${sessionId}`)
}
if (completion.success !== true) {
throw new Error(`create-with-session-id completed unsuccessfully for ${sessionId}`)
}
}
async function resumeSessionAndSendMarker(
cliRoot: string,
workspacePath: string,
sessionId: string,
messageToken: string,
): Promise<void> {
const pingRequestId = `ping-${Date.now()}`
const messageRequestId = `message-${Date.now()}`
const shutdownRequestId = `shutdown-${Date.now()}`
const messagePrompt = `Resume marker token: ${messageToken}. Reply with exactly "ack-${messageToken}".`
const child = execa(
"pnpm",
[
"dev",
"--print",
"--stdin-prompt-stream",
"--provider",
"openrouter",
"--output-format",
"stream-json",
"--workspace",
workspacePath,
"--session-id",
sessionId,
],
{
cwd: cliRoot,
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
reject: false,
forceKillAfterDelay: 2_000,
},
)
child.stderr?.on("data", (chunk) => {
process.stderr.write(chunk)
})
let pingSent = false
let messageSent = false
let shutdownSent = false
let sawMessageControlDone = false
let sawUserTurnWithMarker = false
let shutdownTaskId: string | undefined
let handlerError: Error | null = null
let timedOut = false
const sendCommand = (command: { command: "ping" | "message" | "shutdown"; requestId: string; prompt?: string }) => {
if (!child.stdin || child.stdin.destroyed) {
return
}
child.stdin.write(`${JSON.stringify(command)}\n`)
}
const timeout = setTimeout(() => {
timedOut = true
handlerError = new Error(
`timed out resuming session ${sessionId} (pingSent=${pingSent}, messageSent=${messageSent}, sawMessageControlDone=${sawMessageControlDone}, sawUserTurnWithMarker=${sawUserTurnWithMarker})`,
)
child.kill("SIGTERM")
}, RESUME_TIMEOUT_MS)
const rl = readline.createInterface({
input: child.stdout!,
crlfDelay: Infinity,
})
rl.on("line", (line) => {
process.stdout.write(`${line}\n`)
const event = parseStreamEvent(line)
if (!event) {
return
}
if (event.type === "system" && event.subtype === "init" && !pingSent) {
pingSent = true
sendCommand({ command: "ping", requestId: pingRequestId })
return
}
if (
event.type === "control" &&
event.subtype === "done" &&
event.command === "ping" &&
event.requestId === pingRequestId &&
!messageSent
) {
messageSent = true
sendCommand({
command: "message",
requestId: messageRequestId,
prompt: messagePrompt,
})
return
}
if (
event.type === "control" &&
event.subtype === "error" &&
event.command === "message" &&
event.requestId === messageRequestId
) {
handlerError = new Error(
`message command failed while resuming ${sessionId}: code=${event.code ?? "unknown"} content=${event.content ?? ""}`,
)
child.kill("SIGTERM")
return
}
if (
event.type === "control" &&
event.subtype === "done" &&
event.command === "message" &&
event.requestId === messageRequestId
) {
sawMessageControlDone = true
return
}
if (event.type === "user" && event.requestId === messageRequestId && event.content?.includes(messageToken)) {
sawUserTurnWithMarker = true
if (!shutdownSent) {
shutdownSent = true
sendCommand({ command: "shutdown", requestId: shutdownRequestId })
}
return
}
if (
event.type === "control" &&
(event.subtype === "ack" || event.subtype === "done") &&
event.command === "shutdown" &&
event.requestId === shutdownRequestId &&
typeof event.taskId === "string"
) {
shutdownTaskId = event.taskId
return
}
if (event.type === "control" && event.subtype === "error" && event.requestId !== shutdownRequestId) {
handlerError = new Error(
`unexpected control error while resuming ${sessionId}: command=${event.command ?? "unknown"} code=${event.code ?? "unknown"} content=${event.content ?? ""}`,
)
child.kill("SIGTERM")
return
}
})
const result = await child
clearTimeout(timeout)
rl.close()
if (handlerError) {
throw handlerError
}
if (timedOut) {
throw new Error(`stream resume for ${sessionId} timed out`)
}
if (result.exitCode !== 0) {
throw new Error(`stream resume for ${sessionId} exited non-zero: ${result.exitCode}`)
}
if (!sawMessageControlDone) {
throw new Error(`did not observe message control completion while resuming ${sessionId}`)
}
if (!sawUserTurnWithMarker) {
throw new Error(`did not observe resumed user marker turn while resuming ${sessionId}`)
}
if (shutdownTaskId !== sessionId) {
throw new Error(
`shutdown taskId did not match resumed session (expected=${sessionId}, actual=${shutdownTaskId ?? "none"})`,
)
}
}
async function main() {
const cliRoot = process.env.ROO_CLI_ROOT
? path.resolve(process.env.ROO_CLI_ROOT)
: path.resolve(__dirname, "../../..")
const workspacePath = await fs.mkdtemp(path.join(os.tmpdir(), "roo-cli-create-session-id-"))
const firstSessionId = randomUUID()
const secondSessionId = randomUUID()
const firstMarker = `FIRST-MARKER-${Date.now()}`
const secondMarker = `SECOND-MARKER-${Date.now()}`
try {
await createSessionWithCustomId(
cliRoot,
workspacePath,
firstSessionId,
`Create first session marker ${firstMarker}. Reply with exactly "ok-${firstMarker}".`,
)
await createSessionWithCustomId(
cliRoot,
workspacePath,
secondSessionId,
`Create second session marker ${secondMarker}. Reply with exactly "ok-${secondMarker}".`,
)
const initialSessions = await listSessions(cliRoot, workspacePath)
if (!initialSessions.some((session) => session.id === firstSessionId)) {
throw new Error(`session list missing first custom session id ${firstSessionId}`)
}
if (!initialSessions.some((session) => session.id === secondSessionId)) {
throw new Error(`session list missing second custom session id ${secondSessionId}`)
}
const resumeMarkerForFirst = `resume-first-${Date.now()}`
await resumeSessionAndSendMarker(cliRoot, workspacePath, firstSessionId, resumeMarkerForFirst)
const resumeMarkerForSecond = `resume-second-${Date.now()}`
await resumeSessionAndSendMarker(cliRoot, workspacePath, secondSessionId, resumeMarkerForSecond)
console.log(`[PASS] created and resumed custom sessions: ${firstSessionId}, ${secondSessionId}`)
} finally {
await fs.rm(workspacePath, { recursive: true, force: true })
}
}
main().catch((error) => {
console.error(`[FAIL] ${error instanceof Error ? error.message : String(error)}`)
process.exit(1)
})