diff --git a/api/openapi.yaml b/api/openapi.yaml index 75a7eb3595..0e2470c3a0 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -3338,7 +3338,7 @@ paths: - Conversations operationId: createConversationJoinToken summary: Get a token to watch a conversation live - description: 'Make a join token for the conversation''s thread, and say where to use it. The token opens the threadStream channel of api/asyncapi.yaml: a WebSocket that replays the Bot''s runs in the conversation, a run in progress from its start, and then carries on live. The token works once and for about half a minute, so ask for a new one for every connection, and again to reconnect. Only a person in the conversation may have one, and it opens the thread they see there and no other. A conversation no Bot has run in yet has nothing to join (409). Where realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app''s access token, or an API key, as Authorization: Bearer or x-api-key. So a script that holds only an API key can watch a conversation live.' + description: 'Make a join token for the conversation''s thread, and say where to use it. The token opens the threadStream channel of api/asyncapi.yaml: a WebSocket that replays the Bot''s runs in the conversation, a run in progress from its start, and then carries on live. The token works once and for about half a minute, so ask for a new one for every connection, and again to reconnect. Only a person in the conversation may have one, and it opens the thread they see there and no other. A conversation no Bot has run in yet has nothing to join (409). Where realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app''s access token, or an API key, as Authorization: Bearer or x-api-key. So a script that holds only an API key can watch a conversation live. The answer also names the thread''s last run and how it ended (lastRun), as a thread''s status says whether its last run failed.' security: - webSession: [] - appOAuth: @@ -33580,6 +33580,11 @@ components: - string - 'null' description: The run in progress in the thread, or null when the Bot is not working. + lastRun: + oneOf: + - $ref: '#/components/schemas/ConversationRun' + - type: 'null' + description: 'The Bot''s most recent run in the thread, and how it ended, as getConversationRun says it: the run in progress, while one is (its outcome null), and otherwise the last one. Null when this server keeps no record of a run in the thread. Absent from a server before it said this. A client that opens the conversation without replaying its runs to the end reads here whether the last one failed, so it can say so and offer to carry on, as it would had it heard the run''s RUN_ERROR.' realtime: type: object description: Where to use the token. @@ -34236,6 +34241,34 @@ components: description: True uses OpenBot's list, false hands each computer back its own. apps: $ref: '#/components/schemas/WindowsAllowlistApps' + ConversationRun: + type: object + description: One of a Bot's runs in a conversation, and how it ended. + required: + - id + - outcome + - endedAt + properties: + id: + type: string + minLength: 1 + description: The run's id, as its events carry it. + outcome: + type: + - string + - 'null' + x-extensible-enum: + - succeeded + - interrupted + - cancelled + - failed + description: 'How the run ended, as its own last event said. succeeded: it finished. interrupted: it stopped to ask a person (an approval, a missing value). cancelled: it was stopped. failed: it ended with an error, or its stream failed, or its server ended it on the way down. Null while the run is going, and for a run that ended without saying how.' + endedAt: + type: + - string + - 'null' + format: date-time + description: When the run ended, or null while outcome is null. ConversationWork: type: object description: 'Something still owed an answer in a conversation: another Bot that was asked and has not answered (handoff), a routine running into it (routine), or the person''s own turn, which the server is carrying on with no page open (turn).' @@ -49493,34 +49526,6 @@ components: description: The apps that came across connected. items: $ref: '#/components/schemas/CarriedApp' - ConversationRun: - type: object - description: One of a Bot's runs in a conversation, and how it ended. - required: - - id - - outcome - - endedAt - properties: - id: - type: string - minLength: 1 - description: The run's id, as its events carry it. - outcome: - type: - - string - - 'null' - x-extensible-enum: - - succeeded - - interrupted - - cancelled - - failed - description: 'How the run ended, as its own last event said. succeeded: it finished. interrupted: it stopped to ask a person (an approval, a missing value). cancelled: it was stopped. failed: it ended with an error, or its stream failed, or its server ended it on the way down. Null while the run is going, and for a run that ended without saying how.' - endedAt: - type: - - string - - 'null' - format: date-time - description: When the run ended, or null while outcome is null. ConversationRunResponse: type: object required: @@ -61028,6 +61033,10 @@ components: expiresAt: '2026-11-14T12:00:30.000Z' threadId: 6f3d6b1f-6f10-8a53-9d51-5f0d6c0e2f1a runId: 0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21 + lastRun: + id: 0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21 + outcome: null + endedAt: null realtime: clientUrl: wss://realtime.example.com/client topic: thread:6f3d6b1f-6f10-8a53-9d51-5f0d6c0e2f1a diff --git a/api/openapi/conversations.yaml b/api/openapi/conversations.yaml index 62e6869b02..f31c723e12 100644 --- a/api/openapi/conversations.yaml +++ b/api/openapi/conversations.yaml @@ -82,7 +82,9 @@ paths: realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app's access token, or an API key, as Authorization: Bearer or x-api-key. So a script - that holds only an API key can watch a conversation live. + that holds only an API key can watch a conversation live. The answer + also names the thread's last run and how it ended (lastRun), as a + thread's status says whether its last run failed. security: - webSession: [] - appOAuth: [conversations:read] @@ -2381,6 +2383,19 @@ components: - string - 'null' description: The run in progress in the thread, or null when the Bot is not working. + lastRun: + oneOf: + - $ref: '#/components/schemas/ConversationRun' + - type: 'null' + description: >- + The Bot's most recent run in the thread, and how it ended, as + getConversationRun says it: the run in progress, while one is (its + outcome null), and otherwise the last one. Null when this server + keeps no record of a run in the thread. Absent from a server + before it said this. A client that opens the conversation without + replaying its runs to the end reads here whether the last one + failed, so it can say so and offer to carry on, as it would had it + heard the run's RUN_ERROR. realtime: type: object description: Where to use the token. @@ -4125,6 +4140,10 @@ components: expiresAt: '2026-11-14T12:00:30.000Z' threadId: 6f3d6b1f-6f10-8a53-9d51-5f0d6c0e2f1a runId: 0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21 + lastRun: + id: 0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21 + outcome: null + endedAt: null realtime: clientUrl: wss://realtime.example.com/client topic: thread:6f3d6b1f-6f10-8a53-9d51-5f0d6c0e2f1a diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index d6ebae3fa8..085e4e8314 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -135,6 +135,7 @@ import { askRunLiveness, askTimes, finishedRunId, + lastRunFailure, type QuietEnding, quietRunPeriod, RUN_ENDED_UNHEARD, @@ -1419,33 +1420,46 @@ export function ChannelChat({ * heard that RUN_ERROR, but the join that resumed the thread took longer than its deadline, * and a failure is said above only from a join that finished. * - * So when the join did not finish and heard no run of its own, the last run the kept agent - * heard is asked about: said again if the server has no run going and says that run did not - * finish. Asked after the history is in, so the conversation is never held for it. + * AND A RELOAD ON A SLOW LINK. With no agent kept (a reload, a page opened again) the join is + * the only record of how the last run ended, and one cut at its deadline may not have reached + * it: the conversation opened on its history with nothing said, as above. + * + * So when the join did not finish, the server is asked how the thread's last run ended + * (`lastRun` on the join token, as a thread's status says whether its last run failed). A last + * run that failed is said again: in its own words where this page heard them (the replay, or + * the kept agent), otherwise as a turn that stopped part way, with Carry on. A server from + * before `lastRun` is asked about the run the kept agent heard fail. Asked after the history + * is in, so the conversation is never held for it. */ - const keptStory = heardRuns(agent); - const keptFailure = keptStory?.failure() ?? null; - const keptFailedRun = keptStory?.runId() ?? null; - if ( - joined !== "connected" && - lastRun.runId() === null && - keptFailure !== null && - keptFailedRun !== null && - current && - turnsRef.current === 0 - ) { - const going = await askRunGoing(channel.id); - const ended = - going.liveness === "over" - ? await askRunEnding(channel.id, keptFailedRun) - : null; - if (ended === "stopped" && current && turnsRef.current === 0) { - const code = keptStory?.failureCode(); - setRunError( - (shown) => - shown ?? { message: keptFailure, ...(code ? { code } : {}) }, - ); - } + if (joined !== "connected" && current && turnsRef.current === 0) { + // What this page heard of the last run: the join's own, or else the kept agent's. + const replayHeard = lastRun.runId() !== null; + const heard = replayHeard ? lastRun : (heardRuns(agent) ?? lastRun); + const said = await lastRunFailure({ + conversationId: channel.id, + heardByKeptAgent: !replayHeard, + heardRun: heard.runId(), + heardFailure: heard.failure(), + heardCode: heard.failureCode(), + // Kept from a turn the server refused: drawn under its message (`refusedRun`). + refusedAt: async () => { + try { + const turns = await queryClient.fetchQuery( + refusedTurnsQueryOptions(channel.id), + ); + return turns.map((turn) => turn.createdAt); + } catch { + return []; + } + }, + }); + if ( + said !== null && + current && + turnsRef.current === 0 && + !carriedByServerRef.current + ) + setRunError((shown) => shown ?? said); } /* * A TURN THE SERVER IS STILL CARRYING ON IS FOLLOWED FROM HERE. The join above streams the run diff --git a/app/src/lib/api/generated/conversations/conversations.msw.ts b/app/src/lib/api/generated/conversations/conversations.msw.ts index df08d0e36c..3883da8c4c 100644 --- a/app/src/lib/api/generated/conversations/conversations.msw.ts +++ b/app/src/lib/api/generated/conversations/conversations.msw.ts @@ -37,6 +37,11 @@ export const getCreateConversationJoinTokenResponseMock = expiresAt: "2026-11-14T12:00:30.000Z", threadId: "6f3d6b1f-6f10-8a53-9d51-5f0d6c0e2f1a", runId: "0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21", + lastRun: { + id: "0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21", + outcome: null, + endedAt: null, + }, realtime: { clientUrl: "wss://realtime.example.com/client", topic: "thread:6f3d6b1f-6f10-8a53-9d51-5f0d6c0e2f1a", diff --git a/app/src/lib/api/generated/conversations/conversations.ts b/app/src/lib/api/generated/conversations/conversations.ts index 1041789bba..0668dc67c3 100644 --- a/app/src/lib/api/generated/conversations/conversations.ts +++ b/app/src/lib/api/generated/conversations/conversations.ts @@ -121,7 +121,7 @@ export const getCreateConversationJoinTokenUrl = ( }; /** - * Make a join token for the conversation's thread, and say where to use it. The token opens the threadStream channel of api/asyncapi.yaml: a WebSocket that replays the Bot's runs in the conversation, a run in progress from its start, and then carries on live. The token works once and for about half a minute, so ask for a new one for every connection, and again to reconnect. Only a person in the conversation may have one, and it opens the thread they see there and no other. A conversation no Bot has run in yet has nothing to join (409). Where realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app's access token, or an API key, as Authorization: Bearer or x-api-key. So a script that holds only an API key can watch a conversation live. + * Make a join token for the conversation's thread, and say where to use it. The token opens the threadStream channel of api/asyncapi.yaml: a WebSocket that replays the Bot's runs in the conversation, a run in progress from its start, and then carries on live. The token works once and for about half a minute, so ask for a new one for every connection, and again to reconnect. Only a person in the conversation may have one, and it opens the thread they see there and no other. A conversation no Bot has run in yet has nothing to join (409). Where realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app's access token, or an API key, as Authorization: Bearer or x-api-key. So a script that holds only an API key can watch a conversation live. The answer also names the thread's last run and how it ended (lastRun), as a thread's status says whether its last run failed. * @summary Get a token to watch a conversation live */ export const createConversationJoinToken = async ( diff --git a/app/src/lib/api/generated/conversations/conversations.zod.ts b/app/src/lib/api/generated/conversations/conversations.zod.ts index 9978d0d1cf..7888efb0d2 100644 --- a/app/src/lib/api/generated/conversations/conversations.zod.ts +++ b/app/src/lib/api/generated/conversations/conversations.zod.ts @@ -4,7 +4,7 @@ import * as zod from "zod"; /** - * Make a join token for the conversation's thread, and say where to use it. The token opens the threadStream channel of api/asyncapi.yaml: a WebSocket that replays the Bot's runs in the conversation, a run in progress from its start, and then carries on live. The token works once and for about half a minute, so ask for a new one for every connection, and again to reconnect. Only a person in the conversation may have one, and it opens the thread they see there and no other. A conversation no Bot has run in yet has nothing to join (409). Where realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app's access token, or an API key, as Authorization: Bearer or x-api-key. So a script that holds only an API key can watch a conversation live. + * Make a join token for the conversation's thread, and say where to use it. The token opens the threadStream channel of api/asyncapi.yaml: a WebSocket that replays the Bot's runs in the conversation, a run in progress from its start, and then carries on live. The token works once and for about half a minute, so ask for a new one for every connection, and again to reconnect. Only a person in the conversation may have one, and it opens the thread they see there and no other. A conversation no Bot has run in yet has nothing to join (409). Where realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app's access token, or an API key, as Authorization: Bearer or x-api-key. So a script that holds only an API key can watch a conversation live. The answer also names the thread's last run and how it ended (lastRun), as a thread's status says whether its last run failed. * @summary Get a token to watch a conversation live */ @@ -64,6 +64,32 @@ export const CreateConversationJoinTokenResponse = zod .describe( "The run in progress in the thread, or null when the Bot is not working.", ), + lastRun: zod + .union([ + zod + .object({ + id: zod + .string() + .min(1) + .describe("The run's id, as its events carry it."), + outcome: zod + .string() + .nullable() + .describe( + "How the run ended, as its own last event said. succeeded: it finished. interrupted: it stopped to ask a person (an approval, a missing value). cancelled: it was stopped. failed: it ended with an error, or its stream failed, or its server ended it on the way down. Null while the run is going, and for a run that ended without saying how.", + ), + endedAt: zod.iso + .datetime({ offset: true }) + .nullable() + .describe("When the run ended, or null while outcome is null."), + }) + .describe("One of a Bot's runs in a conversation, and how it ended."), + zod.null(), + ]) + .optional() + .describe( + "The Bot's most recent run in the thread, and how it ended, as getConversationRun says it: the run in progress, while one is (its outcome null), and otherwise the last one. Null when this server keeps no record of a run in the thread. Absent from a server before it said this. A client that opens the conversation without replaying its runs to the end reads here whether the last one failed, so it can say so and offer to carry on, as it would had it heard the run's RUN_ERROR.", + ), realtime: zod .object({ clientUrl: zod diff --git a/app/src/lib/api/generated/model/conversationJoinToken.ts b/app/src/lib/api/generated/model/conversationJoinToken.ts index 9b69ded0bc..9072bd4768 100644 --- a/app/src/lib/api/generated/model/conversationJoinToken.ts +++ b/app/src/lib/api/generated/model/conversationJoinToken.ts @@ -2,6 +2,7 @@ * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. */ import type { ConversationJoinTokenRealtime } from "./conversationJoinTokenRealtime"; +import type { ConversationRun } from "./conversationRun"; /** * What a client needs to watch a conversation live: a token, and the socket and topic to use it on (the threadStream channel of api/asyncapi.yaml). @@ -24,6 +25,8 @@ export interface ConversationJoinToken { * @nullable */ runId: string | null; + /** The Bot's most recent run in the thread, and how it ended, as getConversationRun says it: the run in progress, while one is (its outcome null), and otherwise the last one. Null when this server keeps no record of a run in the thread. Absent from a server before it said this. A client that opens the conversation without replaying its runs to the end reads here whether the last one failed, so it can say so and offer to carry on, as it would had it heard the run's RUN_ERROR. */ + lastRun?: ConversationRun | null; /** Where to use the token. */ realtime: ConversationJoinTokenRealtime; } diff --git a/app/src/lib/copilot/quiet-run.ts b/app/src/lib/copilot/quiet-run.ts index e20f829f3f..b83f87d4ed 100644 --- a/app/src/lib/copilot/quiet-run.ts +++ b/app/src/lib/copilot/quiet-run.ts @@ -92,8 +92,29 @@ export const RUN_ENDED_UNHEARD = export const RUN_UNREACHABLE = "OpenBot lost touch with the Bot before it finished. Carry on once OpenBot is back."; -/** What a join token says about the conversation it is for: the run in progress, or none. */ -type Joined = { runId: string | null }; +/** + * What a join token says about the conversation it is for: the run in progress, or none, and the + * thread's last run and how it ended, from a server that says it (`lastRun`). + */ +type Joined = { + runId: string | null; + lastRun?: { + id: string; + outcome: string | null; + endedAt: string | null; + } | null; +}; + +/** + * The thread's last run as the server keeps it: its id, how it ended (null while it is going, or + * when it ended without saying how) and when. Null when the server keeps no run of the thread. + * Undefined when the server did not say, as one from before `lastRun` does not, or when it was not + * reached. + */ +export type LastRun = + | { id: string; outcome: string | null; endedAt: string | null } + | null + | undefined; /** * Ask whether this conversation has a run going, by asking for a join token for it (the API's @@ -123,7 +144,7 @@ export async function askRunGoing( join?: (conversationId: string, signal: AbortSignal) => Promise; answerMs?: number; } = {}, -): Promise<{ liveness: RunLiveness; runId: string | null }> { +): Promise<{ liveness: RunLiveness; runId: string | null; lastRun?: LastRun }> { const join = options.join ?? ((id: string, signal: AbortSignal) => @@ -148,9 +169,24 @@ export async function askRunGoing( }), ]); if (joined === null) return { liveness: "unreachable", runId: null }; + // Read only in the shape it is written: anything else is a server that didn't say. + const said = joined.lastRun; + const lastRun: LastRun = + said === null + ? null + : said && + typeof said.id === "string" && + said.id && + (typeof said.outcome === "string" || said.outcome === null) + ? { + id: said.id, + outcome: said.outcome, + endedAt: typeof said.endedAt === "string" ? said.endedAt : null, + } + : undefined; return typeof joined.runId === "string" - ? { liveness: "live", runId: joined.runId || null } - : { liveness: "over", runId: null }; + ? { liveness: "live", runId: joined.runId || null, lastRun } + : { liveness: "over", runId: null, lastRun }; } catch (error) { return { liveness: @@ -342,6 +378,74 @@ export async function askRunEnding( } } +/** + * How long apart a refused turn's record and its run's end may be and still be the same turn. The + * server keeps the refused turn as its run starts, and the run ends at once. + */ +const REFUSED_WITH_RUN_MS = 120_000; + +/** + * Why the thread's last run ended without finishing, for a conversation opened without hearing its + * end: the join that would have replayed it ran past its deadline (a reload on a slow link, a phone + * coming back to a conversation). Null when the last run finished, stopped to ask somebody, was + * stopped, or is still going, or when nothing can say. + * + * Read from the server (`lastRun` on the join token: the thread's last run and how it ended, as a + * thread's status in LangGraph's threads API says whether its last run failed). A failed run is + * said in its own words where this page heard them (`heardFailure`, for `heardRun`), and otherwise as + * a turn that stopped part way, with Carry on. A turn the server refused (`refusedAt`) is drawn under + * its own message, so its run is not said again here. From a server before `lastRun`, only a failure + * the kept agent heard itself is said, once the server says that run did not finish. + */ +export async function lastRunFailure({ + conversationId, + heardByKeptAgent, + heardRun, + heardFailure, + heardCode, + refusedAt, + ask = askRunGoing, + ending = askRunEnding, +}: { + conversationId: string; + /** Whether what was heard was heard by the agent kept from before, not by this join. */ + heardByKeptAgent: boolean; + heardRun: string | null; + heardFailure: string | null; + heardCode?: string; + /** When each of the conversation's refused turns was kept. */ + refusedAt: () => Promise; + ask?: typeof askRunGoing; + ending?: (conversationId: string, runId: string) => Promise; +}): Promise<{ message: string; code?: string } | null> { + const heard = + heardFailure === null + ? null + : { message: heardFailure, ...(heardCode ? { code: heardCode } : {}) }; + const going = await ask(conversationId); + if (going.liveness !== "over") return null; + const last = going.lastRun; + if (last === undefined) { + if (!heardByKeptAgent || heard === null || heardRun === null) return null; + return (await ending(conversationId, heardRun)) === "stopped" + ? heard + : null; + } + if (last === null || last.outcome !== "failed") return null; + if (last.id === heardRun && heard !== null) return heard; + const ended = last.endedAt === null ? Number.NaN : Date.parse(last.endedAt); + if (Number.isFinite(ended)) { + const refused = (await refusedAt()).some((at) => { + const kept = Date.parse(at); + return ( + Number.isFinite(kept) && Math.abs(ended - kept) <= REFUSED_WITH_RUN_MS + ); + }); + if (refused) return null; + } + return { message: RUN_ENDED_UNHEARD }; +} + /** * Watch a run for quiet. `heard` is called for everything that arrives from it, and `rest` when * the server's run ends with the turn still going here. After `quietMs` diff --git a/app/tests/last-run-failure.test.ts b/app/tests/last-run-failure.test.ts new file mode 100644 index 0000000000..e6f8d3fade --- /dev/null +++ b/app/tests/last-run-failure.test.ts @@ -0,0 +1,116 @@ +import { expect, test } from "bun:test"; +import { + type LastRun, + lastRunFailure, + RUN_ENDED_UNHEARD, +} from "@/lib/copilot/quiet-run"; + +/** + * How the last run of a conversation opened without hearing its end is said (`lastRunFailure`), + * from what the server answers on the join token. The browser journey is + * stopped-turn-return-browser.test.tsx; these are the rules it rests on, one answer each. + */ + +const DROPPED = "The connection to OpenAI dropped. Ask the Bot to carry on."; +const ENDED = "2026-12-04T10:38:33.690Z"; + +function asked( + lastRun: LastRun, + over: Partial[0]> = {}, + liveness: "live" | "over" | "unreachable" = "over", +) { + const endings: string[] = []; + return { + endings, + said: lastRunFailure({ + conversationId: "c1", + heardByKeptAgent: false, + heardRun: null, + heardFailure: null, + refusedAt: async () => [], + ask: async () => ({ liveness, runId: null, lastRun }), + ending: async (_conversation, runId) => { + endings.push(runId); + return "stopped"; + }, + ...over, + }), + }; +} + +test("a last run that failed, heard by nobody here, is said as a turn that stopped part way", async () => { + expect( + await asked({ id: "r2", outcome: "failed", endedAt: ENDED }).said, + ).toEqual({ message: RUN_ENDED_UNHEARD }); +}); + +test("a last run that failed and was heard here is said in its own words, with its code", async () => { + expect( + await asked( + { id: "r2", outcome: "failed", endedAt: ENDED }, + { heardRun: "r2", heardFailure: DROPPED, heardCode: "BOT_KEY_REFUSED" }, + ).said, + ).toEqual({ message: DROPPED, code: "BOT_KEY_REFUSED" }); +}); + +test("a failure heard of an older run is not said when the last run is another", async () => { + // Carried on elsewhere and answered: the last run finished. + expect( + await asked( + { id: "r3", outcome: "succeeded", endedAt: ENDED }, + { heardRun: "r2", heardFailure: DROPPED, heardByKeptAgent: true }, + ).said, + ).toBeNull(); +}); + +test("a last run that finished, was stopped, stopped to ask, is going, or doesn't exist says nothing", async () => { + for (const outcome of ["succeeded", "cancelled", "interrupted", null]) + expect( + await asked({ id: "r2", outcome, endedAt: outcome ? ENDED : null }).said, + ).toBeNull(); + expect(await asked(null).said).toBeNull(); + expect( + await asked({ id: "r2", outcome: "failed", endedAt: ENDED }, {}, "live") + .said, + ).toBeNull(); + expect( + await asked( + { id: "r2", outcome: "failed", endedAt: ENDED }, + {}, + "unreachable", + ).said, + ).toBeNull(); +}); + +test("a turn the server refused is drawn under its own message, so its failed run is not said again", async () => { + // The refused turn is kept as its run starts; the run ends a moment later. + expect( + await asked( + { id: "r2", outcome: "failed", endedAt: ENDED }, + { refusedAt: async () => ["2026-12-04T10:38:33.100Z"] }, + ).said, + ).toBeNull(); + // One refused long before is another turn's. + expect( + await asked( + { id: "r2", outcome: "failed", endedAt: ENDED }, + { refusedAt: async () => ["2026-12-03T09:00:00.000Z"] }, + ).said, + ).toEqual({ message: RUN_ENDED_UNHEARD }); +}); + +test("from a server that doesn't name the last run, only a failure the kept agent heard is said, once the server says that run didn't finish", async () => { + const kept = asked(undefined, { + heardByKeptAgent: true, + heardRun: "r2", + heardFailure: DROPPED, + }); + expect(await kept.said).toEqual({ message: DROPPED }); + expect(kept.endings).toEqual(["r2"]); + // Heard by this join, which may have stopped short of a later run: not said. + expect( + await asked(undefined, { heardRun: "r2", heardFailure: DROPPED }).said, + ).toBeNull(); + // Nothing heard: nothing to say. + expect(await asked(undefined, { heardByKeptAgent: true }).said).toBeNull(); +}); diff --git a/app/tests/stopped-turn-return-browser.test.tsx b/app/tests/stopped-turn-return-browser.test.tsx index 3b1dc1f698..edc2427ba9 100644 --- a/app/tests/stopped-turn-return-browser.test.tsx +++ b/app/tests/stopped-turn-return-browser.test.tsx @@ -6,6 +6,7 @@ import type { Browser, BrowserType, Page } from "playwright-core"; import { compile } from "tailwindcss"; import { getGetBotDelegationResponseMock } from "@/lib/api/generated/agents/agents.msw"; import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import { RUN_ENDED_UNHEARD } from "@/lib/copilot/quiet-run"; import { personBody } from "./accounts-api"; import { botGrantsBody } from "./bot-grants-api"; import { still } from "./page-still"; @@ -27,7 +28,9 @@ import { test } from "./renderer-crash"; * The RUN_ERROR is not in the thread's stored messages, only in the run's events. The agent kept for * the conversation heard it, but a failure was said again only from a join that finished, and the * join that resumed the thread took longer than its deadline (1.5 s, on a phone), so the - * conversation came back with nothing said. + * conversation came back with nothing said. A reload on a slow link was the same, with no agent + * kept to have heard anything: the server now names the thread's last run and how it ended on the + * join token (`lastRun`), so a last run that failed is said there too. * * OPENBOT_APP_BROWSER=1 bun test app/tests/stopped-turn-return-browser.test.tsx * @@ -80,9 +83,14 @@ type Scene = { runs: number; recorded: unknown[]; stored: unknown[]; - ending: string; + /** The sentence the run fails with, or null for a run the person stopped. */ + ending: string | null; replayAfterMs: number; breaksAfterMs: number; + /** Whether the server names the thread's last run on a join token (`lastRun`), as one from 1.2.12 does. */ + saysLastRun: boolean; + /** The last run, as the server keeps it. */ + last: { id: string; outcome: "failed" | "cancelled" } | null; }; const fresh = (over: Partial = {}): Scene => ({ runs: 0, @@ -91,6 +99,8 @@ const fresh = (over: Partial = {}): Scene => ({ ending: DROPPED, replayAfterMs: 0, breaksAfterMs: 0, + saysLastRun: true, + last: null, ...over, }); let scene: Scene = fresh(); @@ -180,9 +190,20 @@ function run(input: { toolCallId: next, content: "Free 10:00-10:30 and 13:00-13:30.", }, - { type: "RUN_ERROR", message: scene.ending }, + scene.ending === null + ? { + type: "RUN_FINISHED", + threadId, + runId, + outcome: { type: "cancelled" }, + } + : { type: "RUN_ERROR", message: scene.ending }, ]; scene.recorded.push(...events); + scene.last = { + id: runId, + outcome: scene.ending === null ? "cancelled" : "failed", + }; const known = new Set( scene.stored.map((message) => (message as { id: string }).id), ); @@ -302,11 +323,19 @@ async function answer(request: Request): Promise { expiresAt: new Date(Date.now() + 30_000).toISOString(), threadId: "launch-thread", runId: null, + // The thread's last run and how it ended, from a server that says it. + ...(scene.saysLastRun + ? { + lastRun: scene.last + ? { ...scene.last, endedAt: new Date().toISOString() } + : null, + } + : {}), realtime: { clientUrl: "ws://127.0.0.1/client", topic: "thread" }, }, 201, ); - // How each run ended, as the server keeps it: failed. + // How each run ended, as the server keeps it. const ran = path.match( new RegExp(`^${ORGANIZATION}/conversations/${CONVERSATION}/runs/([^/]+)$`), ); @@ -314,7 +343,7 @@ async function answer(request: Request): Promise { return json({ run: { id: decodeURIComponent(ran[1] ?? ""), - outcome: "failed", + outcome: scene.last?.outcome ?? "failed", endedAt: new Date().toISOString(), }, }); @@ -554,8 +583,84 @@ describe.skipIf(!asked)("a turn that ended in an error", () => { said: DROPPED, carryOn: 1, }); + + // Opened again from nothing on a slow link, the replay past the join's deadline: the + // server says the last run failed, and the turn says it stopped part way. + scene.replayAfterMs = 2_500; + await page.goto(`${origin}${HERE}?quietMs=400&theme=${theme}`); + await settled(page); + await shoot(page, name("3-reloaded-slow")); + expect(await notice(page)).toEqual({ + count: 1, + said: RUN_ENDED_UNHEARD, + carryOn: 1, + }); } finally { await page.close(); } }, 120_000); + + /** A page for the checks below, which hold at any size: phone width, light. */ + async function phone(engine: string) { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: { width: 390, height: 844 }, + colorScheme: "light", + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + return page; + } + + for (const engine of engines) + test(`a run that was stopped says nothing after a slow reload, in ${engine}`, async () => { + scene = fresh({ ending: null }); + const page = await phone(engine); + try { + await page.goto(`${origin}${HERE}?quietMs=400&theme=light`); + await send(page, ASKED); + await settled(page); + expect((await notice(page)).count).toBe(0); + scene.replayAfterMs = 2_500; + await page.goto(`${origin}${HERE}?quietMs=400&theme=light`); + await settled(page); + await shoot(page, `stopped-turn-return-stopped-slow-${engine}`); + expect((await notice(page)).count).toBe(0); + } finally { + await page.close(); + } + }, 120_000); + + /* + * A server from before `lastRun` (an app is often newer than its server): coming back to the + * conversation in the same page still says the failure the page heard, and a slow reload, which + * nothing can tell about the last run, opens on the history as before. + */ + for (const engine of engines) + test(`against a server that doesn't name the last run, coming back still says so, in ${engine}`, async () => { + scene = fresh({ breaksAfterMs: 3_000, saysLastRun: false }); + const page = await phone(engine); + try { + await page.goto(`${origin}${HERE}?quietMs=400&theme=light`); + await send(page, ASKED); + await page.getByText(PROMISE).waitFor({ timeout: 15_000 }); + await go(page, "/channel/new"); + await page.getByText("Somewhere else in OpenBot").waitFor(); + await sleep(4_500); + scene.replayAfterMs = 2_500; + await go(page, HERE); + await settled(page); + expect(await notice(page)).toEqual({ + count: 1, + said: DROPPED, + carryOn: 1, + }); + await page.goto(`${origin}${HERE}?quietMs=400&theme=light`); + await settled(page); + expect((await notice(page)).count).toBe(0); + } finally { + await page.close(); + } + }, 120_000); }); diff --git a/mobile/src/api/generated/conversations/conversations.ts b/mobile/src/api/generated/conversations/conversations.ts index 32cff6b476..1169296b43 100644 --- a/mobile/src/api/generated/conversations/conversations.ts +++ b/mobile/src/api/generated/conversations/conversations.ts @@ -43,7 +43,7 @@ export const getCreateConversationJoinTokenUrl = ( }; /** - * Make a join token for the conversation's thread, and say where to use it. The token opens the threadStream channel of api/asyncapi.yaml: a WebSocket that replays the Bot's runs in the conversation, a run in progress from its start, and then carries on live. The token works once and for about half a minute, so ask for a new one for every connection, and again to reconnect. Only a person in the conversation may have one, and it opens the thread they see there and no other. A conversation no Bot has run in yet has nothing to join (409). Where realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app's access token, or an API key, as Authorization: Bearer or x-api-key. So a script that holds only an API key can watch a conversation live. + * Make a join token for the conversation's thread, and say where to use it. The token opens the threadStream channel of api/asyncapi.yaml: a WebSocket that replays the Bot's runs in the conversation, a run in progress from its start, and then carries on live. The token works once and for about half a minute, so ask for a new one for every connection, and again to reconnect. Only a person in the conversation may have one, and it opens the thread they see there and no other. A conversation no Bot has run in yet has nothing to join (409). Where realtime.clientUrl is on this server, open it with the same credential that made the token: the session, an app's access token, or an API key, as Authorization: Bearer or x-api-key. So a script that holds only an API key can watch a conversation live. The answer also names the thread's last run and how it ended (lastRun), as a thread's status says whether its last run failed. * @summary Get a token to watch a conversation live */ export const createConversationJoinToken = async ( diff --git a/mobile/src/api/generated/model/conversationJoinToken.ts b/mobile/src/api/generated/model/conversationJoinToken.ts index 9b69ded0bc..9072bd4768 100644 --- a/mobile/src/api/generated/model/conversationJoinToken.ts +++ b/mobile/src/api/generated/model/conversationJoinToken.ts @@ -2,6 +2,7 @@ * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. */ import type { ConversationJoinTokenRealtime } from "./conversationJoinTokenRealtime"; +import type { ConversationRun } from "./conversationRun"; /** * What a client needs to watch a conversation live: a token, and the socket and topic to use it on (the threadStream channel of api/asyncapi.yaml). @@ -24,6 +25,8 @@ export interface ConversationJoinToken { * @nullable */ runId: string | null; + /** The Bot's most recent run in the thread, and how it ended, as getConversationRun says it: the run in progress, while one is (its outcome null), and otherwise the last one. Null when this server keeps no record of a run in the thread. Absent from a server before it said this. A client that opens the conversation without replaying its runs to the end reads here whether the last one failed, so it can say so and offer to carry on, as it would had it heard the run's RUN_ERROR. */ + lastRun?: ConversationRun | null; /** Where to use the token. */ realtime: ConversationJoinTokenRealtime; }