Skip to content

Commit 085e650

Browse files
tylerslatonclaude
andauthored
OpenBot Mobile: a reply streams again when its run's start never reached the phone (#2761)
The phone joins a conversation's live socket a moment after it sends, when the Bot's run is already under way, and Cloud's gateway replays nothing of that run: its RUN_STARTED never arrives. Every word and step after it was dropped for having no run to go to, so nothing was drawn live and the reply only appeared, in jumps, each time the messages were read again. A run is now taken up from its first event (or from the run the join token names), its end is matched by the run's real id, stream_idle ends any run still drawn as live, and while the socket is quiet on a live run for 8 seconds the messages are read again as well. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8af735b commit 085e650

4 files changed

Lines changed: 182 additions & 14 deletions

File tree

‎mobile/app/conversation.tsx‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ import {
9696
arriving,
9797
asMessages,
9898
caughtUp,
99+
idle,
99100
type LiveRuns,
100101
liveAnswers,
101102
liveStep,
@@ -158,6 +159,8 @@ const AWAIT_MS = 120_000;
158159
const SETTLE_MS = 20_000;
159160
/** How often a conversation with a reply owed or under way is read again while no socket carries it. */
160161
const FOLLOW_MS = 1_500;
162+
/** A live run the socket has said nothing about for this long is followed by reading the messages again too. */
163+
const QUIET_MS = 8_000;
161164

162165
/**
163166
* A conversation: the Bot at the top, what was said, and the message box. The person's messages
@@ -267,6 +270,8 @@ export function Conversation({
267270
const liveNow = useRef(live);
268271
liveNow.current = live;
269272
const watcher = useRef<{ reconnect(): void } | null>(null);
273+
// Whether the socket has gone quiet on a live run: true until it carries an event, and QUIET_MS after its last.
274+
const [quiet, setQuiet] = useState(true);
270275
// The runs Stop was pressed for: they are ending on the server, and the button waits for them.
271276
const [stopAsked, setStopAsked] = useState<ReadonlySet<string>>(new Set());
272277
// Read through a ref, so the socket isn't opened again each time the reloads change who they read for.
@@ -298,28 +303,42 @@ export function Conversation({
298303
}, SETTLE_MS);
299304
settling.add(timer);
300305
};
306+
let quietTimer: ReturnType<typeof setTimeout> | undefined;
307+
const heard = () => {
308+
setQuiet(false);
309+
if (quietTimer) clearTimeout(quietTimer);
310+
quietTimer = setTimeout(() => setQuiet(true), QUIET_MS);
311+
};
301312
const watch = watchConversationLive(channelId, {
302313
onEvent(event, replayed) {
303314
if (replayed) {
304315
replay = reduce(replay ?? liveNow.current, event);
305316
return;
306317
}
318+
heard();
307319
setLive((runs) => reduce(runs, event));
308320
if (event.type === "RUN_STARTED") void refreshConversation();
309321
if (event.type === "RUN_FINISHED" || event.type === "RUN_ERROR")
310322
ended();
311323
},
312-
onCaughtUp() {
313-
setLive(caughtUp(replay ?? liveNow.current));
324+
onCaughtUp(runId) {
325+
setLive(caughtUp(replay ?? liveNow.current, runId));
314326
replay = null;
315327
// Whatever ended while the socket was away is in the messages now.
316328
void refreshHistory();
317329
},
330+
onIdle() {
331+
// Nothing is running here: a run still drawn as live ended without its end reaching the phone.
332+
if (!liveNow.current.some((run) => !run.ended)) return;
333+
setLive(idle);
334+
ended();
335+
},
318336
});
319337
watcher.current = watch;
320338
return () => {
321339
watcher.current = null;
322340
watch.stop();
341+
if (quietTimer) clearTimeout(quietTimer);
323342
for (const timer of settling) clearTimeout(timer);
324343
};
325344
}, [channelId, person]);
@@ -433,15 +452,28 @@ export function Conversation({
433452
// A run that ended and isn't in the messages in full yet is still being waited for.
434453
const unsettled = live.some((run) => run.ended && !run.error);
435454
const expecting = owed || working || replyUnderway || unsettled;
455+
// A live run the socket went quiet on is followed this way too, so a reply never sits half written.
456+
const carried = streaming && !quiet;
457+
// A run still drawn as live after the socket went quiet, while the messages say nothing is under way, is over:
458+
// its end never reached the phone.
459+
const readBusy = (history.data?.messages ?? []).some(
460+
(message) => message.status === "queued" || message.status === "running",
461+
);
462+
const haveRead = Boolean(history.data);
463+
useEffect(() => {
464+
if (!quiet || !streaming || readBusy || !haveRead) return;
465+
const timer = setTimeout(() => setLive(idle), QUIET_MS);
466+
return () => clearTimeout(timer);
467+
}, [quiet, streaming, readBusy, haveRead]);
436468
useEffect(() => {
437-
if (!expecting || streaming) return;
469+
if (!expecting || carried) return;
438470
const timer = setInterval(() => {
439471
if (AppState.currentState !== "active") return;
440472
void reload.current.history();
441473
void reload.current.conversation();
442474
}, FOLLOW_MS);
443475
return () => clearInterval(timer);
444-
}, [expecting, streaming]);
476+
}, [expecting, carried]);
445477
// What a Bot asked the person to approve in this chat, decided right here as on the web app.
446478
const loadInbox = useCallback(() => loadApprovalInbox(), []);
447479
const inbox = useLoad(loadInbox, Boolean(session));

‎mobile/src/live-run.ts‎

Lines changed: 71 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -146,17 +146,58 @@ function withRun(
146146
return runs.map((run, at) => (at === index ? change(run) : run));
147147
}
148148

149+
/** How a run is named when its RUN_STARTED never reached the phone and its events name no run. */
150+
const UNSTARTED = "unstarted:";
151+
152+
const fresh = (id: string): LiveRun => ({
153+
id,
154+
ended: false,
155+
messages: [],
156+
tools: [],
157+
});
158+
159+
/**
160+
* The runs, with one to take this event where none would. The phone joins the thread a moment after it sends, when
161+
* the Bot's run is often under way already, and the gateway does not always replay that run's start: its words and
162+
* steps then arrive for a run the phone never saw begin. They were dropped, so nothing was drawn live and the reply
163+
* only appeared each time the messages were read again. Such a run is taken up from its first event instead: under
164+
* the id the event names, else as the newest run when that one is over.
165+
*/
166+
function adopted(runs: LiveRuns, event: LiveEvent): LiveRuns {
167+
const named = runOf(event);
168+
if (named)
169+
return runs.some((run) => run.id === named)
170+
? runs
171+
: [...runs, fresh(named)];
172+
const tool = toolOf(event);
173+
const messages = [messageOf(event), text(event.parentMessageId)];
174+
const holds = runs.some(
175+
(run) =>
176+
(tool !== undefined && run.tools.some((item) => item.id === tool)) ||
177+
messages.some(
178+
(id) => id !== undefined && run.messages.some((item) => item.id === id),
179+
),
180+
);
181+
if (holds || (runs.length > 0 && !runs[runs.length - 1]?.ended)) return runs;
182+
return [...runs, fresh(`${UNSTARTED}${messages[0] ?? tool ?? runs.length}`)];
183+
}
184+
149185
/** The runs after one more event. Events of a type it doesn't know change nothing. */
150186
export function reduce(runs: LiveRuns, event: LiveEvent): LiveRuns {
151187
switch (event.type) {
152188
case "RUN_STARTED": {
153189
const id = runOf(event);
154190
if (!id || runs.some((run) => run.id === id)) return runs;
155-
return [...runs, { id, ended: false, messages: [], tools: [] }];
191+
return [...runs, fresh(id)];
156192
}
157193
case "RUN_FINISHED":
158194
case "RUN_ERROR": {
159-
const at = find(runs, event);
195+
let at = find(runs, event);
196+
// A run taken up without its start was named for its first message: its end names the real id.
197+
if (at < 0)
198+
at = runs.findLastIndex(
199+
(run) => !run.ended && run.id.startsWith(UNSTARTED),
200+
);
160201
const error =
161202
event.type === "RUN_ERROR"
162203
? (text(event.message)?.trim() ??
@@ -177,10 +218,12 @@ export function reduce(runs: LiveRuns, event: LiveEvent): LiveRuns {
177218
if (typeof event.role === "string" && event.role !== "assistant")
178219
return runs;
179220
const id = messageOf(event);
180-
const at = find(runs, event);
181-
if (!id || at < 0) return runs;
221+
if (!id) return runs;
222+
const taken = adopted(runs, event);
223+
const at = find(taken, event);
224+
if (at < 0) return runs;
182225
const delta = typeof event.delta === "string" ? event.delta : "";
183-
return withRun(runs, at, (run) => {
226+
return withRun(taken, at, (run) => {
184227
const held = run.messages.some((item) => item.id === id);
185228
if (!held)
186229
return { ...run, messages: [...run.messages, { id, text: delta }] };
@@ -194,10 +237,15 @@ export function reduce(runs: LiveRuns, event: LiveEvent): LiveRuns {
194237
});
195238
}
196239
case "TOOL_CALL_START":
197-
return started(runs, event);
240+
return toolOf(event) && text(event.toolCallName)
241+
? started(adopted(runs, event), event)
242+
: runs;
198243
case "TOOL_CALL_CHUNK": {
199244
// A chunk stands for START, ARGS and END in one: the first one of a call names it.
200-
const begun = started(runs, event);
245+
const begun =
246+
toolOf(event) && text(event.toolCallName)
247+
? started(adopted(runs, event), event)
248+
: runs;
201249
const delta = typeof event.delta === "string" ? event.delta : "";
202250
return delta
203251
? withTool(begun, event, (tool) => ({
@@ -308,9 +356,22 @@ export function stopOffer(
308356
return { runs: left, stopping: left.length === 0 };
309357
}
310358

311-
/** What the thread replayed when the socket joined, down to the runs still in progress: an ended one is in the messages. */
312-
export function caughtUp(runs: LiveRuns): LiveRuns {
313-
return runs.filter((run) => !run.ended);
359+
/**
360+
* What the thread replayed when the socket joined, down to the runs still in progress: an ended one is in the messages.
361+
* `runId` is the run the join token said was under way: it is drawn even when the replay left out its start, so what
362+
* it says next has a run to go to.
363+
*/
364+
export function caughtUp(runs: LiveRuns, runId?: string | null): LiveRuns {
365+
const going = runs.filter((run) => !run.ended);
366+
if (!runId || runs.some((run) => run.id === runId)) return going;
367+
return [...going, fresh(runId)];
368+
}
369+
370+
/** The gateway said no run is in progress in the thread (`stream_idle`): every run drawn as live is over. */
371+
export function idle(runs: LiveRuns): LiveRuns {
372+
return runs.some((run) => !run.ended)
373+
? runs.map((run) => (run.ended ? run : { ...run, ended: true }))
374+
: runs;
314375
}
315376

316377
/**

‎mobile/src/live-thread.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ export type LiveHandlers = {
2828
onEvent(event: LiveEvent, replayed: boolean): void;
2929
/** The replay is over: what follows is live. `runId` is the run in progress when the token was made, if any. */
3030
onCaughtUp(runId: string | null): void;
31+
/** The gateway says no run is in progress in the thread (`stream_idle`), as after a run ends. */
32+
onIdle?(): void;
3133
};
3234

3335
/** The socket answered nothing for this long: it is dead, and opened again. The gateway's own timeout. */
@@ -234,6 +236,10 @@ export function watchConversation(
234236
handlers.onCaughtUp(token.runId);
235237
return;
236238
}
239+
if (event === "stream_idle") {
240+
handlers.onIdle?.();
241+
return;
242+
}
237243
// Its time is up, its replay failed, or its topic failed or closed: open it again with a new token.
238244
if (
239245
event === "expired" ||

‎mobile/tests/live-run.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
arriving,
1010
asMessages,
1111
caughtUp,
12+
idle,
1213
type LiveRuns,
1314
liveAnswers,
1415
liveStep,
@@ -69,6 +70,74 @@ test("a reply's words add up as they come, even from events that name no run", (
6970
]);
7071
});
7172

73+
test("a reply is drawn as it comes even when the run's start never reached the phone", () => {
74+
// The phone joins a moment after it sends, and the gateway may not replay the start of the run under way.
75+
const runs = play([
76+
{ type: "TEXT_MESSAGE_START", messageId: "m1", role: "assistant" },
77+
words("m1", "Here are "),
78+
words("m1", "today's headlines"),
79+
]);
80+
expect(asMessages(runs, [])).toEqual([
81+
expect.objectContaining({
82+
id: "m1",
83+
text: "Here are today's headlines",
84+
status: "running",
85+
}),
86+
]);
87+
const over = play([finished("r9")], runs);
88+
expect(over.map((run) => run.ended)).toEqual([true]);
89+
});
90+
91+
test("a run an event names is taken up even if its start never came", () => {
92+
const runs = play([start("r2", "m2"), words("m2", "Hi")]);
93+
expect(runs.map((run) => run.id)).toEqual(["r2"]);
94+
expect(play([finished("r2")], runs)[0]?.ended).toBe(true);
95+
});
96+
97+
test("a step from a run whose start never came is drawn as it goes", () => {
98+
const runs = play([
99+
{
100+
type: "TOOL_CALL_START",
101+
toolCallId: "t1",
102+
toolCallName: "web_search",
103+
parentMessageId: "m1",
104+
},
105+
]);
106+
const [step] = asMessages(runs, []);
107+
expect(step).toMatchObject({ role: "tool", status: "running" });
108+
});
109+
110+
test("words after a run ended start a new one instead of joining the old", () => {
111+
const before = play([
112+
started("r1"),
113+
start("r1", "m1"),
114+
words("m1", "Done."),
115+
finished("r1"),
116+
]);
117+
const after = play([words("m2", "Next reply")], before);
118+
expect(after).toHaveLength(2);
119+
expect(after[0]?.messages.map((item) => item.text)).toEqual(["Done."]);
120+
expect(after[1]).toMatchObject({ ended: false });
121+
});
122+
123+
test("the run the join token named is drawn once the replay is over, and takes what it says next", () => {
124+
const joined = caughtUp([], "r5");
125+
expect(joined.map((run) => run.id)).toEqual(["r5"]);
126+
const saying = play([words("m5", "Working on it")], joined);
127+
expect(saying).toHaveLength(1);
128+
expect(saying[0]?.messages.map((item) => item.text)).toEqual([
129+
"Working on it",
130+
]);
131+
expect(caughtUp(saying, "r5")).toHaveLength(1);
132+
});
133+
134+
test("when the gateway says nothing is running, every run drawn as live is over", () => {
135+
const runs = play([started("r1"), start("r1", "m1"), words("m1", "Half")]);
136+
expect(idle(runs).map((run) => run.ended)).toEqual([true]);
137+
const ended = idle(runs);
138+
expect(idle(ended)).toBe(ended);
139+
});
140+
72141
test("reasoning and events of a type it doesn't know change nothing", () => {
73142
const runs = play([started("r1")]);
74143
expect(

0 commit comments

Comments
 (0)