-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathagent-server.test.ts
More file actions
4167 lines (3814 loc) · 139 KB
/
Copy pathagent-server.test.ts
File metadata and controls
4167 lines (3814 loc) · 139 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 { createHash } from "node:crypto";
import {
lstat,
mkdir,
mkdtemp,
readFile,
readlink,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { ContentBlock } from "@agentclientprotocol/sdk";
import type { Adapter } from "@posthog/shared";
import { zipSync } from "fflate";
import jwt from "jsonwebtoken";
import { type SetupServerApi, setupServer } from "msw/node";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";
import { getSessionJsonlPath } from "../adapters/claude/session/jsonl-hydration";
import type { PermissionMode } from "../execution-mode";
import type { PostHogAPIClient } from "../posthog-api";
import type { ResumeState } from "../resume";
import {
createMockApiClient,
createTaskRun,
createTestRepo,
type TestRepo,
} from "../test/fixtures/api";
import { createPostHogHandlers } from "../test/mocks/msw-handlers";
import type { StoredEntry, TaskRun } from "../types";
import {
AgentServer,
isTurnCompleteNotification,
SSE_KEEPALIVE_INTERVAL_MS,
} from "./agent-server";
import { type JwtPayload, SANDBOX_CONNECTION_AUDIENCE } from "./jwt";
const mockedClaudeSdk = vi.hoisted(() => {
const createSuccessResult = () => ({
type: "result",
subtype: "success",
duration_ms: 100,
duration_api_ms: 50,
is_error: false,
num_turns: 1,
result: "Done",
stop_reason: null,
total_cost_usd: 0.01,
usage: {
input_tokens: 100,
output_tokens: 50,
output_tokens_details: { thinking_tokens: 0 },
cache_read_input_tokens: 0,
cache_creation_input_tokens: 0,
cache_creation: {
ephemeral_1h_input_tokens: 0,
ephemeral_5m_input_tokens: 0,
},
server_tool_use: { web_search_requests: 0, web_fetch_requests: 0 },
service_tier: "standard",
inference_geo: "us",
iterations: [],
speed: "standard",
},
modelUsage: {},
permission_denials: [],
uuid: crypto.randomUUID() as `${string}-${string}-${string}-${string}-${string}`,
session_id: "test-session",
});
const query = vi.fn(
(params: { prompt?: { push?: (message: unknown) => void } }) => {
const queuedMessages: unknown[] = [];
let resolveNext: ((value: IteratorResult<unknown, void>) => void) | null =
null;
let isDone = false;
const flushQueue = () => {
if (!resolveNext) {
return;
}
if (queuedMessages.length > 0) {
const resolve = resolveNext;
resolveNext = null;
resolve({
value: queuedMessages.shift(),
done: false,
});
return;
}
if (isDone) {
const resolve = resolveNext;
resolveNext = null;
resolve({ value: undefined, done: true });
}
};
const enqueue = (message: unknown) => {
if (isDone) {
return;
}
queuedMessages.push(message);
flushQueue();
};
const prompt = params.prompt;
if (prompt && typeof prompt.push === "function") {
const originalPush = prompt.push.bind(prompt);
prompt.push = (message: unknown) => {
originalPush(message);
if (
message &&
typeof message === "object" &&
"uuid" in message &&
typeof message.uuid === "string"
) {
enqueue({
type: "user",
uuid: message.uuid,
parent_tool_use_id: null,
message: {
content: [],
},
});
enqueue(createSuccessResult());
}
};
}
return {
next: vi.fn(() => {
if (queuedMessages.length > 0) {
return Promise.resolve({
value: queuedMessages.shift(),
done: false as const,
});
}
if (isDone) {
return Promise.resolve({
value: undefined,
done: true as const,
});
}
return new Promise<IteratorResult<unknown, void>>((resolve) => {
resolveNext = resolve;
});
}),
return: vi.fn(() => {
isDone = true;
flushQueue();
return Promise.resolve({ value: undefined, done: true as const });
}),
throw: vi.fn((error: Error) => {
isDone = true;
flushQueue();
return Promise.reject(error);
}),
[Symbol.asyncIterator]() {
return this;
},
interrupt: vi.fn(async () => {
isDone = true;
flushQueue();
}),
setPermissionMode: vi.fn().mockResolvedValue(undefined),
setModel: vi.fn().mockResolvedValue(undefined),
setMaxThinkingTokens: vi.fn().mockResolvedValue(undefined),
supportedCommands: vi.fn().mockResolvedValue([]),
supportedModels: vi.fn().mockResolvedValue([]),
mcpServerStatus: vi.fn().mockResolvedValue([]),
accountInfo: vi.fn().mockResolvedValue({}),
rewindFiles: vi.fn().mockResolvedValue({ canRewind: false }),
setMcpServers: vi
.fn()
.mockResolvedValue({ added: [], removed: [], errors: {} }),
streamInput: vi.fn().mockResolvedValue(undefined),
close: vi.fn(),
initializationResult: vi.fn().mockResolvedValue({
result: "success",
commands: [],
models: [],
}),
reconnectMcpServer: vi.fn().mockResolvedValue(undefined),
toggleMcpServer: vi.fn().mockResolvedValue(undefined),
supportedAgents: vi.fn().mockResolvedValue([]),
stopTask: vi.fn().mockResolvedValue(undefined),
applyFlagSettings: vi.fn().mockResolvedValue(undefined),
getContextUsage: vi.fn().mockResolvedValue({}),
reloadPlugins: vi.fn().mockResolvedValue(undefined),
seedReadState: vi.fn().mockResolvedValue(undefined),
readFile: vi.fn().mockResolvedValue(""),
backgroundTasks: vi.fn().mockResolvedValue([]),
[Symbol.asyncDispose]: vi.fn().mockResolvedValue(undefined),
};
},
);
return { query };
});
vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => ({
...(await importOriginal()),
query: mockedClaudeSdk.query,
}));
interface TestableServer {
getInitialPromptOverride(run: TaskRun): string | null;
getClearedPendingUserState(run: TaskRun | null): string[] | null;
clearPendingInitialPromptState(
payload: JwtPayload,
run: TaskRun | null,
): Promise<void>;
detectedPrUrl: string | null;
buildCloudSystemPrompt(
prUrl?: string | null,
slackThreadUrl?: string | null,
inboxReportUrl?: string | null,
): string;
buildDetectedPrContext(prUrl: string): string;
buildSessionSystemPrompt(
prUrl?: string | null,
slackThreadUrl?: string | null,
inboxReportUrl?: string | null,
): string | { append: string };
buildCodexInstructions(systemPrompt: string | { append: string }): string;
getRuntimeAdapter(): Adapter;
buildClaudeCodeSessionMeta(
runtimeAdapter: Adapter,
): { claudeCode: { options: Record<string, unknown> } } | undefined;
resumeState: ResumeState | null;
getNativeGoalForFreshSession(
runtimeAdapter: Adapter,
): ResumeState["nativeGoal"];
}
interface NativeResumeTestServer {
resumeState: ResumeState | null;
prepareNativeResume(
payload: JwtPayload,
posthogAPI: PostHogAPIClient,
preTaskRun: TaskRun | null,
runtimeAdapter: Adapter,
cwd: string,
permissionMode: PermissionMode,
): Promise<{ sessionId: string; warm: boolean } | null>;
}
let nextTestPort = 20000;
function getNextTestPort(): number {
const port = nextTestPort;
nextTestPort += 1;
return port;
}
function exactArrayBuffer(bytes: Uint8Array): ArrayBuffer {
const copy = new Uint8Array(bytes.byteLength);
copy.set(bytes);
return copy.buffer;
}
// The Claude Agent SDK has an internal readMessages() loop that rejects with
// "Query closed before response received" during cleanup. The SDK starts this
// promise in the constructor without a .catch() handler, so the rejection is
// unhandled. We suppress it here to prevent vitest from failing the suite.
type Listener = (...args: unknown[]) => void;
const originalListeners: Listener[] = [];
beforeAll(() => {
originalListeners.push(
...process.rawListeners("unhandledRejection").map((l) => l as Listener),
);
process.removeAllListeners("unhandledRejection");
process.on("unhandledRejection", (reason: unknown) => {
if (
reason instanceof Error &&
reason.message === "Query closed before response received"
) {
return;
}
for (const listener of originalListeners) {
listener(reason);
}
});
});
afterAll(() => {
process.removeAllListeners("unhandledRejection");
for (const listener of originalListeners) {
process.on("unhandledRejection", listener);
}
});
function createTestJwt(
payload: JwtPayload,
privateKey: string,
expiresInSeconds = 3600,
): string {
return jwt.sign(
{ ...payload, aud: SANDBOX_CONNECTION_AUDIENCE },
privateKey,
{
algorithm: "RS256",
expiresIn: expiresInSeconds,
},
);
}
function sessionUpdateEntry(
sessionUpdate: string,
extra: Record<string, unknown> = {},
): StoredEntry {
return {
type: "notification",
timestamp: new Date().toISOString(),
notification: {
jsonrpc: "2.0",
method: "session/update",
params: { update: { sessionUpdate, ...extra } },
},
};
}
// Test RSA key pair (2048-bit, for testing only)
const TEST_PRIVATE_KEY = `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDqh94SYMFsvG4C
Co9BSGjtPr2/OxzuNGr41O4+AMkDQRd9pKO49DhTA4VzwnOvrH8y4eI9N8OQne7B
wpdoouSn4DoDAS/b3SUfij/RoFUSyZiTQoWz0H6o2Vuufiz0Hf+BzlZEVnhSQ1ru
vqSf+4l8cWgeMXaFXgdD5kQ8GjvR5uqKxvO2Env1hMJRKeOOEGgCep/0c6SkMUTX
SeC+VjypVg9+8yPxtIpOQ7XKv+7e/PA0ilqehRQh4fo9BAWjUW1+HnbtsjJAjjfv
ngzIjpajuQVyMi7G79v8OvijhLMJjJBh3TdbVIfi+RkVj/H94UUfKWRfJA0eLykA
VvTiFf0nAgMBAAECggEABkLBQWFW2IXBNAm/IEGEF408uH2l/I/mqSTaBUq1EwKq
U17RRg8y77hg2CHBP9fNf3i7NuIltNcaeA6vRwpOK1MXiVv/QJHLO2fP41Mx4jIC
gi/c7NtsfiprQaG5pnykhP0SnXlndd65bzUkpOasmWdXnbK5VL8ZV40uliInJafE
1Eo9qSYCJxHmivU/4AbiBgygOAo1QIiuuUHcx0YGknLrBaMQETuvWJGE3lxVQ30/
EuRyA3r6BwN2T0z47PZBzvCpg/C1KeoYuKSMwMyEXfl+a8NclqdROkVaenmZpvVH
0lAvFDuPrBSDmU4XJbKCEfwfHjRkiWAFaTrKntGQtQKBgQD/ILoK4U9DkJoKTYvY
9lX7dg6wNO8jGLHNufU8tHhU+QnBMH3hBXrAtIKQ1sGs+D5rq/O7o0Balmct9vwb
CQZ1EpPfa83Thsv6Skd7lWK0JF7g2vVk8kT4nY/eqkgZUWgkfdMp+OMg2drYiIE8
u+sRPTCdq4Tv5miRg0OToX2H/QKBgQDrVR2GXm6ZUyFbCy8A0kttXP1YyXqDVq7p
L4kqyUq43hmbjzIRM4YDN3EvgZvVf6eub6L/3HfKvWD/OvEhHovTvHb9jkwZ3FO+
YQllB/ccAWJs/Dw5jLAsX9O+eIe4lfwROib3vYLnDTAmrXD5VL35R5F0MsdRoxk5
lTCq1sYI8wKBgGA9ZjDIgXAJUjJkwkZb1l9/T1clALiKjjf+2AXIRkQ3lXhs5G9H
8+BRt5cPjAvFsTZIrS6xDIufhNiP/NXt96OeGG4FaqVKihOmhYSW+57cwXWs4zjr
Mx1dwnHKZlw2m0R4unlwy60OwUFBbQ8ODER6gqZXl1Qv5G5Px+Qe3Q25AoGAUl+s
wgfz9r9egZvcjBEQTeuq0pVTyP1ipET7YnqrKSK1G/p3sAW09xNFDzfy8DyK2UhC
agUl+VVoym47UTh8AVWK4R4aDUNOHOmifDbZjHf/l96CxjI0yJOSbq2J9FarsOwG
D9nKJE49eIxlayD6jnM6us27bxwEDF/odSRQlXkCgYEAxn9l/5kewWkeEA0Afe1c
Uf+mepHBLw1Pbg5GJYIZPC6e5+wRNvtFjM5J6h5LVhyb7AjKeLBTeohoBKEfUyUO
rl/ql9qDIh5lJFn3uNh7+r7tmG21Zl2pyh+O8GljjZ25mYhdiwl0uqzVZaINe2Wa
vbMnD1ZQKgL8LHgb02cbTsc=
-----END PRIVATE KEY-----`;
const TEST_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6ofeEmDBbLxuAgqPQUho
7T69vzsc7jRq+NTuPgDJA0EXfaSjuPQ4UwOFc8Jzr6x/MuHiPTfDkJ3uwcKXaKLk
p+A6AwEv290lH4o/0aBVEsmYk0KFs9B+qNlbrn4s9B3/gc5WRFZ4UkNa7r6kn/uJ
fHFoHjF2hV4HQ+ZEPBo70ebqisbzthJ79YTCUSnjjhBoAnqf9HOkpDFE10ngvlY8
qVYPfvMj8bSKTkO1yr/u3vzwNIpanoUUIeH6PQQFo1Ftfh527bIyQI43754MyI6W
o7kFcjIuxu/b/Dr4o4SzCYyQYd03W1SH4vkZFY/x/eFFHylkXyQNHi8pAFb04hX9
JwIDAQAB
-----END PUBLIC KEY-----`;
describe("AgentServer HTTP Mode", () => {
let repo: TestRepo;
let server: AgentServer | undefined;
let mswServer: SetupServerApi;
let appendLogCalls: unknown[][];
let port: number;
beforeEach(async () => {
repo = await createTestRepo("agent-server-http");
appendLogCalls = [];
// Use a unique high port per test to avoid reuse and browser-blocked ports.
port = getNextTestPort();
mswServer = setupServer(
...createPostHogHandlers({
baseUrl: "http://localhost:8000",
onAppendLog: (entries) => appendLogCalls.push(entries),
}),
);
mswServer.listen({ onUnhandledRequest: "bypass" });
});
afterEach(async () => {
if (server) {
await server.stop();
server = undefined;
}
mswServer.close();
await repo.cleanup();
});
const createServer = (
overrides: Partial<ConstructorParameters<typeof AgentServer>[0]> = {},
) => {
server = new AgentServer({
port,
jwtPublicKey: TEST_PUBLIC_KEY,
repositoryPath: repo.path,
apiUrl: "http://localhost:8000",
apiKey: "test-api-key",
projectId: 1,
mode: "interactive",
taskId: "test-task-id",
runId: "test-run-id",
resolveRtkSavings: async () => null,
...overrides,
});
return server;
};
const createToken = (overrides = {}) => {
return createTestJwt(
{
run_id: "test-run-id",
task_id: "test-task-id",
team_id: 1,
user_id: 1,
distinct_id: "test-distinct-id",
mode: "interactive",
...overrides,
},
TEST_PRIVATE_KEY,
);
};
it("replays ACP notifications emitted before cloud session assignment", () => {
const testServer = createServer() as unknown as {
session: { sseController: null } | null;
pendingEvents: Record<string, unknown>[];
preSessionEvents: Record<string, unknown>[];
handleAcpTransportMessage(message: unknown): void;
flushPreSessionEvents(): void;
};
const message = {
method: "session/update",
params: {
update: {
sessionUpdate: "available_commands_update",
availableCommands: [{ name: "goal" }],
},
},
};
testServer.handleAcpTransportMessage(message);
expect(testServer.preSessionEvents).toHaveLength(1);
testServer.session = { sseController: null };
testServer.flushPreSessionEvents();
expect(testServer.preSessionEvents).toHaveLength(0);
expect(testServer.pendingEvents).toContainEqual(
expect.objectContaining({ notification: message }),
);
testServer.session = null;
});
describe("GET /health", () => {
it("returns ok status with active session", async () => {
await createServer().start();
const response = await fetch(`http://localhost:${port}/health`);
const body = await response.json();
expect(response.status).toBe(200);
expect(body).toEqual({
status: "ok",
hasSession: true,
bootMs: expect.any(Number),
sessionInitMs: expect.any(Number),
});
}, 30000);
it("links native agent state before initializing the session", async () => {
const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR;
const originalCodexHome = process.env.CODEX_HOME;
const claudeConfigDir = join(repo.path, ".claude-test");
const codexHome = join(repo.path, ".codex-test");
const agentStateDir = join(repo.path, ".posthog", "agent-state");
process.env.CLAUDE_CONFIG_DIR = claudeConfigDir;
process.env.CODEX_HOME = codexHome;
try {
await createServer({ agentStateDir }).start();
const claudeProjects = join(claudeConfigDir, "projects");
const codexSessions = join(codexHome, "sessions");
expect((await lstat(claudeProjects)).isSymbolicLink()).toBe(true);
expect((await lstat(codexSessions)).isSymbolicLink()).toBe(true);
expect(await readlink(claudeProjects)).toBe(
join(agentStateDir, "claude", "projects"),
);
expect(await readlink(codexSessions)).toBe(
join(agentStateDir, "codex", "sessions"),
);
} finally {
if (originalClaudeConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR;
} else {
process.env.CLAUDE_CONFIG_DIR = originalClaudeConfigDir;
}
if (originalCodexHome === undefined) {
delete process.env.CODEX_HOME;
} else {
process.env.CODEX_HOME = originalCodexHome;
}
}
}, 30000);
});
describe("turn completion", () => {
function stubSessionCleanup(testServer: unknown): {
session: unknown;
cleanupSession: (options?: {
completeEventStream?: boolean;
}) => Promise<void>;
eventStreamSender: {
enqueue: ReturnType<typeof vi.fn>;
stop: ReturnType<typeof vi.fn>;
};
} {
const cleanupServer = testServer as {
session: unknown;
eventStreamSender: {
enqueue: ReturnType<typeof vi.fn>;
stop: ReturnType<typeof vi.fn>;
};
captureCheckpointState: ReturnType<typeof vi.fn>;
cleanupSession: (options?: {
completeEventStream?: boolean;
}) => Promise<void>;
};
cleanupServer.captureCheckpointState = vi.fn(async () => {});
cleanupServer.eventStreamSender = {
enqueue: vi.fn(),
stop: vi.fn(async () => {}),
};
cleanupServer.session = {
payload: { run_id: "run-1" },
pendingHandoffGitState: undefined,
logWriter: { flush: vi.fn(async () => {}) },
acpConnection: { cleanup: vi.fn(async () => {}) },
sseController: { close: vi.fn() },
};
return cleanupServer;
}
it("keeps event ingest open for non-terminal session cleanup", async () => {
const testServer = stubSessionCleanup(createServer());
await testServer.cleanupSession();
expect(testServer.eventStreamSender.enqueue).not.toHaveBeenCalled();
expect(testServer.eventStreamSender.stop).not.toHaveBeenCalled();
});
it("stops event ingest for terminal session cleanup without fake task completion", async () => {
const testServer = stubSessionCleanup(createServer());
await testServer.cleanupSession({ completeEventStream: true });
expect(testServer.eventStreamSender.enqueue).not.toHaveBeenCalled();
expect(testServer.eventStreamSender.stop).toHaveBeenCalledOnce();
});
it("emits rtk savings once before terminal event ingest stops", async () => {
const testServer = stubSessionCleanup(
createServer({
resolveRtkSavings: async () => ({
totalCommands: 4,
inputTokens: 1000,
outputTokens: 350,
tokensSaved: 650,
}),
}),
);
const session = testServer.session;
await testServer.cleanupSession({ completeEventStream: true });
testServer.session = session;
await testServer.cleanupSession({ completeEventStream: true });
expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledOnce();
expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(
expect.objectContaining({
notification: expect.objectContaining({
method: "_posthog/rtk_savings",
params: expect.objectContaining({
task_id: "test-task-id",
run_id: "test-run-id",
team_id: 1,
counter_id: "test-task-id",
cumulative_commands: 4,
cumulative_input_tokens: 1000,
cumulative_output_tokens: 350,
cumulative_tokens_saved: 650,
}),
}),
}),
);
expect(
testServer.eventStreamSender.enqueue.mock.invocationCallOrder[0],
).toBeLessThan(
testServer.eventStreamSender.stop.mock.invocationCallOrder[0],
);
});
it("writes terminal failure status before completing event ingest", async () => {
const order: string[] = [];
const testServer = new AgentServer({
port,
jwtPublicKey: TEST_PUBLIC_KEY,
repositoryPath: repo.path,
apiUrl: "http://localhost:8000",
apiKey: "test-api-key",
projectId: 1,
mode: "interactive",
taskId: "test-task-id",
runId: "test-run-id",
resolveRtkSavings: async () => null,
}) as unknown as {
eventStreamSender: {
enqueue: (event: Record<string, unknown>) => void;
stop: () => Promise<void>;
};
posthogAPI: {
updateTaskRun: (
taskId: string,
runId: string,
payload: Record<string, unknown>,
) => Promise<unknown>;
};
signalTaskComplete(
payload: JwtPayload,
stopReason: string,
errorMessage?: string,
): Promise<void>;
};
testServer.eventStreamSender = {
enqueue: vi.fn(() => {
order.push("enqueue");
}),
stop: vi.fn(async () => {
order.push("stop");
}),
};
testServer.posthogAPI = {
updateTaskRun: vi.fn(async () => {
order.push("update");
return {};
}),
};
await testServer.signalTaskComplete(
{
run_id: "run-1",
task_id: "task-1",
team_id: 1,
user_id: 1,
distinct_id: "distinct-id",
mode: "interactive",
},
"error",
"boom",
);
expect(order).toEqual(["enqueue", "update", "stop"]);
expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(
expect.objectContaining({
type: "notification",
notification: expect.objectContaining({
method: "_posthog/error",
params: expect.objectContaining({ error: "boom" }),
}),
}),
);
expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(
"task-1",
"run-1",
{
status: "failed",
error_message: "boom",
},
);
});
it("still stops event ingest when terminal failure status update fails", async () => {
const testServer = new AgentServer({
port,
jwtPublicKey: TEST_PUBLIC_KEY,
repositoryPath: repo.path,
apiUrl: "http://localhost:8000",
apiKey: "test-api-key",
projectId: 1,
mode: "interactive",
taskId: "test-task-id",
runId: "test-run-id",
resolveRtkSavings: async () => null,
}) as unknown as {
eventStreamSender: {
enqueue: (event: Record<string, unknown>) => void;
stop: () => Promise<void>;
};
posthogAPI: {
updateTaskRun: (
taskId: string,
runId: string,
payload: Record<string, unknown>,
) => Promise<unknown>;
};
signalTaskComplete(
payload: JwtPayload,
stopReason: string,
errorMessage?: string,
): Promise<void>;
};
testServer.eventStreamSender = {
enqueue: vi.fn(),
stop: vi.fn(async () => {}),
};
testServer.posthogAPI = {
updateTaskRun: vi.fn(async () => {
throw new Error("update failed");
}),
};
await testServer.signalTaskComplete(
{
run_id: "run-1",
task_id: "task-1",
team_id: 1,
user_id: 1,
distinct_id: "distinct-id",
mode: "interactive",
},
"error",
"boom",
);
expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledOnce();
expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledOnce();
expect(testServer.eventStreamSender.stop).toHaveBeenCalledOnce();
});
it("leaves event ingest open for non-error stop reasons", async () => {
const testServer = new AgentServer({
port,
jwtPublicKey: TEST_PUBLIC_KEY,
repositoryPath: repo.path,
apiUrl: "http://localhost:8000",
apiKey: "test-api-key",
projectId: 1,
mode: "interactive",
taskId: "test-task-id",
runId: "test-run-id",
}) as unknown as {
eventStreamSender: {
enqueue: (event: Record<string, unknown>) => void;
stop: () => Promise<void>;
};
posthogAPI: {
updateTaskRun: (
taskId: string,
runId: string,
payload: Record<string, unknown>,
) => Promise<unknown>;
};
signalTaskComplete(
payload: JwtPayload,
stopReason: string,
): Promise<void>;
};
testServer.eventStreamSender = {
enqueue: vi.fn(),
stop: vi.fn(async () => {}),
};
testServer.posthogAPI = {
updateTaskRun: vi.fn(async () => ({})),
};
await testServer.signalTaskComplete(
{
run_id: "run-1",
task_id: "task-1",
team_id: 1,
user_id: 1,
distinct_id: "distinct-id",
mode: "interactive",
},
"end_turn",
);
expect(testServer.eventStreamSender.enqueue).not.toHaveBeenCalled();
expect(testServer.eventStreamSender.stop).not.toHaveBeenCalled();
expect(testServer.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
});
function createUsageTestServer() {
const testServer = new AgentServer({
port,
jwtPublicKey: TEST_PUBLIC_KEY,
repositoryPath: repo.path,
apiUrl: "http://localhost:8000",
apiKey: "test-api-key",
projectId: 1,
mode: "interactive",
taskId: "test-task-id",
runId: "test-run-id",
}) as unknown as {
session: { payload: JwtPayload } | null;
posthogAPI: { updateTaskRun: ReturnType<typeof vi.fn> };
recordTurnUsage(usage: unknown): void;
};
testServer.posthogAPI = { updateTaskRun: vi.fn(async () => ({})) };
testServer.session = {
payload: {
run_id: "run-1",
task_id: "task-1",
team_id: 1,
user_id: 1,
distinct_id: "distinct-id",
mode: "interactive",
},
};
return testServer;
}
it("reports cumulative run token usage into TaskRun.state after each settled turn", () => {
const testServer = createUsageTestServer();
const turnUsage = {
inputTokens: 100,
outputTokens: 50,
cachedReadTokens: 10,
cachedWriteTokens: 5,
totalTokens: 165,
};
testServer.recordTurnUsage(turnUsage);
testServer.recordTurnUsage(turnUsage);
expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledTimes(2);
expect(testServer.posthogAPI.updateTaskRun).toHaveBeenNthCalledWith(
1,
"task-1",
"run-1",
{
state: {
token_usage: {
input_tokens: 100,
output_tokens: 50,
cache_read_tokens: 10,
cache_write_tokens: 5,
thought_tokens: 0,
total_tokens: 165,
turns: 1,
},
},
},
);
// The second report carries run-cumulative totals, not per-turn figures.
expect(testServer.posthogAPI.updateTaskRun).toHaveBeenLastCalledWith(
"task-1",
"run-1",
{
state: {
token_usage: {
input_tokens: 200,
output_tokens: 100,
cache_read_tokens: 20,
cache_write_tokens: 10,
thought_tokens: 0,
total_tokens: 330,
turns: 2,
},
},
},
);
});
it("does not report anything when a turn settles without usage", () => {
const testServer = createUsageTestServer();
testServer.recordTurnUsage(undefined);
expect(testServer.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
});
it("resets run usage on session cleanup so a later run starts from zero", async () => {
const testServer = createUsageTestServer();
const turnUsage = {
inputTokens: 100,
outputTokens: 50,
totalTokens: 150,
};
testServer.recordTurnUsage(turnUsage);
const cleanupServer = stubSessionCleanup(testServer);
await cleanupServer.cleanupSession();
testServer.session = {
payload: {
run_id: "run-2",
task_id: "task-1",
team_id: 1,
user_id: 1,
distinct_id: "distinct-id",
mode: "interactive",
},
};
testServer.recordTurnUsage(turnUsage);
expect(testServer.posthogAPI.updateTaskRun).toHaveBeenLastCalledWith(
"task-1",
"run-2",
{
state: {
token_usage: {
input_tokens: 100,
output_tokens: 50,
cache_read_tokens: 0,
cache_write_tokens: 0,
thought_tokens: 0,
total_tokens: 150,
turns: 1,
},
},
},
);
});
function createFailureTestServer() {
const appendRawLine = vi.fn();
const testServer = new AgentServer({
port,
jwtPublicKey: TEST_PUBLIC_KEY,
repositoryPath: repo.path,
apiUrl: "http://localhost:8000",
apiKey: "test-api-key",
projectId: 1,
mode: "interactive",
taskId: "test-task-id",
runId: "test-run-id",
}) as unknown as {
eventStreamSender: {
enqueue: ReturnType<typeof vi.fn>;
stop: ReturnType<typeof vi.fn>;
};
posthogAPI: { updateTaskRun: ReturnType<typeof vi.fn> };
session: unknown;
handleTurnFailure(
payload: JwtPayload,
phase: "initial" | "resume" | "followup",
error: unknown,
): Promise<void>;
};
testServer.eventStreamSender = {
enqueue: vi.fn(),
stop: vi.fn(async () => {}),
};
testServer.posthogAPI = { updateTaskRun: vi.fn(async () => ({})) };
testServer.session = {
acpSessionId: "acp-1",
payload: { run_id: "run-1" },
logWriter: { appendRawLine, flush: vi.fn(async () => {}) },
};
return testServer;
}
const interactivePayload: JwtPayload = {
run_id: "run-1",
task_id: "task-1",
team_id: 1,
user_id: 1,
distinct_id: "distinct-id",
mode: "interactive",
};
it.each([
["genuine agent error (terminal)", "boom", "agent_error", true],
[
"transient upstream timeout (recoverable)",
"API Error: The operation timed out.",
"upstream_timeout",
false,