-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.test.ts
More file actions
395 lines (342 loc) · 12.5 KB
/
Copy pathnode.test.ts
File metadata and controls
395 lines (342 loc) · 12.5 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
/**
* tests/node.test.ts
*
* Unit tests for OpenCodeNode utility methods:
* - extractLastReply: text / tool-only / empty
* - getSessionStatus: idle / busy / empty session
* - permissionCache: applyEvent permission.asked, idle cleanup, removePendingPermission
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { OpenCodeNode } from "../src/node.js";
import type {
MessageWithParts,
TextPart,
ToolPart,
StepFinishPart,
} from "../src/node.js";
// ── Test helpers ──────────────────────────────────────────────────────────────
function makeNode(): OpenCodeNode {
return new OpenCodeNode(
{ name: "test", url: "http://localhost:9999" },
"opencode",
"test-password"
);
}
/** Build a minimal user MessageWithParts. */
function userMsg(id = "u1"): MessageWithParts {
return { info: { id, sessionID: "s1", role: "user" }, parts: [] };
}
/** Build an assistant MessageWithParts with the given parts. */
function assistantMsg(
parts: MessageWithParts["parts"],
id = "a1"
): MessageWithParts {
return { info: { id, sessionID: "s1", role: "assistant" }, parts };
}
/** Build a TextPart. */
function textPart(text: string): TextPart {
return { id: "p1", sessionID: "s1", messageID: "a1", type: "text", text };
}
/** Build a ToolPart with the given status. */
function toolPart(
tool: string,
status: "pending" | "running" | "completed" | "error",
input?: Record<string, unknown>
): ToolPart {
return {
id: "t1",
sessionID: "s1",
messageID: "a1",
type: "tool",
callID: "c1",
tool,
state: { status, input },
};
}
/** Build a StepFinishPart. */
function stepFinishPart(): StepFinishPart {
return { id: "sf1", sessionID: "s1", messageID: "a1", type: "step-finish" };
}
// ── extractLastReply ──────────────────────────────────────────────────────────
//
// Messages from the API are in ascending order (oldest first, newest last).
// extractLastReply scans from the END of the array and returns the LAST
// (most recent) assistant message found.
describe("extractLastReply", () => {
it("returns text from an assistant message", () => {
const node = makeNode();
const messages: MessageWithParts[] = [
userMsg(),
assistantMsg([textPart("Hello from the agent.")]),
];
expect(node.extractLastReply(messages)).toBe("Hello from the agent.");
});
it("skips user messages and returns the LAST assistant text found", () => {
const node = makeNode();
// Messages are ascending (oldest first). Scan from end → last assistant hit.
const messages: MessageWithParts[] = [
assistantMsg([textPart("first reply")], "a1"),
userMsg(),
assistantMsg([textPart("second reply")], "a2"),
];
// Most recent assistant message is "second reply"
expect(node.extractLastReply(messages)).toBe("second reply");
});
it("returns tool activity summary when first assistant has no text", () => {
const node = makeNode();
const messages: MessageWithParts[] = [
userMsg(),
assistantMsg([toolPart("bash", "running", { command: "make -j4" })]),
];
const result = node.extractLastReply(messages);
expect(result).toContain("[Agent is busy");
expect(result).toContain("bash");
expect(result).toContain("make -j4");
expect(result).toContain("⟳"); // running symbol
});
it("shows ✓ for completed tool and ✗ for error tool", () => {
const node = makeNode();
const messages: MessageWithParts[] = [
userMsg(),
assistantMsg([
toolPart("glob", "completed", { pattern: "**/*.ts" }),
toolPart("bash", "error", { command: "npm test" }),
]),
];
const result = node.extractLastReply(messages);
expect(result).toContain("✓");
expect(result).toContain("✗");
});
it("returns fallback string when assistant message has no parts at all", () => {
const node = makeNode();
const messages: MessageWithParts[] = [userMsg(), assistantMsg([])];
expect(node.extractLastReply(messages)).toBe(
"[Agent started processing — no output yet]"
);
});
it("returns empty string when there are no assistant messages", () => {
const node = makeNode();
expect(node.extractLastReply([])).toBe("");
expect(node.extractLastReply([userMsg()])).toBe("");
});
});
// ── getSessionStatus ──────────────────────────────────────────────────────────
//
// getSessionStatus now reads from the persistent SSE status cache — O(1),
// zero network. Tests inject status directly via injectStatusForTesting().
describe("getSessionStatus", () => {
let node: OpenCodeNode;
beforeEach(() => {
node = makeNode();
});
afterEach(() => {
node.destroy();
vi.restoreAllMocks();
});
it("returns busy when SSE cache has session marked busy", async () => {
node.injectStatusForTesting("s1", { type: "busy" });
const status = await node.getSessionStatus("s1");
expect(status.type).toBe("busy");
});
it("returns idle when session is absent from SSE cache (default)", async () => {
// s1 was never seen in the stream → default idle
const status = await node.getSessionStatus("s1");
expect(status.type).toBe("idle");
});
it("returns idle when SSE cache explicitly has session idle", async () => {
node.injectStatusForTesting("s1", { type: "idle" });
const status = await node.getSessionStatus("s1");
expect(status.type).toBe("idle");
});
it("returns idle when other sessions are busy but not ours", async () => {
node.injectStatusForTesting("ses_abc", { type: "busy" });
node.injectStatusForTesting("ses_def", { type: "busy" });
const status = await node.getSessionStatus("s1");
expect(status.type).toBe("idle");
});
it("returns busy when target session is busy among multiple sessions", async () => {
node.injectStatusForTesting("ses_abc", { type: "busy" });
node.injectStatusForTesting("s1", { type: "busy" });
node.injectStatusForTesting("ses_def", { type: "busy" });
const status = await node.getSessionStatus("s1");
expect(status.type).toBe("busy");
});
});
// ── getSessionStatusFallback ───────────────────────────────────────────────────
//
// The fallback implementation uses message history scanning (step-finish parts).
// Kept for degraded environments where /session/active is unavailable.
describe("getSessionStatusFallback", () => {
let node: OpenCodeNode;
beforeEach(() => {
node = makeNode();
});
afterEach(() => {
vi.restoreAllMocks();
});
function mockMessages(messages: MessageWithParts[]) {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: true,
text: () => Promise.resolve(JSON.stringify(messages)),
})
);
}
it("returns idle when session has no messages", async () => {
mockMessages([]);
const status = await node.getSessionStatusFallback("s1");
expect(status.type).toBe("idle");
});
it("returns idle when no user messages exist", async () => {
mockMessages([assistantMsg([textPart("hello")])]);
const status = await node.getSessionStatusFallback("s1");
expect(status.type).toBe("idle");
});
it("returns idle when last user message is followed by step-finish", async () => {
mockMessages([
userMsg(),
assistantMsg([textPart("Done."), stepFinishPart()]),
]);
const status = await node.getSessionStatusFallback("s1");
expect(status.type).toBe("idle");
});
it("returns busy when last user message has no step-finish after it", async () => {
mockMessages([
userMsg(),
assistantMsg([toolPart("bash", "running", { command: "make" })]),
]);
const status = await node.getSessionStatusFallback("s1");
expect(status.type).toBe("busy");
});
it("uses the LAST user message, not an earlier one", async () => {
mockMessages([
userMsg("u1"),
assistantMsg([textPart("first answer"), stepFinishPart()], "a1"),
userMsg("u2"),
assistantMsg([toolPart("bash", "running", { command: "sleep 30" })], "a2"),
]);
const status = await node.getSessionStatusFallback("s1");
expect(status.type).toBe("busy");
});
it("returns idle when both exchanges are complete", async () => {
mockMessages([
userMsg("u1"),
assistantMsg([textPart("first"), stepFinishPart()], "a1"),
userMsg("u2"),
assistantMsg([textPart("second"), stepFinishPart()], "a2"),
]);
const status = await node.getSessionStatusFallback("s1");
expect(status.type).toBe("idle");
});
});
// ── permissionCache ───────────────────────────────────────────────────────────
//
// Tests for PendingPermission caching via applyEvent() and direct manipulation.
describe("permissionCache", () => {
let node: OpenCodeNode;
beforeEach(() => {
node = makeNode();
});
afterEach(() => {
node.destroy();
vi.restoreAllMocks();
});
it("getPendingPermissions returns [] for an unknown session", () => {
expect(node.getPendingPermissions("ses_unknown")).toEqual([]);
});
it("applyEvent permission.asked stores the permission in permissionCache", () => {
node.applyEventForTesting({
type: "permission.asked",
properties: {
sessionID: "ses_abc",
id: "per_001",
permission: "bash",
patterns: ["rm -rf /tmp/build"],
},
});
const pending = node.getPendingPermissions("ses_abc");
expect(pending).toHaveLength(1);
expect(pending[0]).toEqual({
id: "per_001",
permission: "bash",
patterns: ["rm -rf /tmp/build"],
});
});
it("consecutive permission.asked events append to the list, not overwrite", () => {
node.applyEventForTesting({
type: "permission.asked",
properties: {
sessionID: "ses_abc",
id: "per_001",
permission: "bash",
patterns: ["rm -rf /tmp/build"],
},
});
node.applyEventForTesting({
type: "permission.asked",
properties: {
sessionID: "ses_abc",
id: "per_002",
permission: "write",
patterns: ["/etc/hosts"],
},
});
const pending = node.getPendingPermissions("ses_abc");
expect(pending).toHaveLength(2);
expect(pending[0].id).toBe("per_001");
expect(pending[1].id).toBe("per_002");
});
it("applyEvent session.status idle clears permissionCache for that session", () => {
node.applyEventForTesting({
type: "permission.asked",
properties: {
sessionID: "ses_abc",
id: "per_001",
permission: "bash",
patterns: ["make build"],
},
});
// Confirm it was stored
expect(node.getPendingPermissions("ses_abc")).toHaveLength(1);
// Now emit idle
node.applyEventForTesting({
type: "session.status",
properties: {
sessionID: "ses_abc",
status: { type: "idle" },
},
});
expect(node.getPendingPermissions("ses_abc")).toEqual([]);
});
it("removePendingPermission removes only the specified requestId", () => {
node.injectPermissionForTesting("ses_abc", [
{ id: "per_001", permission: "bash", patterns: ["make"] },
{ id: "per_002", permission: "write", patterns: ["/tmp/out.txt"] },
]);
node.removePendingPermission("ses_abc", "per_001");
const pending = node.getPendingPermissions("ses_abc");
expect(pending).toHaveLength(1);
expect(pending[0].id).toBe("per_002");
});
it("deprecated session.idle event also clears permissionCache for that session", () => {
// session.idle is the deprecated event type — applyEvent handles it the same
// as session.status { type: "idle" }. Both must clear permissionCache.
node.applyEventForTesting({
type: "permission.asked",
properties: {
sessionID: "ses_xyz",
id: "per_dep_001",
permission: "write",
patterns: ["/tmp/dep-test"],
},
});
expect(node.getPendingPermissions("ses_xyz")).toHaveLength(1);
// Emit the deprecated event type
node.applyEventForTesting({
type: "session.idle",
properties: { sessionID: "ses_xyz" },
});
expect(node.getPendingPermissions("ses_xyz")).toEqual([]);
});
});