Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1.4k
fix(sdk,webapp): stop chat losing a message sent right after an action#4234
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
Merged
ericallam
merged 1 commit into
main
from
feature/tri-11952-chatagent-transport-a-send-right-after-an-action-closes-itsJul 11, 2026
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@trigger.dev/sdk": patch | ||
| --- | ||
| Fix a `chat.agent` message-loss race where sending a message right after an action (such as an undo) could drop the follow-up's response from the UI until a refresh. |
7 changes: 5 additions & 2 deletions
7 apps/webapp/app/routes/realtime.v1.sessions.$session.$io.append.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
4 changes: 2 additions & 2 deletions
4 ...ojects.$projectParam.env.$envParam.playground.realtime.v1.sessions.$session.$io.append.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
12 changes: 6 additions & 6 deletions
12 apps/webapp/app/services/realtime/s2realtimeStreams.server.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
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 |
|---|---|---|
| @@ -583,21 +583,25 @@ Signals that the agent's turn is finished — stop reading and wait for user inp | ||
| headers: | ||
| ["trigger-control", "turn-complete"] | ||
| ["public-access-token", "eyJ..."] // optional, refreshed JWT | ||
| ["session-in-event-id", "42"] // optional, agent-internal resume cursor | ||
| ["session-in-event-id", "42"] // optional, send-correlation + resume cursor | ||
| body: "" | ||
| ``` | ||
| | Header | Description | | ||
| | --- | --- | | ||
| | `trigger-control: turn-complete` | Always present on this record. | | ||
| | `public-access-token: <jwt>` (optional) | A refreshed JWT with the same session + run scopes. If present, replace your stored token. | | ||
| | `session-in-event-id: <seq>` (optional) | Internal cursor used by the agent to resume `.in` across worker boots without replaying already-processed user messages. Custom transports should ignore this header — it carries no client-side meaning. | | ||
| | `session-in-event-id: <seq>` (optional) | The agent's committed `.in` cursor for this turn: the seq of the last user record it had consumed when the turn finished. Compare it to the `seq` from your `.in/append` to tell whether this turn-complete is *yours* (see the warning below). Also used internally to resume `.in` across worker boots without replaying processed messages. | | ||
| When you receive this record: | ||
| 1. Update `publicAccessToken` if one is included on the headers. | ||
| 2. Close the stream reader (unless you want to keep it open across turns — see [Resuming a stream](#resuming-a-stream)). | ||
| 3. Wait for the next user message before sending on `.in`. | ||
| <Warning> | ||
| **Correlate turn-completes to your send.** A `turn-complete` on `.out` can belong to an *earlier* turn than the message you just sent, for example a concurrent action (an undo) whose completion lands on the stream first. Only treat a `turn-complete` as terminal for your send if its `session-in-event-id` is greater than or equal to the `seq` returned by that send's `.in/append`; skip any lower one and keep reading. Closing on the wrong turn drops your response until the next reload. The built-in `TriggerChatTransport` does this correlation for you. | ||
| </Warning> | ||
coderabbitai[bot] marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| ### `upgrade-required` control record | ||
| Signals that the agent cannot handle this message on its current version and a new run has been started. Emitted when the agent calls [`chat.requestUpgrade()`](/ai-chat/patterns/version-upgrades). | ||
| @@ -681,7 +685,7 @@ Content-Type: application/json | ||
| `{sessionId}` accepts the same friendly-or-external forms as `.out`. The `publicAccessToken` from session-create authorizes both. | ||
| The body is a JSON-serialized [`ChatInputChunk`](#chatinputchunk) — a tagged union covering messages, stops, and actions. Send them as raw JSON strings (not wrapped in a `data` field). On success the response is `200 OK` with body `{ "ok": true }`; on failure it's `4xx`/`5xx` with `{ "ok": false, "error": "<message>" }`. Common failures: | ||
| The body is a JSON-serialized [`ChatInputChunk`](#chatinputchunk), a tagged union covering messages, stops, and actions. Send them as raw JSON strings (not wrapped in a `data` field). On success the response is `200 OK` with body `{ "ok": true, "seq": <number> }`, where `seq` is the appended record's `.in` sequence number. Use it to correlate this send to the turn that consumes it (see [`turn-complete` control record](#turn-complete-control-record)). On failure it's `4xx`/`5xx` with `{ "ok": false, "error": "<message>" }`. Common failures: | ||
| | Status | When | | ||
| | --- | --- | | ||
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
110 changes: 110 additions & 0 deletions
110 packages/trigger-sdk/test/chat-turn-correlation.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,110 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import type { UIMessage } from "ai"; | ||
| import { TriggerChatTransport, type TriggerChatTransportOptions } from "../src/v3/chat.js"; | ||
| // A send's `.out` stream must close on the turn that consumed its own appended | ||
| // record, not an earlier turn-complete (e.g. a racing undo action). The seq | ||
| // comes back from `/in/append`; correlation headers ride the v2 batch wire. | ||
| function user(text: string, id: string): UIMessage { | ||
| return { id, role: "user", parts: [{ type: "text", text }] }; | ||
| } | ||
| type BatchRecord = { | ||
| body: string; | ||
| seq_num: number; | ||
| timestamp: number; | ||
| headers?: Array<[string, string]>; | ||
| }; | ||
| function batchResponse(records: BatchRecord[]): Response { | ||
| const frames = records | ||
| .map((r) => `event: batch\ndata: ${JSON.stringify({ records: [r] })}\n\n`) | ||
| .join(""); | ||
| return new Response(frames, { | ||
| status: 200, | ||
| headers: { "Content-Type": "text/event-stream", "X-Stream-Version": "v2" }, | ||
| }); | ||
| } | ||
| /** A turn-complete control record whose committed `.in` cursor is `inCursor`. */ | ||
| function turnComplete(seqNum: number, inCursor: number): BatchRecord { | ||
| return { | ||
| body: "", | ||
| seq_num: seqNum, | ||
| timestamp: seqNum, | ||
| headers: [ | ||
| ["trigger-control", "turn-complete"], | ||
| ["session-in-event-id", String(inCursor)], | ||
| ], | ||
| }; | ||
| } | ||
| function textDelta(seqNum: number, text: string): BatchRecord { | ||
| return { | ||
| body: JSON.stringify({ data: { type: "text-delta", id: "t1", delta: text }, id: "m1" }), | ||
| seq_num: seqNum, | ||
| timestamp: seqNum, | ||
| headers: [], | ||
| }; | ||
| } | ||
| function inResponse(seq?: number): Response { | ||
| return new Response(JSON.stringify(seq === undefined ? { ok: true } : { ok: true, seq }), { | ||
| status: 200, | ||
| }); | ||
| } | ||
| async function readDeltas(stream: ReadableStream<unknown>): Promise<string[]> { | ||
| const out: string[] = []; | ||
| const reader = stream.getReader(); | ||
| while (true) { | ||
| const next = await reader.read(); | ||
| if (next.done) return out; | ||
| const chunk = next.value as { type?: string; delta?: string }; | ||
| if (chunk?.type === "text-delta" && typeof chunk.delta === "string") out.push(chunk.delta); | ||
| } | ||
| } | ||
| function makeTransport(out: Response, inSeq: number | undefined) { | ||
| const options: TriggerChatTransportOptions = { | ||
| task: "test-task", | ||
| accessToken: async () => "tok_test", | ||
| sessions: { c1: { publicAccessToken: "tok_test", isStreaming: false } }, | ||
| fetch: async (_url, _init, ctx) => (ctx.endpoint === "in" ? inResponse(inSeq) : out), | ||
| }; | ||
| return new TriggerChatTransport(options); | ||
| } | ||
| async function submit(transport: TriggerChatTransport): Promise<string[]> { | ||
| const stream = await transport.sendMessages({ | ||
| trigger: "submit-message", | ||
| chatId: "c1", | ||
| messageId: undefined, | ||
| messages: [user("hi", "u-1")], | ||
| abortSignal: undefined, | ||
| }); | ||
| return readDeltas(stream); | ||
| } | ||
| describe("transport turn correlation", () => { | ||
| it("skips an earlier turn's turn-complete and closes on its own", async () => { | ||
| // Append seq 5; the undo turn's complete (cursor 4) must be skipped. | ||
| const out = batchResponse([turnComplete(10, 4), textDelta(11, "56"), turnComplete(12, 5)]); | ||
| const deltas = await submit(makeTransport(out, 5)); | ||
| expect(deltas).toEqual(["56"]); | ||
| }); | ||
| it("does not skip when the turn-complete is at the send's own seq", async () => { | ||
| const out = batchResponse([textDelta(10, "56"), turnComplete(11, 5)]); | ||
| const deltas = await submit(makeTransport(out, 5)); | ||
| expect(deltas).toEqual(["56"]); | ||
| }); | ||
| it("without an append seq, closes on the first turn-complete (legacy webapp)", async () => { | ||
| // No seq => no baseline => old behavior: close on the first turn-complete. | ||
| const out = batchResponse([turnComplete(10, 4), textDelta(11, "56"), turnComplete(12, 5)]); | ||
| const deltas = await submit(makeTransport(out, undefined)); | ||
| expect(deltas).toEqual([]); | ||
| }); | ||
| }); |
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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.
Uh oh!
There was an error while loading. Please reload this page.