@gemies/sdk 10.2.0 → 10.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @gemies/sdk
2
2
 
3
+ ## 10.3.0
4
+
5
+ ### Chat streams resume after a dropped connection
6
+
7
+ When the connection that carries a turn drops (a network switch, a sleeping tab, a proxy closing an
8
+ idle socket), `useConversationStream` no longer fails the turn. The server numbers every frame of a
9
+ turn (the SSE `id:`) and keeps the newest ones; the client remembers the last number it applied and,
10
+ on a stream that ends without `[DONE]` or fails mid-read, reconnects to
11
+ `GET /v1/chat/turns/:turnId/stream` with exponential backoff and jitter and carries on. A frame it
12
+ already has is dropped by its number, so a delta is applied once. When the server cannot replay what
13
+ was missed (the cursor is older than its buffer, or the turn finished meanwhile) it sends one
14
+ `alia.snapshot` of the turn instead, which the client applies idempotently over the reply it is
15
+ drawing. The turn is failed only once the resume is refused or its attempts are spent, and then as a
16
+ cut stream always was: `hasUsableStreamOutput` decides whether the person keeps an answer.
17
+
18
+ A server that does not number its frames is read exactly as before. Nothing is added to the public
19
+ API: the reconnect lives inside the hook.
20
+
3
21
  ## 10.2.0
4
22
 
5
23
  ### The files an agent changed, as a diff
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemies/sdk",
3
- "version": "10.2.0",
3
+ "version": "10.3.0",
4
4
  "description": "The Gemies SDK: the conversation runtime, chat UI, voice calls and dictation for Oxy apps that talk to a gemie",
5
5
  "main": "src/index.ts",
6
6
  "react-native": "src/index.ts",
@@ -0,0 +1,306 @@
1
+ /**
2
+ * The frames of a chat turn's stream, kept whole across a dropped connection.
3
+ *
4
+ * A mobile network switch, a sleeping tab or a proxy that closed an idle socket cuts the stream
5
+ * while the turn runs on in the server. The turn is not lost: the server numbers every frame it
6
+ * writes (the SSE `id:`) and keeps the newest ones (`docs/chat-runtime.mdx`, "Resuming a stream").
7
+ * This module is the client's half. It reads the stream's frames, remembers the number of the last
8
+ * one it passed on, and when the connection ends WITHOUT the terminator, or fails mid-read, opens
9
+ * `GET /v1/chat/turns/:turnId/stream` from that number, with exponential backoff and jitter, and
10
+ * carries on. The reader above it never sees the seam:
11
+ *
12
+ * - A frame it already has (a replay that overlaps, the same frame on two connections) is dropped
13
+ * by its number, so a delta is applied once.
14
+ * - A `alia.snapshot` (the cursor was older than the server's buffer, or the turn finished while
15
+ * the client was away) is turned into the frames the reader already understands: a reset of the
16
+ * words and the reasoning, then the words, the reasoning, each tool call and result the reader
17
+ * does not have yet, and the turn's other frames newer than its cursor. Applying one twice
18
+ * leaves the same message.
19
+ * - A turn that cannot be resumed (another person's, one the server no longer knows, a server
20
+ * that does not number its frames) is a stream that ended early, exactly as before: the reader
21
+ * decides what that means. A turn is only given up on once every attempt is spent.
22
+ *
23
+ * A server that does not number frames is read as before: nothing to dedupe, and a drop is the
24
+ * same failure it always was after one refused reconnect.
25
+ */
26
+
27
+ import { createSseFrameReader, type SseFrame } from './sse-frame-reader';
28
+ import { parseTurnSnapshot, TURN_SNAPSHOT_EVENT, type TurnSnapshot } from './stream-events';
29
+
30
+ /** The frame that tells the reader to empty the reply's words (and reasoning) before a snapshot's. */
31
+ export const TURN_RESET_EVENT = 'alia.turn_reset';
32
+
33
+ const DEFAULT_MAX_ATTEMPTS = 6;
34
+ const DEFAULT_BASE_DELAY_MS = 500;
35
+ const DEFAULT_MAX_DELAY_MS = 8_000;
36
+
37
+ /** A status that will not change by asking again: the turn is not this person's, or is gone. */
38
+ const isFinalStatus = (status: number): boolean =>
39
+ status >= 400 && status < 500 && status !== 408 && status !== 429;
40
+
41
+ /**
42
+ * Exponential backoff with equal jitter: half the step is kept, half is random, so reconnecting
43
+ * clients that were cut together do not return together.
44
+ */
45
+ export function resumeDelayMs(
46
+ attempt: number,
47
+ random: () => number = Math.random,
48
+ baseMs: number = DEFAULT_BASE_DELAY_MS,
49
+ maxMs: number = DEFAULT_MAX_DELAY_MS,
50
+ ): number {
51
+ const step = Math.min(maxMs, baseMs * 2 ** attempt);
52
+ return Math.round(step / 2 + (random() * step) / 2);
53
+ }
54
+
55
+ /** What an aborted wait rejects with: the signal's reason, or an `AbortError` where it carries none. */
56
+ const abortReason = (signal: AbortSignal): unknown =>
57
+ signal.reason ?? Object.assign(new Error('The stream was aborted'), { name: 'AbortError' });
58
+
59
+ function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
60
+ return new Promise((resolve, reject) => {
61
+ if (signal.aborted) return reject(abortReason(signal));
62
+ const timer = setTimeout(() => {
63
+ signal.removeEventListener('abort', onAbort);
64
+ resolve();
65
+ }, ms);
66
+ const onAbort = () => {
67
+ clearTimeout(timer);
68
+ reject(abortReason(signal));
69
+ };
70
+ signal.addEventListener('abort', onAbort, { once: true });
71
+ });
72
+ }
73
+
74
+ export interface ResumableFrameSourceOptions {
75
+ /** The turn's first response, already known to be `ok` with a body. */
76
+ response: Response;
77
+ /** Open the turn's stream again, after the frame numbered `cursor`. */
78
+ reconnect(cursor: number, signal: AbortSignal): Promise<Response>;
79
+ /** The turn's own signal: a Stop or a detach ends the stream, never a resume. */
80
+ signal: AbortSignal;
81
+ maxAttempts?: number;
82
+ baseDelayMs?: number;
83
+ maxDelayMs?: number;
84
+ random?: () => number;
85
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
86
+ }
87
+
88
+ export type FrameRead = { done: true } | { done: false; frames: SseFrame[] };
89
+
90
+ export interface ResumableFrameSource {
91
+ /** The frames of the next chunk, deduped and snapshots expanded; `done` once the turn's stream is over. */
92
+ read(): Promise<FrameRead>;
93
+ /** Stop reading: the reader above has what it needed (an error frame, a refusal). */
94
+ cancel(): void;
95
+ }
96
+
97
+ const text = (data: unknown): SseFrame => ({ event: '', data: JSON.stringify(data) });
98
+
99
+ /** The frames a snapshot stands for, given what the reader already has. */
100
+ function expandSnapshot(
101
+ snapshot: TurnSnapshot,
102
+ cursor: number,
103
+ seen: { calls: Set<string>; results: Set<string> },
104
+ ): SseFrame[] {
105
+ const frames: SseFrame[] = [
106
+ {
107
+ event: TURN_RESET_EVENT,
108
+ data: JSON.stringify({ eventVersion: 1, reasoning: snapshot.reasoning !== undefined }),
109
+ },
110
+ ];
111
+ if (snapshot.content !== '') {
112
+ frames.push(
113
+ text({ choices: [{ index: 0, delta: { content: snapshot.content }, finish_reason: null }] }),
114
+ );
115
+ }
116
+ if (snapshot.reasoning) {
117
+ frames.push({
118
+ event: 'alia.reasoning',
119
+ data: JSON.stringify({ eventVersion: 1, content: snapshot.reasoning }),
120
+ });
121
+ }
122
+ snapshot.toolInvocations.forEach((call, index) => {
123
+ if (!seen.calls.has(call.toolCallId)) {
124
+ seen.calls.add(call.toolCallId);
125
+ frames.push(
126
+ text({
127
+ choices: [
128
+ {
129
+ index: 0,
130
+ delta: {
131
+ tool_calls: [
132
+ {
133
+ index,
134
+ id: call.toolCallId,
135
+ type: 'function',
136
+ function: { name: call.toolName, arguments: call.arguments },
137
+ },
138
+ ],
139
+ },
140
+ finish_reason: null,
141
+ },
142
+ ],
143
+ }),
144
+ );
145
+ }
146
+ if (call.state === 'result' && !seen.results.has(call.toolCallId)) {
147
+ seen.results.add(call.toolCallId);
148
+ frames.push({
149
+ event: 'alia.tool_result',
150
+ data: JSON.stringify({
151
+ eventVersion: 1,
152
+ tool_call_id: call.toolCallId,
153
+ name: call.toolName,
154
+ output: call.result,
155
+ }),
156
+ });
157
+ }
158
+ });
159
+ for (const frame of snapshot.frames) {
160
+ if (frame.seq > cursor) frames.push({ event: frame.event, data: frame.data });
161
+ }
162
+ return frames;
163
+ }
164
+
165
+ export function createResumableFrameSource(
166
+ options: ResumableFrameSourceOptions,
167
+ ): ResumableFrameSource {
168
+ const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
169
+ const random = options.random ?? Math.random;
170
+ const sleep = options.sleep ?? sleepUnlessAborted;
171
+ // Ends with the turn's own signal or with `cancel()`. Linked by hand: this runs on every turn,
172
+ // and `AbortSignal.any` is not in every React Native this package supports.
173
+ const lifetime = new AbortController();
174
+ const followTurn = () => lifetime.abort(options.signal.reason);
175
+ if (options.signal.aborted) followTurn();
176
+ else options.signal.addEventListener('abort', followTurn, { once: true });
177
+ const { signal } = lifetime;
178
+
179
+ let reader = options.response.body?.getReader();
180
+ let decoder = new TextDecoder();
181
+ let frames = createSseFrameReader();
182
+ /** The number of the newest frame passed on. */
183
+ let cursor = 0;
184
+ let sawTerminal = false;
185
+ /**
186
+ * Reconnects spent since the stream last delivered a frame. A connection that opens and drops
187
+ * again without one counts against the same budget, so a flapping link ends instead of looping.
188
+ */
189
+ let attempts = 0;
190
+ const seen = { calls: new Set<string>(), results: new Set<string>() };
191
+
192
+ /** Remember which tool calls and results the reader has, so a snapshot sends only what it lacks. */
193
+ const observe = (frame: SseFrame): void => {
194
+ if (frame.event === 'alia.tool_result') {
195
+ try {
196
+ const id = (JSON.parse(frame.data) as { tool_call_id?: unknown }).tool_call_id;
197
+ if (typeof id === 'string') {
198
+ seen.calls.add(id);
199
+ seen.results.add(id);
200
+ }
201
+ } catch {
202
+ // Not a frame the reader will apply either.
203
+ }
204
+ } else if (frame.event === '' && frame.data.includes('"tool_calls"')) {
205
+ try {
206
+ const parsed = JSON.parse(frame.data) as {
207
+ choices?: Array<{ delta?: { tool_calls?: Array<{ id?: unknown }> } }>;
208
+ };
209
+ for (const call of parsed.choices?.[0]?.delta?.tool_calls ?? []) {
210
+ if (typeof call.id === 'string') seen.calls.add(call.id);
211
+ }
212
+ } catch {
213
+ // Likewise.
214
+ }
215
+ }
216
+ };
217
+
218
+ /** Dedupe by number, expand snapshots, and note the terminator. */
219
+ const accept = (incoming: SseFrame[]): SseFrame[] => {
220
+ const out: SseFrame[] = [];
221
+ for (const frame of incoming) {
222
+ if (frame.id !== undefined) {
223
+ if (frame.id <= cursor) continue;
224
+ const before = cursor;
225
+ cursor = frame.id;
226
+ if (frame.event === TURN_SNAPSHOT_EVENT) {
227
+ const snapshot = parseSnapshot(frame.data);
228
+ if (snapshot) out.push(...expandSnapshot(snapshot, before, seen));
229
+ continue;
230
+ }
231
+ } else if (frame.event === TURN_SNAPSHOT_EVENT) {
232
+ // A stored reply with no number (the buffer is gone): applies whatever the cursor.
233
+ const snapshot = parseSnapshot(frame.data);
234
+ if (snapshot) out.push(...expandSnapshot(snapshot, cursor, seen));
235
+ continue;
236
+ }
237
+ if (frame.data === '[DONE]') sawTerminal = true;
238
+ observe(frame);
239
+ out.push(frame);
240
+ }
241
+ return out;
242
+ };
243
+
244
+ const parseSnapshot = (data: string): TurnSnapshot | null => {
245
+ try {
246
+ return parseTurnSnapshot(JSON.parse(data));
247
+ } catch {
248
+ return null;
249
+ }
250
+ };
251
+
252
+ /** Open the stream again; true once a connection is open, false when resuming is given up. */
253
+ const resume = async (): Promise<boolean> => {
254
+ while (attempts < maxAttempts) {
255
+ await sleep(resumeDelayMs(attempts, random, options.baseDelayMs, options.maxDelayMs), signal);
256
+ attempts++;
257
+ try {
258
+ const response = await options.reconnect(cursor, signal);
259
+ if (response.ok && response.body) {
260
+ reader = response.body.getReader();
261
+ decoder = new TextDecoder();
262
+ frames = createSseFrameReader();
263
+ return true;
264
+ }
265
+ await response.body?.cancel().catch(() => undefined);
266
+ if (isFinalStatus(response.status)) return false;
267
+ } catch (error) {
268
+ if (signal.aborted) throw error;
269
+ }
270
+ }
271
+ return false;
272
+ };
273
+
274
+ return {
275
+ async read(): Promise<FrameRead> {
276
+ let failure: unknown;
277
+ while (true) {
278
+ failure = undefined;
279
+ try {
280
+ if (!reader) return { done: true };
281
+ const { done, value } = await reader.read();
282
+ if (!done) {
283
+ const accepted = accept(frames.push(decoder.decode(value, { stream: true })));
284
+ if (accepted.length > 0) {
285
+ attempts = 0;
286
+ return { done: false, frames: accepted };
287
+ }
288
+ continue;
289
+ }
290
+ if (sawTerminal) return { done: true };
291
+ } catch (error) {
292
+ if (signal.aborted) throw error;
293
+ failure = error;
294
+ }
295
+ // The connection ended without the terminator, or broke: the turn may still be running.
296
+ if (await resume()) continue;
297
+ if (failure !== undefined) throw failure;
298
+ return { done: true };
299
+ }
300
+ },
301
+ cancel() {
302
+ lifetime.abort();
303
+ reader?.cancel().catch(() => undefined);
304
+ },
305
+ };
306
+ }
@@ -18,6 +18,20 @@ export const API_ROUTES = {
18
18
  },
19
19
  /** The answer to an awaited host action, read by the turn that is waiting for it. */
20
20
  hostResults: (turnId: string) => `/v1/chat/turns/${encodeURIComponent(turnId)}/host-results`,
21
+ /**
22
+ * A dropped chat stream, picked up after the frame numbered `cursor` (`runtime/resumable-stream.ts`).
23
+ * The conversation and reply name what the turn was streaming, so a turn that finished meanwhile
24
+ * is answered with its stored reply.
25
+ */
26
+ chatTurnStream: (
27
+ turnId: string,
28
+ resume: { cursor: number; conversationId?: string; assistantMessageId: string },
29
+ ) => {
30
+ const query = new URLSearchParams({ cursor: String(resume.cursor) });
31
+ if (resume.conversationId) query.set('conversationId', resume.conversationId);
32
+ query.set('assistantMessageId', resume.assistantMessageId);
33
+ return `/v1/chat/turns/${encodeURIComponent(turnId)}/stream?${query}`;
34
+ },
21
35
  /** The person's folders and projects (`runtime/collections.ts`). */
22
36
  collections: {
23
37
  list: '/v1/conversations/collections',
@@ -31,6 +31,11 @@ export interface SseFrame {
31
31
  readonly event: string;
32
32
  /** The `data:` payload, trimmed. `[DONE]` is passed through as-is. */
33
33
  readonly data: string;
34
+ /**
35
+ * The frame's `id:`, the turn's sequence number (`resumable-stream.ts`), when it has one. A frame
36
+ * of a server that numbers nothing has none.
37
+ */
38
+ readonly id?: number;
34
39
  }
35
40
 
36
41
  export interface SseFrameReader {
@@ -41,6 +46,7 @@ export interface SseFrameReader {
41
46
  export function createSseFrameReader(): SseFrameReader {
42
47
  let buffer = '';
43
48
  let currentEventType = '';
49
+ let currentId: number | undefined;
44
50
 
45
51
  return {
46
52
  push(chunk: string): SseFrame[] {
@@ -63,19 +69,32 @@ export function createSseFrameReader(): SseFrameReader {
63
69
  continue;
64
70
  }
65
71
 
72
+ // Only a whole number is a sequence number; anything else is a field this client ignores.
73
+ if (line.startsWith('id: ')) {
74
+ const id = line.slice(4).trim();
75
+ currentId = /^\d{1,15}$/.test(id) ? Number(id) : undefined;
76
+ continue;
77
+ }
78
+
66
79
  // A blank line closes a frame. Resetting here is what stops a `data:`
67
80
  // line in the NEXT frame inheriting this frame's event name.
68
81
  if (line === '') {
69
82
  currentEventType = '';
83
+ currentId = undefined;
70
84
  continue;
71
85
  }
72
86
 
73
87
  if (line.startsWith('data: ')) {
74
- frames.push({ event: currentEventType, data: line.slice(6).trim() });
88
+ frames.push({
89
+ event: currentEventType,
90
+ data: line.slice(6).trim(),
91
+ ...(currentId === undefined ? {} : { id: currentId }),
92
+ });
75
93
  // One `data:` line is one frame for this protocol. The event name is
76
94
  // consumed with it, so a second `data:` without its own `event:` is
77
95
  // correctly unnamed rather than inheriting.
78
96
  currentEventType = '';
97
+ currentId = undefined;
79
98
  }
80
99
 
81
100
  // Comments (`: keep-alive`) and any field this client does not read
@@ -155,3 +155,71 @@ export function lockedFeatureOf(error: unknown): string | null {
155
155
  if (!isObject(error) || error.code !== FEATURE_ENTITLEMENT_REQUIRED) return null;
156
156
  return isText(error.feature) ? error.feature : null;
157
157
  }
158
+
159
+ /** The event name of a resume's snapshot of the turn (`resumable-stream.ts`). */
160
+ export const TURN_SNAPSHOT_EVENT = 'alia.snapshot';
161
+
162
+ /** One tool call of a snapshot; `arguments` is the JSON string the wire sends them as. */
163
+ export interface SnapshotToolInvocation {
164
+ toolCallId: string;
165
+ toolName: string;
166
+ state: 'call' | 'result';
167
+ arguments: string;
168
+ result?: unknown;
169
+ }
170
+
171
+ /**
172
+ * The turn's state the server sends when a reconnect cannot be given the frames it missed: the
173
+ * words, the reasoning and the tool calls so far, and the turn's other frames. `seq` is the number
174
+ * the state runs through; `reasoning` is absent when the reader should keep its own.
175
+ */
176
+ export interface TurnSnapshot {
177
+ seq?: number;
178
+ content: string;
179
+ reasoning?: string;
180
+ toolInvocations: SnapshotToolInvocation[];
181
+ frames: Array<{ seq: number; event: string; data: string }>;
182
+ }
183
+
184
+ /** The snapshot a `alia.snapshot` frame carries, or `null` when it is not well-formed. */
185
+ export function parseTurnSnapshot(data: unknown): TurnSnapshot | null {
186
+ if (!isObject(data) || data.eventVersion !== 1 || typeof data.content !== 'string') return null;
187
+ if (data.reasoning !== undefined && typeof data.reasoning !== 'string') return null;
188
+ if (data.seq !== undefined && !(Number.isSafeInteger(data.seq) && (data.seq as number) >= 0)) {
189
+ return null;
190
+ }
191
+ if (!Array.isArray(data.toolInvocations) || !Array.isArray(data.frames)) return null;
192
+
193
+ const toolInvocations: SnapshotToolInvocation[] = [];
194
+ for (const call of data.toolInvocations) {
195
+ if (!isObject(call) || !isText(call.toolCallId) || !isText(call.toolName)) return null;
196
+ if (call.state !== 'call' && call.state !== 'result') return null;
197
+ if (typeof call.arguments !== 'string') return null;
198
+ toolInvocations.push({
199
+ toolCallId: call.toolCallId,
200
+ toolName: call.toolName,
201
+ state: call.state,
202
+ arguments: call.arguments,
203
+ ...(call.result === undefined ? {} : { result: call.result }),
204
+ });
205
+ }
206
+ const frames: TurnSnapshot['frames'] = [];
207
+ for (const frame of data.frames) {
208
+ if (
209
+ !isObject(frame) ||
210
+ !Number.isSafeInteger(frame.seq) ||
211
+ typeof frame.event !== 'string' ||
212
+ typeof frame.data !== 'string'
213
+ ) {
214
+ return null;
215
+ }
216
+ frames.push({ seq: frame.seq as number, event: frame.event, data: frame.data });
217
+ }
218
+ return {
219
+ ...(data.seq === undefined ? {} : { seq: data.seq as number }),
220
+ content: data.content,
221
+ ...(data.reasoning === undefined ? {} : { reasoning: data.reasoning }),
222
+ toolInvocations,
223
+ frames,
224
+ };
225
+ }
@@ -39,7 +39,7 @@ import {
39
39
  } from './approvals';
40
40
  import { type GemieHostTools, HostOutcomeQueue, hostRequest } from './host-tools';
41
41
  import { API_ROUTES } from './routes';
42
- import { createSseFrameReader } from './sse-frame-reader';
42
+ import { createResumableFrameSource, TURN_RESET_EVENT } from './resumable-stream';
43
43
  import {
44
44
  type MemberTurnEvent,
45
45
  lockedFeatureOf,
@@ -949,34 +949,47 @@ export function useConversationStream({
949
949
  // The server has the outcomes this request carried: they are its calls' results now.
950
950
  hostOutcomesRef.current.delivered(outcomes);
951
951
 
952
- const reader = response.body.getReader();
953
- const decoder = new TextDecoder();
954
952
  /**
955
- * Frame reassembly lives in `sse-frame-reader.ts`.
953
+ * Frame reassembly lives in `sse-frame-reader.ts` and the seam across a dropped connection
954
+ * in `resumable-stream.ts`, which reads the turn's frames, drops the ones already applied
955
+ * by their number, and resumes the turn from its last frame when the connection ends
956
+ * before the server said the turn was over.
956
957
  *
957
- * It used to be loose variables here, and that is how the bug happened:
958
- * `buffer` was declared outside the read loop and survived a chunk
959
- * boundary, but the current event name was declared INSIDE it and reset
960
- * on every `reader.read()`. A frame is `event: X\ndata: {…}\n\n`, so any
961
- * frame split between those two lines lost its name, fell through to the
962
- * OpenAI-shaped branch below, found no `choices[0]`, and was dropped in
963
- * silence — most often for the largest payloads, which are the ones that
964
- * do not fit in one read: `alia.title`, `alia.tool_result`,
965
- * `alia.plan_preview`, `alia.agent_start`, `alia.host_action`.
966
- *
967
- * Two pieces of state that must both outlive a chunk are fields of one
968
- * object now, and its test feeds a stream split at every byte offset —
969
- * which is not something a test of this hook could do.
958
+ * Frame reassembly used to be loose variables here, and that is how the bug happened:
959
+ * `buffer` was declared outside the read loop and survived a chunk boundary, but the
960
+ * current event name was declared INSIDE it and reset on every `reader.read()`. A frame is
961
+ * `event: X\ndata: {…}\n\n`, so any frame split between those two lines lost its name,
962
+ * fell through to the OpenAI-shaped branch below, found no `choices[0]`, and was dropped in
963
+ * silence — most often for the largest payloads, which are the ones that do not fit in one
964
+ * read: `alia.title`, `alia.tool_result`, `alia.plan_preview`, `alia.agent_start`,
965
+ * `alia.host_action`. Its test feeds a stream split at every byte offset.
970
966
  */
971
- const sse = createSseFrameReader();
967
+ const turnId = turnControl.id;
968
+ const client = linked.client;
969
+ const source = createResumableFrameSource({
970
+ response,
971
+ signal: controller.signal,
972
+ reconnect: async (cursor, signal) =>
973
+ client.requestAuthenticatedResponse({
974
+ method: 'GET',
975
+ url: API_ROUTES.chatTurnStream(turnId, {
976
+ cursor,
977
+ ...(conversationId && { conversationId }),
978
+ assistantMessageId: assistantMessage.id,
979
+ }),
980
+ headers: { ...(await appAssertionHeaders()), Accept: 'text/event-stream' },
981
+ signal,
982
+ ...(streamFetch ? { fetch: streamFetch } : {}),
983
+ }),
984
+ });
972
985
  let lastOutputAt = 0;
973
986
  /** The server closed the turn: `[DONE]`, or a chunk that carries a finish reason. */
974
987
  let sawTerminal = false;
975
988
 
976
989
  while (true) {
977
- const { done, value } = await reader.read();
990
+ const next = await source.read();
978
991
 
979
- if (done) {
992
+ if (next.done) {
980
993
  // Flush any remaining batched content before checking
981
994
  flushPendingUpdates();
982
995
 
@@ -1000,11 +1013,7 @@ export function useConversationStream({
1000
1013
  break;
1001
1014
  }
1002
1015
 
1003
- // `{ stream: true }`: a multi-byte character split across two reads
1004
- // decodes to U+FFFD without it.
1005
- const chunk = decoder.decode(value, { stream: true });
1006
-
1007
- for (const frame of sse.push(chunk)) {
1016
+ for (const frame of next.frames) {
1008
1017
  const data = frame.data;
1009
1018
  const currentEventType = frame.event;
1010
1019
 
@@ -1036,6 +1045,26 @@ export function useConversationStream({
1036
1045
  setMessages((prev) => prev.filter((m) => m.id !== assistantMessage.id));
1037
1046
  continue;
1038
1047
  }
1048
+ case TURN_RESET_EVENT: {
1049
+ // A snapshot follows (`resumable-stream.ts`): it carries the words, so the
1050
+ // ones this connection built are emptied first and the snapshot applies once.
1051
+ dropPendingUpdates();
1052
+ outputEvidence.realOutputChars = 0;
1053
+ replyText = '';
1054
+ const clearsReasoning = parsed.reasoning === true;
1055
+ setMessages((prev) => {
1056
+ const last = prev[prev.length - 1];
1057
+ if (last?.role !== 'assistant') return prev;
1058
+ const updated = [...prev];
1059
+ updated[updated.length - 1] = {
1060
+ ...last,
1061
+ content: '',
1062
+ ...(clearsReasoning ? { thinking: '' } : {}),
1063
+ };
1064
+ return updated;
1065
+ });
1066
+ continue;
1067
+ }
1039
1068
  case 'alia.reasoning': {
1040
1069
  const content = parsed.content;
1041
1070
  if (content) {
@@ -1243,7 +1272,7 @@ export function useConversationStream({
1243
1272
  flushPendingUpdates();
1244
1273
  settleAssistant('cancelled');
1245
1274
  abortThisTurn();
1246
- reader.cancel().catch(() => {});
1275
+ source.cancel();
1247
1276
  return 'aborted';
1248
1277
  }
1249
1278
  // An agent's feature gate refused the turn before anything was spent: the host
@@ -1252,7 +1281,7 @@ export function useConversationStream({
1252
1281
  if (lockedFeature !== null) {
1253
1282
  setIsLoading(false);
1254
1283
  abortThisTurn();
1255
- reader.cancel().catch(() => {});
1284
+ source.cancel();
1256
1285
  host.onFeatureLocked?.(lockedFeature);
1257
1286
  return settleError();
1258
1287
  }
@@ -1298,7 +1327,7 @@ export function useConversationStream({
1298
1327
  setError(new Error(msg));
1299
1328
  setIsLoading(false);
1300
1329
  abortThisTurn();
1301
- reader.cancel().catch(() => {});
1330
+ source.cancel();
1302
1331
  // A turn that failed after it started carries a run reference:
1303
1332
  // its card says code and reference, never the server's English
1304
1333
  // prose. A refusal without one (a gate, a bad request) keeps its
@@ -1473,7 +1502,7 @@ export function useConversationStream({
1473
1502
  abortThisTurn();
1474
1503
 
1475
1504
  // Break out of the streaming loop
1476
- reader.cancel().catch(() => {});
1505
+ source.cancel();
1477
1506
  return keepFailedTurn(true, errMsg);
1478
1507
  }
1479
1508
  } catch (frameError: unknown) {