-
Notifications
You must be signed in to change notification settings - Fork 53
fix(sessions): recover and resend prompts after "session not found" #3170
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
richardsolomou
wants to merge
2
commits into
main
Choose a base branch
from
posthog-code/recover-stale-session-prompt-send
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
133 changes: 133 additions & 0 deletions
133
packages/core/src/sessions/sessionServicePromptRecovery.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| import type { AgentSession } from "@posthog/shared"; | ||
| import { describe, expect, it, vi } from "vitest"; | ||
| import { SessionService, type SessionServiceDeps } from "./sessionService"; | ||
|
|
||
| const TASK_ID = "task-1"; | ||
| const TASK_RUN_ID = `run-${TASK_ID}`; | ||
|
|
||
| function makeSession(): AgentSession { | ||
| return { | ||
| taskRunId: TASK_RUN_ID, | ||
| taskId: TASK_ID, | ||
| taskTitle: "Test task", | ||
| channel: "", | ||
| events: [], | ||
| startedAt: 1, | ||
| status: "connected", | ||
| isPromptPending: false, | ||
| isCompacting: false, | ||
| promptStartedAt: null, | ||
| pendingPermissions: new Map(), | ||
| pausedDurationMs: 0, | ||
| messageQueue: [], | ||
| optimisticItems: [], | ||
| } as AgentSession; | ||
| } | ||
|
|
||
| function createHarness() { | ||
| const sessions: Record<string, AgentSession> = { | ||
| [TASK_RUN_ID]: makeSession(), | ||
| }; | ||
| const store = { | ||
| getSessions: () => sessions, | ||
| getSessionByTaskId: (taskId: string) => | ||
| Object.values(sessions).find((s) => s.taskId === taskId), | ||
| setSession: vi.fn((session: AgentSession) => { | ||
| sessions[session.taskRunId] = session; | ||
| }), | ||
| updateSession: vi.fn((taskRunId: string, patch: Partial<AgentSession>) => { | ||
| const existing = sessions[taskRunId]; | ||
| if (existing) sessions[taskRunId] = { ...existing, ...patch }; | ||
| }), | ||
| appendOptimisticItem: vi.fn(), | ||
| clearOptimisticItems: vi.fn(), | ||
| }; | ||
| const promptMutate = vi.fn(); | ||
| const deps = { | ||
| store, | ||
| h: { extractSkillButtonId: () => undefined }, | ||
| log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, | ||
| toast: { error: vi.fn(), info: vi.fn() }, | ||
| track: vi.fn(), | ||
| getIsOnline: () => true, | ||
| addDirectoryDialog: { open: false }, | ||
| usageLimit: { show: vi.fn() }, | ||
| trpc: { | ||
| agent: { | ||
| prompt: { mutate: promptMutate }, | ||
| cancel: { mutate: vi.fn().mockResolvedValue(undefined) }, | ||
| onSessionIdleKilled: { | ||
| subscribe: () => ({ unsubscribe: vi.fn() }), | ||
| }, | ||
| }, | ||
| }, | ||
| } as unknown as SessionServiceDeps; | ||
|
|
||
| const service = new SessionService(deps); | ||
| const recoverSpy = vi.spyOn( | ||
| service as unknown as { | ||
| tryAutoRecoverLocalSession: ( | ||
| taskId: string, | ||
| taskRunId: string, | ||
| reason: string, | ||
| ) => Promise<boolean>; | ||
| }, | ||
| "tryAutoRecoverLocalSession", | ||
| ); | ||
| return { service, sessions, store, promptMutate, recoverSpy }; | ||
| } | ||
|
|
||
| type RecoverSpy = ReturnType<typeof createHarness>["recoverSpy"]; | ||
|
|
||
| describe("SessionService prompt recovery on fatal session errors", () => { | ||
| it("recovers the session and resends the prompt once", async () => { | ||
| const { service, promptMutate, recoverSpy } = createHarness(); | ||
| promptMutate | ||
| .mockRejectedValueOnce(new Error(`Session not found: ${TASK_RUN_ID}`)) | ||
| .mockResolvedValueOnce({ stopReason: "end_turn" }); | ||
| recoverSpy.mockResolvedValue(true); | ||
|
|
||
| const result = await service.sendPrompt(TASK_ID, "hello again"); | ||
|
|
||
| expect(result).toEqual({ stopReason: "end_turn" }); | ||
| expect(recoverSpy).toHaveBeenCalledTimes(1); | ||
| expect(promptMutate).toHaveBeenCalledTimes(2); | ||
| }); | ||
|
|
||
| it.each([ | ||
| { | ||
| case: "recovery fails", | ||
| setupRecovery: (spy: RecoverSpy) => spy.mockResolvedValue(false), | ||
| expectedPromptCalls: 1, | ||
| }, | ||
| { | ||
| case: "the resend hits another fatal error", | ||
| setupRecovery: (spy: RecoverSpy) => spy.mockResolvedValue(true), | ||
| expectedPromptCalls: 2, | ||
| }, | ||
| { | ||
| case: "recovery throws", | ||
| setupRecovery: (spy: RecoverSpy) => | ||
| spy.mockRejectedValue(new Error("auth restoring")), | ||
| expectedPromptCalls: 1, | ||
| }, | ||
| ])( | ||
| "surfaces the error state and rethrows when $case", | ||
| async ({ setupRecovery, expectedPromptCalls }) => { | ||
| const { service, store, promptMutate, recoverSpy } = createHarness(); | ||
| promptMutate.mockRejectedValue( | ||
| new Error(`Session not found: ${TASK_RUN_ID}`), | ||
| ); | ||
| setupRecovery(recoverSpy); | ||
|
|
||
| await expect(service.sendPrompt(TASK_ID, "hello again")).rejects.toThrow( | ||
| "Session not found", | ||
| ); | ||
| expect(recoverSpy).toHaveBeenCalledTimes(1); | ||
| expect(promptMutate).toHaveBeenCalledTimes(expectedPromptCalls); | ||
| expect(store.setSession).toHaveBeenCalledWith( | ||
| expect.objectContaining({ taskRunId: TASK_RUN_ID, status: "error" }), | ||
| ); | ||
| }, | ||
| ); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The four test cases share identical scaffolding — mock
promptMutate, mockrecoverSpy, callsendPrompt, assert. Per the team's style guide ("We always prefer parameterised tests"), these should be expressed as a singleit.eachtable that varies the mock return values and the expected outcome, rather than four separateit(...)blocks.Context Used: Do not attempt to comment on incorrect alphabetica... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!