Stopping a run stores a RUN_FINISHED without threadId/runId, so /connect replay fails with a ZodError
Summary
If a user stops a run, the runtime stores a RUN_FINISHED event that has no threadId and no runId. On the next /connect, the client parses the replayed events, and @ag-ui/core rejects that event because both fields are required. The thread fails to load with a ZodError. It keeps failing until the stored events are gone. For InMemoryAgentRunner, that means until the server restarts.
This is the reload failure in #2974 (screenshot shows ZodError: threadId Required, runId Required). The comment in that issue blames a RUN_ERROR without message. The real cause is this RUN_FINISHED.
Mechanism (main bd39b04c68)
- Stop calls
InMemoryAgentRunner.stop()(packages/runtime/src/v2/runtime/runner/in-memory.ts~917). It setsstopRequestedand callsabortRun(). The agent stream ends with no terminal event. finalizeRunEvents(packages/shared/src/finalize-events.ts~130) adds the missing terminal event:Theif (stopRequested) { appended.push({ type: EventType.RUN_FINISHED } as BaseEvent);as BaseEventcast hides the missing required fields.- The runner stores the event, and
connect()replays it. ProxiedCopilotRuntimeAgent.connect(packages/core/src/agent.ts~596) parses it withtransformHttpEventStream.EventSchemas.parsethrows, becauseRunFinishedEventSchemarequiresthreadId: z.string()andrunId: z.string().
The SQLite runner (sqlite-runner.ts ~328) and the Intelligence runner (intelligence.ts ~672) call the same helper.
Repro
A vitest probe drives InMemoryAgentRunner with a fake agent. The agent streams part of a text message and, on abortRun(), ends without a terminal event. The probe calls run, then stop, then connect, and sends the replay through EventEncoder and the real transformHttpEventStream (@ag-ui/client 0.0.59).
- Stopped run: the replay ends in
{"type":"RUN_FINISHED"}, and parsing throwsZodError [threadId Required, runId Required]. - Control, a run that finishes normally: parse OK.
- Mutation check: take the ids from
RUN_STARTEDand put them on the syntheticRUN_FINISHED. The stopped run then parses OK.
Expected
Stopping a run leaves a thread that reloads. The synthetic RUN_FINISHED carries the run's threadId and runId. Take them from the observed RUN_STARTED (or the run input), and remove the as BaseEvent cast so that the type checker catches this.
Related
- #7368 / PR #7435: same function, but a different defect. That one is event order: closers land after the terminal event. It does not add the ids.
- Refs #2974.
Source: CopilotKit/CopilotKit