You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 77fb02d
Browse filesBrowse the repository at this point in the historyBrowse files
Fix `AgentChat` returning another turn's reply, or several replies joined together, instead of the answer to the message you sent: for example when continuing a chat without a saved `lastEventId`, sending two messages in a row, or when a run answers earlier messages first. Agents now mark where each turn starts and where steered messages join one on the output stream, so redeploy them on this version; with an older agent, a reply `AgentChat` can't match to your message is delivered when its turn completes instead of streamed. Custom readers of the session output stream must skip control records they don't recognise. A send aborted before its stream starts now asks the agent to stop.
Copy file name to clipboardExpand all lines: docs/ai-chat/backend.mdx
+2Lines changed: 2 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -195,6 +195,8 @@ await waitUntilComplete();
195
195
|`chat.stream.append(value, options?)`| Append raw data |
196
196
|`chat.stream.read(runId, options?)`| Read the stream by run ID |
197
197
198
+
The first write a turn makes to the stream also marks where the turn starts, so an `await chat.stream.append()` in `onTurnStart` or `onChatStart` takes one extra append to return (it writes that marker first).
199
+
198
200
For piping streams from subtasks to the parent chat (via `target: "root"`), see the [Sub-agents pattern](/ai-chat/patterns/sub-agents).
Copy file name to clipboardExpand all lines: docs/ai-chat/client-protocol.mdx
+29Lines changed: 29 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -398,6 +398,10 @@ if (controlValue === "upgrade-required") {
398
398
// by the time this arrives — subsequent chunks are from the new run...
399
399
continue;
400
400
}
401
+
// Any other control record (`turn-start`, `turn-join`, and subtypes added
402
+
// later): its body is empty, so never parse it. Ignore it, or use it as
403
+
// described under "Which turn a record belongs to".
404
+
if (controlValue) continue;
401
405
402
406
// Otherwise: data record. Parse the body, dispatch the UIMessageChunk.
403
407
const { data: chunk } = JSON.parse(record.body);
@@ -627,6 +631,31 @@ When you receive this record:
627
631
628
632
The built-in clients handle this transparently.
629
633
634
+
### Which turn a record belongs to
635
+
636
+
`session.out` can carry more than one turn: a replacement run answering several unanswered messages in order, a message another client sent just before yours, or the retained tail of an earlier turn when you read without a cursor. Two control records say whose turn the records after them belong to. A custom reader that doesn't need this can ignore both (they have empty bodies, like every control record), as the built-in clients did before them.
637
+
638
+
```
639
+
headers:
640
+
["trigger-control", "turn-start"]
641
+
["turn-start-in-seq", "<seq>"] // optional
642
+
body: ""
643
+
```
644
+
645
+
`turn-start` is the first record the agent writes for a turn. `turn-start-in-seq` is the `.in` seq of the message that turn answers, the same number your `.in/append` returned for it. It is absent for a turn that answers no `.in` message (one started from the run's start payload, such as a head start), which is nobody's own turn. A reader waiting on its own send keeps the records after a `turn-start` whose seq equals its own and drops the records after any other, up to the next `turn-complete`.
646
+
647
+
```
648
+
headers:
649
+
["trigger-control", "turn-join"]
650
+
["turn-start-in-seq", "<seq>,<seq>"]
651
+
["turn-join-injection-id", "<id>"] // optional
652
+
body: ""
653
+
```
654
+
655
+
`turn-join` is written in the middle of a turn when [pending messages](/ai-chat/pending-messages) are folded into it: those messages get no turn of their own, and what the turn writes from here on answers them. The header lists their `.in` seqs. The previous step's last records can still arrive just after it, `start-step` included, because the record is appended directly while the step's chunks are batched. `turn-join-injection-id` is the `id` of the `data-pending-message-injected` chunk the agent writes into the turn for those messages, between the previous step and the one that follows the injection. When the turn's output goes out through the agent's managed response (a `streamText` result returned from `run`, or from a `chat.createSession` turn), that chunk is ordered with the step's own chunks, so a reader that takes the rest of the turn should start right after it. The agent writes the header only then. With `chat.pipe`, or an agent that pipes the model output itself, the chunk goes out on a separate pipe and can land after the step it should precede, so the header is absent: start at the next `start-step` chunk instead, as you do for an older agent's join. The turn's `turn-complete` is the reader's boundary from then on, even when its `session-in-event-id` is below the joined seqs (an earlier input or a queued action is still owed): the turn answers the joined messages either way.
656
+
657
+
Only agents on a recent SDK version write these. Against an older agent a reader sees neither, and has to fall back to the `turn-complete` correlation described above.
658
+
630
659
### Resuming a stream
631
660
632
661
If the SSE connection drops, or the server sends an `error` event, reconnect with the `Last-Event-ID` header set to the **last `record.seq_num` you successfully processed** (decoded from the batch body, not the SSE `id:` line, which is a comma-list internal to S2):
Copy file name to clipboardExpand all lines: docs/ai-chat/testing.mdx
+8-2Lines changed: 8 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -244,7 +244,7 @@ Each turn returns:
244
244
```ts
245
245
typeMockChatAgentTurn= {
246
246
chunks:UIMessageChunk[]; // text-delta, tool-call, etc.
247
-
rawChunks:unknown[]; // includes control chunks (turn-complete, errors)
247
+
rawChunks:unknown[]; // includes control chunks (turn-complete, errors), not turn markers
248
248
};
249
249
```
250
250
@@ -611,6 +611,9 @@ function mockChatAgent(
611
611
|`previousRunId`|`string`|`undefined`| Set `payload.previousRunId` on the initial wire payload. Typically paired with `continuation: true`. |
612
612
|`snapshot`|`ChatSnapshotV1`|`undefined`| Pre-seed the snapshot the agent reads at run boot (replaces the real S3 GET). Use to drive resume scenarios with prior history. See [Persistence and replay](/ai-chat/patterns/persistence-and-replay) for the production snapshot model. |
613
613
|`setupLocals`|`({ set }) => void \| Promise<void>`|`undefined`| Callback invoked before `run()` starts. Use `set(key, value)` to inject server-side dependencies (DB clients, service stubs) that the agent reads via `locals.get()`. |
614
+
|`outAppendLatencyMs`|`number`|`0`| Milliseconds each append to the output stream takes to be acknowledged (control records, one-shot appends and the first chunk of each piped stream). For testing timing, such as time to first chunk. |
615
+
|`outPipeLingerMs`|`number`|`0`| Milliseconds each piped chunk lingers before it is acknowledged, modelling the writer's batching so a control record written while a step streams can land ahead of that step's tail. |
616
+
|`omitTurnMarkers`|`boolean`|`false`| Write no `turn-start` or `turn-join` records, as an agent on an older SDK version does, to test how a client behaves against it. |
614
617
615
618
##### Boot modes
616
619
@@ -643,7 +646,10 @@ The harness's initial wire payload depends on `mode`:
643
646
|`getSnapshot()`| The most recently written snapshot, or `undefined` if no snapshot was written. |
644
647
|`close()`| Send a `close` trigger, abort the signal, wait for `run()` to return. Always call at end of test. |
645
648
|`allChunks`| Every `UIMessageChunk` emitted since the harness was created. |
646
-
|`allRawChunks`| Every raw chunk emitted since creation, including control chunks (`trigger:turn-complete`, errors). |
649
+
|`allRawChunks`| Every raw chunk emitted since creation, including control chunks (`trigger:turn-complete`, errors). The `turn-start` and `turn-join` markers the agent writes (see [Which turn a record belongs to](/ai-chat/client-protocol#which-turn-a-record-belongs-to)) are left out, so exact-sequence assertions don't see them; they are in `outRecords`. |
650
+
|`outRecords`| The output stream as a reader sees it: every record with its 1-based `seqNum`, its `headers` (a `trigger-control` entry on control records, none on data records), its `chunk` (data records) and the `at` time it was acknowledged (`TestOutRecord`). |
651
+
|`onOutRecord(listener)`| Call `listener(record)` for each record written to the output stream, after it is in `outRecords`. Returns an unsubscribe function. |
652
+
|`deliverInput(chunk, seqNum)`| Put a record on `session.in` at an explicit seq, without waiting for a turn, the way the server does for an append from any client. Use it to drive several sends in flight, or to host a real `AgentChat` over a fake fetch. |
0 commit comments