|
| 1 | +import type { AgentSession } from "@posthog/shared"; |
| 2 | +import { describe, expect, it, vi } from "vitest"; |
| 3 | +import { SessionService, type SessionServiceDeps } from "./sessionService"; |
| 4 | + |
| 5 | +const TASK_ID = "task-1"; |
| 6 | +const TASK_RUN_ID = `run-${TASK_ID}`; |
| 7 | + |
| 8 | +function makeSession(): AgentSession { |
| 9 | + return { |
| 10 | + taskRunId: TASK_RUN_ID, |
| 11 | + taskId: TASK_ID, |
| 12 | + taskTitle: "Test task", |
| 13 | + channel: "", |
| 14 | + events: [], |
| 15 | + startedAt: 1, |
| 16 | + status: "connected", |
| 17 | + isPromptPending: false, |
| 18 | + isCompacting: false, |
| 19 | + promptStartedAt: null, |
| 20 | + pendingPermissions: new Map(), |
| 21 | + pausedDurationMs: 0, |
| 22 | + messageQueue: [], |
| 23 | + optimisticItems: [], |
| 24 | + } as AgentSession; |
| 25 | +} |
| 26 | + |
| 27 | +function createHarness() { |
| 28 | + const sessions: Record<string, AgentSession> = { |
| 29 | + [TASK_RUN_ID]: makeSession(), |
| 30 | + }; |
| 31 | + const store = { |
| 32 | + getSessions: () => sessions, |
| 33 | + getSessionByTaskId: (taskId: string) => |
| 34 | + Object.values(sessions).find((s) => s.taskId === taskId), |
| 35 | + setSession: vi.fn((session: AgentSession) => { |
| 36 | + sessions[session.taskRunId] = session; |
| 37 | + }), |
| 38 | + updateSession: vi.fn((taskRunId: string, patch: Partial<AgentSession>) => { |
| 39 | + const existing = sessions[taskRunId]; |
| 40 | + if (existing) sessions[taskRunId] = { ...existing, ...patch }; |
| 41 | + }), |
| 42 | + appendOptimisticItem: vi.fn(), |
| 43 | + clearOptimisticItems: vi.fn(), |
| 44 | + }; |
| 45 | + const promptMutate = vi.fn(); |
| 46 | + const deps = { |
| 47 | + store, |
| 48 | + h: { extractSkillButtonId: () => undefined }, |
| 49 | + log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, |
| 50 | + toast: { error: vi.fn(), info: vi.fn() }, |
| 51 | + track: vi.fn(), |
| 52 | + getIsOnline: () => true, |
| 53 | + addDirectoryDialog: { open: false }, |
| 54 | + usageLimit: { show: vi.fn() }, |
| 55 | + trpc: { |
| 56 | + agent: { |
| 57 | + prompt: { mutate: promptMutate }, |
| 58 | + cancel: { mutate: vi.fn().mockResolvedValue(undefined) }, |
| 59 | + onSessionIdleKilled: { |
| 60 | + subscribe: () => ({ unsubscribe: vi.fn() }), |
| 61 | + }, |
| 62 | + }, |
| 63 | + }, |
| 64 | + } as unknown as SessionServiceDeps; |
| 65 | + |
| 66 | + const service = new SessionService(deps); |
| 67 | + const recoverSpy = vi.spyOn( |
| 68 | + service as unknown as { |
| 69 | + tryAutoRecoverLocalSession: ( |
| 70 | + taskId: string, |
| 71 | + taskRunId: string, |
| 72 | + reason: string, |
| 73 | + ) => Promise<boolean>; |
| 74 | + }, |
| 75 | + "tryAutoRecoverLocalSession", |
| 76 | + ); |
| 77 | + return { service, sessions, store, promptMutate, recoverSpy }; |
| 78 | +} |
| 79 | + |
| 80 | +type RecoverSpy = ReturnType<typeof createHarness>["recoverSpy"]; |
| 81 | + |
| 82 | +describe("SessionService prompt recovery on fatal session errors", () => { |
| 83 | + it("recovers the session and resends the prompt once", async () => { |
| 84 | + const { service, promptMutate, recoverSpy } = createHarness(); |
| 85 | + promptMutate |
| 86 | + .mockRejectedValueOnce(new Error(`Session not found: ${TASK_RUN_ID}`)) |
| 87 | + .mockResolvedValueOnce({ stopReason: "end_turn" }); |
| 88 | + recoverSpy.mockResolvedValue(true); |
| 89 | + |
| 90 | + const result = await service.sendPrompt(TASK_ID, "hello again"); |
| 91 | + |
| 92 | + expect(result).toEqual({ stopReason: "end_turn" }); |
| 93 | + expect(recoverSpy).toHaveBeenCalledTimes(1); |
| 94 | + expect(promptMutate).toHaveBeenCalledTimes(2); |
| 95 | + }); |
| 96 | + |
| 97 | + it.each([ |
| 98 | + { |
| 99 | + case: "recovery fails", |
| 100 | + setupRecovery: (spy: RecoverSpy) => spy.mockResolvedValue(false), |
| 101 | + expectedPromptCalls: 1, |
| 102 | + }, |
| 103 | + { |
| 104 | + case: "the resend hits another fatal error", |
| 105 | + setupRecovery: (spy: RecoverSpy) => spy.mockResolvedValue(true), |
| 106 | + expectedPromptCalls: 2, |
| 107 | + }, |
| 108 | + { |
| 109 | + case: "recovery throws", |
| 110 | + setupRecovery: (spy: RecoverSpy) => |
| 111 | + spy.mockRejectedValue(new Error("auth restoring")), |
| 112 | + expectedPromptCalls: 1, |
| 113 | + }, |
| 114 | + ])( |
| 115 | + "surfaces the error state and rethrows when $case", |
| 116 | + async ({ setupRecovery, expectedPromptCalls }) => { |
| 117 | + const { service, store, promptMutate, recoverSpy } = createHarness(); |
| 118 | + promptMutate.mockRejectedValue( |
| 119 | + new Error(`Session not found: ${TASK_RUN_ID}`), |
| 120 | + ); |
| 121 | + setupRecovery(recoverSpy); |
| 122 | + |
| 123 | + await expect(service.sendPrompt(TASK_ID, "hello again")).rejects.toThrow( |
| 124 | + "Session not found", |
| 125 | + ); |
| 126 | + expect(recoverSpy).toHaveBeenCalledTimes(1); |
| 127 | + expect(promptMutate).toHaveBeenCalledTimes(expectedPromptCalls); |
| 128 | + expect(store.setSession).toHaveBeenCalledWith( |
| 129 | + expect.objectContaining({ taskRunId: TASK_RUN_ID, status: "error" }), |
| 130 | + ); |
| 131 | + }, |
| 132 | + ); |
| 133 | +}); |
0 commit comments