Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions mobile/app/conversation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ import {
arriving,
asMessages,
caughtUp,
idle,
type LiveRuns,
liveAnswers,
liveStep,
Expand Down Expand Up @@ -157,6 +158,8 @@ const AWAIT_MS = 120_000;
const SETTLE_MS = 20_000;
/** How often a conversation with a reply owed or under way is read again while no socket carries it. */
const FOLLOW_MS = 1_500;
/** A live run the socket has said nothing about for this long is followed by reading the messages again too. */
const QUIET_MS = 8_000;

/**
* A conversation: the Bot at the top, what was said, and the message box. The person's messages
Expand Down Expand Up @@ -266,6 +269,8 @@ export function Conversation({
const liveNow = useRef(live);
liveNow.current = live;
const watcher = useRef<{ reconnect(): void } | null>(null);
// Whether the socket has gone quiet on a live run: true until it carries an event, and QUIET_MS after its last.
const [quiet, setQuiet] = useState(true);
// The runs Stop was pressed for: they are ending on the server, and the button waits for them.
const [stopAsked, setStopAsked] = useState<ReadonlySet<string>>(new Set());
// Read through a ref, so the socket isn't opened again each time the reloads change who they read for.
Expand Down Expand Up @@ -297,28 +302,42 @@ export function Conversation({
}, SETTLE_MS);
settling.add(timer);
};
let quietTimer: ReturnType<typeof setTimeout> | undefined;
const heard = () => {
setQuiet(false);
if (quietTimer) clearTimeout(quietTimer);
quietTimer = setTimeout(() => setQuiet(true), QUIET_MS);
};
const watch = watchConversationLive(channelId, {
onEvent(event, replayed) {
if (replayed) {
replay = reduce(replay ?? liveNow.current, event);
return;
}
heard();
setLive((runs) => reduce(runs, event));
if (event.type === "RUN_STARTED") void refreshConversation();
if (event.type === "RUN_FINISHED" || event.type === "RUN_ERROR")
ended();
},
onCaughtUp() {
setLive(caughtUp(replay ?? liveNow.current));
onCaughtUp(runId) {
setLive(caughtUp(replay ?? liveNow.current, runId));
replay = null;
// Whatever ended while the socket was away is in the messages now.
void refreshHistory();
},
onIdle() {
// Nothing is running here: a run still drawn as live ended without its end reaching the phone.
if (!liveNow.current.some((run) => !run.ended)) return;
setLive(idle);
ended();
},
});
watcher.current = watch;
return () => {
watcher.current = null;
watch.stop();
if (quietTimer) clearTimeout(quietTimer);
for (const timer of settling) clearTimeout(timer);
};
}, [channelId, person]);
Expand Down Expand Up @@ -432,15 +451,28 @@ export function Conversation({
// A run that ended and isn't in the messages in full yet is still being waited for.
const unsettled = live.some((run) => run.ended && !run.error);
const expecting = owed || working || replyUnderway || unsettled;
// A live run the socket went quiet on is followed this way too, so a reply never sits half written.
const carried = streaming && !quiet;
// A run still drawn as live after the socket went quiet, while the messages say nothing is under way, is over:
// its end never reached the phone.
const readBusy = (history.data?.messages ?? []).some(
(message) => message.status === "queued" || message.status === "running",
);
const haveRead = Boolean(history.data);
useEffect(() => {
if (!quiet || !streaming || readBusy || !haveRead) return;
const timer = setTimeout(() => setLive(idle), QUIET_MS);
return () => clearTimeout(timer);
}, [quiet, streaming, readBusy, haveRead]);
useEffect(() => {
if (!expecting || streaming) return;
if (!expecting || carried) return;
const timer = setInterval(() => {
if (AppState.currentState !== "active") return;
void reload.current.history();
void reload.current.conversation();
}, FOLLOW_MS);
return () => clearInterval(timer);
}, [expecting, streaming]);
}, [expecting, carried]);
// What a Bot asked the person to approve in this chat, decided right here as on the web app.
const loadInbox = useCallback(() => loadApprovalInbox(), []);
const inbox = useLoad(loadInbox, Boolean(session));
Expand Down
81 changes: 71 additions & 10 deletions mobile/src/live-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,17 +146,58 @@ function withRun(
return runs.map((run, at) => (at === index ? change(run) : run));
}

/** How a run is named when its RUN_STARTED never reached the phone and its events name no run. */
const UNSTARTED = "unstarted:";

const fresh = (id: string): LiveRun => ({
id,
ended: false,
messages: [],
tools: [],
});

/**
* The runs, with one to take this event where none would. The phone joins the thread a moment after it sends, when
* the Bot's run is often under way already, and the gateway does not always replay that run's start: its words and
* steps then arrive for a run the phone never saw begin. They were dropped, so nothing was drawn live and the reply
* only appeared each time the messages were read again. Such a run is taken up from its first event instead: under
* the id the event names, else as the newest run when that one is over.
*/
function adopted(runs: LiveRuns, event: LiveEvent): LiveRuns {
const named = runOf(event);
if (named)
return runs.some((run) => run.id === named)
? runs
: [...runs, fresh(named)];
const tool = toolOf(event);
const messages = [messageOf(event), text(event.parentMessageId)];
const holds = runs.some(
(run) =>
(tool !== undefined && run.tools.some((item) => item.id === tool)) ||
messages.some(
(id) => id !== undefined && run.messages.some((item) => item.id === id),
),
);
if (holds || (runs.length > 0 && !runs[runs.length - 1]?.ended)) return runs;
return [...runs, fresh(`${UNSTARTED}${messages[0] ?? tool ?? runs.length}`)];
}

/** The runs after one more event. Events of a type it doesn't know change nothing. */
export function reduce(runs: LiveRuns, event: LiveEvent): LiveRuns {
switch (event.type) {
case "RUN_STARTED": {
const id = runOf(event);
if (!id || runs.some((run) => run.id === id)) return runs;
return [...runs, { id, ended: false, messages: [], tools: [] }];
return [...runs, fresh(id)];
}
case "RUN_FINISHED":
case "RUN_ERROR": {
const at = find(runs, event);
let at = find(runs, event);
// A run taken up without its start was named for its first message: its end names the real id.
if (at < 0)
at = runs.findLastIndex(
(run) => !run.ended && run.id.startsWith(UNSTARTED),
);
const error =
event.type === "RUN_ERROR"
? (text(event.message)?.trim() ??
Expand All @@ -177,10 +218,12 @@ export function reduce(runs: LiveRuns, event: LiveEvent): LiveRuns {
if (typeof event.role === "string" && event.role !== "assistant")
return runs;
const id = messageOf(event);
const at = find(runs, event);
if (!id || at < 0) return runs;
if (!id) return runs;
const taken = adopted(runs, event);
const at = find(taken, event);
if (at < 0) return runs;
const delta = typeof event.delta === "string" ? event.delta : "";
return withRun(runs, at, (run) => {
return withRun(taken, at, (run) => {
const held = run.messages.some((item) => item.id === id);
if (!held)
return { ...run, messages: [...run.messages, { id, text: delta }] };
Expand All @@ -194,10 +237,15 @@ export function reduce(runs: LiveRuns, event: LiveEvent): LiveRuns {
});
}
case "TOOL_CALL_START":
return started(runs, event);
return toolOf(event) && text(event.toolCallName)
? started(adopted(runs, event), event)
: runs;
case "TOOL_CALL_CHUNK": {
// A chunk stands for START, ARGS and END in one: the first one of a call names it.
const begun = started(runs, event);
const begun =
toolOf(event) && text(event.toolCallName)
? started(adopted(runs, event), event)
: runs;
const delta = typeof event.delta === "string" ? event.delta : "";
return delta
? withTool(begun, event, (tool) => ({
Expand Down Expand Up @@ -308,9 +356,22 @@ export function stopOffer(
return { runs: left, stopping: left.length === 0 };
}

/** What the thread replayed when the socket joined, down to the runs still in progress: an ended one is in the messages. */
export function caughtUp(runs: LiveRuns): LiveRuns {
return runs.filter((run) => !run.ended);
/**
* What the thread replayed when the socket joined, down to the runs still in progress: an ended one is in the messages.
* `runId` is the run the join token said was under way: it is drawn even when the replay left out its start, so what
* it says next has a run to go to.
*/
export function caughtUp(runs: LiveRuns, runId?: string | null): LiveRuns {
const going = runs.filter((run) => !run.ended);
if (!runId || runs.some((run) => run.id === runId)) return going;
return [...going, fresh(runId)];
}

/** The gateway said no run is in progress in the thread (`stream_idle`): every run drawn as live is over. */
export function idle(runs: LiveRuns): LiveRuns {
return runs.some((run) => !run.ended)
? runs.map((run) => (run.ended ? run : { ...run, ended: true }))
: runs;
}

/**
Expand Down
6 changes: 6 additions & 0 deletions mobile/src/live-thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export type LiveHandlers = {
onEvent(event: LiveEvent, replayed: boolean): void;
/** The replay is over: what follows is live. `runId` is the run in progress when the token was made, if any. */
onCaughtUp(runId: string | null): void;
/** The gateway says no run is in progress in the thread (`stream_idle`), as after a run ends. */
onIdle?(): void;
};

/** The socket answered nothing for this long: it is dead, and opened again. The gateway's own timeout. */
Expand Down Expand Up @@ -234,6 +236,10 @@ export function watchConversation(
handlers.onCaughtUp(token.runId);
return;
}
if (event === "stream_idle") {
handlers.onIdle?.();
return;
}
// Its time is up, its replay failed, or its topic failed or closed: open it again with a new token.
if (
event === "expired" ||
Expand Down
69 changes: 69 additions & 0 deletions mobile/tests/live-run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
arriving,
asMessages,
caughtUp,
idle,
type LiveRuns,
liveAnswers,
liveStep,
Expand Down Expand Up @@ -69,6 +70,74 @@ test("a reply's words add up as they come, even from events that name no run", (
]);
});

test("a reply is drawn as it comes even when the run's start never reached the phone", () => {
// The phone joins a moment after it sends, and the gateway may not replay the start of the run under way.
const runs = play([
{ type: "TEXT_MESSAGE_START", messageId: "m1", role: "assistant" },
words("m1", "Here are "),
words("m1", "today's headlines"),
]);
expect(asMessages(runs, [])).toEqual([
expect.objectContaining({
id: "m1",
text: "Here are today's headlines",
status: "running",
}),
]);
const over = play([finished("r9")], runs);
expect(over.map((run) => run.ended)).toEqual([true]);
});

test("a run an event names is taken up even if its start never came", () => {
const runs = play([start("r2", "m2"), words("m2", "Hi")]);
expect(runs.map((run) => run.id)).toEqual(["r2"]);
expect(play([finished("r2")], runs)[0]?.ended).toBe(true);
});

test("a step from a run whose start never came is drawn as it goes", () => {
const runs = play([
{
type: "TOOL_CALL_START",
toolCallId: "t1",
toolCallName: "web_search",
parentMessageId: "m1",
},
]);
const [step] = asMessages(runs, []);
expect(step).toMatchObject({ role: "tool", status: "running" });
});

test("words after a run ended start a new one instead of joining the old", () => {
const before = play([
started("r1"),
start("r1", "m1"),
words("m1", "Done."),
finished("r1"),
]);
const after = play([words("m2", "Next reply")], before);
expect(after).toHaveLength(2);
expect(after[0]?.messages.map((item) => item.text)).toEqual(["Done."]);
expect(after[1]).toMatchObject({ ended: false });
});

test("the run the join token named is drawn once the replay is over, and takes what it says next", () => {
const joined = caughtUp([], "r5");
expect(joined.map((run) => run.id)).toEqual(["r5"]);
const saying = play([words("m5", "Working on it")], joined);
expect(saying).toHaveLength(1);
expect(saying[0]?.messages.map((item) => item.text)).toEqual([
"Working on it",
]);
expect(caughtUp(saying, "r5")).toHaveLength(1);
});

test("when the gateway says nothing is running, every run drawn as live is over", () => {
const runs = play([started("r1"), start("r1", "m1"), words("m1", "Half")]);
expect(idle(runs).map((run) => run.ended)).toEqual([true]);
const ended = idle(runs);
expect(idle(ended)).toBe(ended);
});

test("reasoning and events of a type it doesn't know change nothing", () => {
const runs = play([started("r1")]);
expect(
Expand Down
Loading