-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathcloudTaskUpdateNotifications.test.ts
More file actions
407 lines (382 loc) · 11.2 KB
/
Copy pathcloudTaskUpdateNotifications.test.ts
File metadata and controls
407 lines (382 loc) · 11.2 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
import type { AgentSession, StoredLogEntry } from "@posthog/shared";
import type { CloudTaskUpdatePayload } from "@posthog/shared/domain-types";
import { describe, expect, it, vi } from "vitest";
import { SessionService, type SessionServiceDeps } from "./sessionService";
const TASK_ID = "task-1";
const RUN_ID = "run-1";
function turnComplete(
timestamp?: string,
stopReason = "end_turn",
): StoredLogEntry {
return {
type: "notification",
timestamp,
notification: {
method: "_posthog/turn_complete",
params: { sessionId: RUN_ID, stopReason },
},
};
}
// The agent's JSON-RPC response to `session/prompt`. Real logs carry it next
// to `_posthog/turn_complete` in either order (the two writes race in the
// agent's log stream), so completion cases must ring for both orderings.
function promptResponse(
id: number,
stopReason = "end_turn",
timestamp?: string,
): StoredLogEntry {
return {
type: "notification",
timestamp,
notification: { id, result: { stopReason } },
};
}
// The `session/prompt` request that opens a turn. Its arrival is what arms the
// turn's single completion notification, so realistic sequences pair it with a
// later `turn_complete`.
function sessionPrompt(id: number, timestamp?: string): StoredLogEntry {
return {
type: "notification",
timestamp,
notification: {
id,
method: "session/prompt",
params: { sessionId: RUN_ID, prompt: [] },
},
};
}
function permissionRequest(
requestId: string,
toolCallId: string,
): StoredLogEntry {
return {
type: "notification",
notification: {
method: "_posthog/permission_request",
params: {
requestId,
toolCall: { toolCallId, title: "Run command", kind: "execute" },
options: [],
},
},
};
}
function logsUpdate(
newEntries: StoredLogEntry[],
totalEntryCount: number,
): CloudTaskUpdatePayload {
return {
taskId: TASK_ID,
runId: RUN_ID,
kind: "logs",
newEntries,
totalEntryCount,
};
}
function snapshotUpdate(
newEntries: StoredLogEntry[],
totalEntryCount: number,
): CloudTaskUpdatePayload {
return {
taskId: TASK_ID,
runId: RUN_ID,
kind: "snapshot",
newEntries,
totalEntryCount,
};
}
function createHarness() {
const sessions: Record<string, AgentSession> = {};
const store = {
getSessions: () => sessions,
getSessionByTaskId: (taskId: string) =>
Object.values(sessions).find((s) => s.taskId === taskId),
setSession: (session: AgentSession) => {
sessions[session.taskRunId] = session;
},
updateSession: (taskRunId: string, updates: Partial<AgentSession>) => {
const session = sessions[taskRunId];
if (session) Object.assign(session, updates);
},
appendEvents: (
taskRunId: string,
events: AgentSession["events"],
newLineCount?: number,
) => {
const session = sessions[taskRunId];
if (!session) return;
session.events = [...session.events, ...events];
if (newLineCount !== undefined) {
session.processedLineCount = newLineCount;
}
},
updateCloudStatus: (
taskRunId: string,
fields: { status?: AgentSession["cloudStatus"] },
) => {
const session = sessions[taskRunId];
if (session && fields.status !== undefined) {
session.cloudStatus = fields.status;
}
},
setPendingPermissions: (
taskRunId: string,
permissions: AgentSession["pendingPermissions"],
) => {
const session = sessions[taskRunId];
if (session) session.pendingPermissions = permissions;
},
clearTailOptimisticItems: vi.fn(),
appendOptimisticItem: vi.fn(),
replaceOptimisticWithEvent: vi.fn(),
clearMessageQueue: vi.fn(),
};
let onUpdate: ((update: CloudTaskUpdatePayload) => void) | undefined;
const notifyPromptComplete = vi.fn();
const notifyPermissionRequest = vi.fn();
const enqueueSpeech = vi.fn();
const markActivity = vi.fn();
const noopLog = {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
};
const deps = {
store,
log: noopLog,
notifyPromptComplete,
notifyPermissionRequest,
enqueueSpeech,
taskViewedApi: { markActivity },
getPersistedConfigOptions: () => undefined,
setPersistedConfigOptions: vi.fn(),
adapterStore: {
getAdapter: () => undefined,
setAdapter: vi.fn(),
removeAdapter: vi.fn(),
},
trpc: {
agent: {
onSessionIdleKilled: {
subscribe: () => ({ unsubscribe: vi.fn() }),
},
getPreviewConfigOptions: {
query: vi.fn().mockResolvedValue([]),
},
},
logs: {
readLocalLogs: { query: vi.fn().mockResolvedValue("") },
},
cloudTask: {
onUpdate: {
subscribe: (
_input: unknown,
handlers: { onData: (update: CloudTaskUpdatePayload) => void },
) => {
onUpdate = handlers.onData;
return { unsubscribe: vi.fn() };
},
},
watch: { mutate: vi.fn().mockResolvedValue(undefined) },
unwatch: { mutate: vi.fn().mockResolvedValue(undefined) },
},
},
} as unknown as SessionServiceDeps;
const service = new SessionService(deps);
service.watchCloudTask(TASK_ID, RUN_ID, "https://us.posthog.com", 1);
if (!onUpdate) throw new Error("watchCloudTask did not subscribe");
return {
sendUpdate: (update: CloudTaskUpdatePayload) => onUpdate?.(update),
notifyPromptComplete,
notifyPermissionRequest,
enqueueSpeech,
markActivity,
};
}
describe("cloud task update notifications", () => {
it("does not notify for turn_completes replayed in a snapshot", () => {
const harness = createHarness();
harness.sendUpdate({
taskId: TASK_ID,
runId: RUN_ID,
kind: "snapshot",
newEntries: [turnComplete(), turnComplete(), turnComplete()],
totalEntryCount: 3,
});
expect(harness.notifyPromptComplete).not.toHaveBeenCalled();
expect(harness.markActivity).not.toHaveBeenCalled();
});
// Each case applies a sequence of updates to a fresh harness; `expected` is
// the resulting notify count. Snapshots never ring; each armed turn rings at
// most once even if the producer writes duplicate completion entries.
it.each([
{
label: "a completion event without an armed turn",
updates: [logsUpdate([turnComplete()], 1)],
expected: 0,
},
{
label: "a live turn that starts and completes",
updates: [logsUpdate([sessionPrompt(1), turnComplete()], 2)],
expected: 1,
},
{
label: "several turns each completing",
updates: [
logsUpdate([sessionPrompt(1), turnComplete()], 2),
logsUpdate([sessionPrompt(2), turnComplete()], 4),
],
expected: 2,
},
{
label: "duplicate completion events for one turn",
updates: [
logsUpdate([sessionPrompt(1), turnComplete()], 2),
logsUpdate([turnComplete()], 3),
],
expected: 1,
},
{
label: "a turn whose response precedes turn_complete",
updates: [
logsUpdate([sessionPrompt(1), promptResponse(1), turnComplete()], 3),
],
expected: 1,
},
{
label: "a turn whose response follows turn_complete",
updates: [
logsUpdate([sessionPrompt(1), turnComplete(), promptResponse(1)], 3),
],
expected: 1,
},
{
label: "a duplicate turn_complete after a response-first turn",
updates: [
logsUpdate([sessionPrompt(1), promptResponse(1), turnComplete()], 3),
logsUpdate([turnComplete()], 4),
],
expected: 1,
},
{
label: "several turns with responses on both sides of turn_complete",
updates: [
logsUpdate([sessionPrompt(1), promptResponse(1), turnComplete()], 3),
logsUpdate([sessionPrompt(2), turnComplete(), promptResponse(2)], 6),
],
expected: 2,
},
{
label: "a cancelled turn",
updates: [
logsUpdate(
[
sessionPrompt(1),
promptResponse(1, "cancelled"),
turnComplete(undefined, "cancelled"),
],
3,
),
],
expected: 0,
},
{
// Opening a task mid-turn: its session/prompt is already in history and
// only the turn_complete arrives live. The completion must still ring.
label: "a prompt seen only in the snapshot, completing live",
updates: [
snapshotUpdate([sessionPrompt(1)], 1),
logsUpdate([turnComplete()], 2),
],
expected: 1,
},
])(
"fires the completion notification once per turn: $label",
({ updates, expected }) => {
const harness = createHarness();
for (const update of updates) harness.sendUpdate(update);
expect(harness.notifyPromptComplete).toHaveBeenCalledTimes(expected);
},
);
it("notifies with the task title, stop reason and turn duration, and marks activity", () => {
const harness = createHarness();
harness.sendUpdate(
logsUpdate(
[
sessionPrompt(1, "2026-01-01T00:00:00Z"),
turnComplete("2026-01-01T00:00:45Z"),
],
2,
),
);
expect(harness.notifyPromptComplete).toHaveBeenCalledWith(
"Cloud Task",
"end_turn",
TASK_ID,
45_000,
);
expect(harness.enqueueSpeech).toHaveBeenCalledWith(
expect.objectContaining({ kind: "done", source: "backstop" }),
);
expect(harness.markActivity).toHaveBeenCalledTimes(1);
});
it("keeps the turn duration when the response precedes turn_complete", () => {
const harness = createHarness();
harness.sendUpdate(
logsUpdate(
[
sessionPrompt(1, "2026-01-01T00:00:00Z"),
promptResponse(1, "end_turn", "2026-01-01T00:00:44Z"),
turnComplete("2026-01-01T00:00:45Z"),
],
3,
),
);
expect(harness.notifyPromptComplete).toHaveBeenCalledWith(
"Cloud Task",
"end_turn",
TASK_ID,
45_000,
);
});
it("notifies a pending permission once across repeated snapshots", () => {
const harness = createHarness();
const snapshot = () =>
harness.sendUpdate({
taskId: TASK_ID,
runId: RUN_ID,
kind: "snapshot",
newEntries: [permissionRequest("r1", "t1")],
totalEntryCount: 1,
});
snapshot();
expect(harness.notifyPermissionRequest).toHaveBeenCalledTimes(1);
expect(harness.enqueueSpeech).toHaveBeenCalledWith(
expect.objectContaining({ kind: "needs_input", source: "backstop" }),
);
snapshot();
snapshot();
expect(harness.notifyPermissionRequest).toHaveBeenCalledTimes(1);
});
it("notifies again when the same tool call asks with a new requestId", () => {
const harness = createHarness();
harness.sendUpdate({
taskId: TASK_ID,
runId: RUN_ID,
kind: "snapshot",
newEntries: [permissionRequest("r1", "t1")],
totalEntryCount: 1,
});
expect(harness.notifyPermissionRequest).toHaveBeenCalledTimes(1);
harness.sendUpdate({
taskId: TASK_ID,
runId: RUN_ID,
kind: "permission_request",
requestId: "r2",
toolCall: { toolCallId: "t1", title: "Run command", kind: "execute" },
options: [],
});
expect(harness.notifyPermissionRequest).toHaveBeenCalledTimes(2);
});
});