Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

bugfix: fix session events api calls in chat page for better ux (#1111)

harshil-20962b88c4badd06
diff --git a/.changeset/paint-session-events-before-tip.md b/.changeset/paint-session-events-before-tip.md
new file mode 100644
index 000000000..a50a42bd1
--- /dev/null
+++ b/.changeset/paint-session-events-before-tip.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge-assistant-ui-runtime': patch
+---
+
+Paint a loaded session from its events window before confirming the tip, and stop fetching the oldest turn to decide whether that tip is still running. A send that applies its message in that window is kept, a send that fails before then still lets the load finish, and a tip that finishes before its done event is still shown.
diff --git a/packages/assistant-ui-runtime/src/convertTurnMessages.ts b/packages/assistant-ui-runtime/src/convertTurnMessages.ts
index 1a500aff9..abb02028b 100644
--- a/packages/assistant-ui-runtime/src/convertTurnMessages.ts
+++ b/packages/assistant-ui-runtime/src/convertTurnMessages.ts
@@ -473,6 +473,28 @@ function ingestSessionEventsIntoSnapshot(
}
}
+function rootModelMessageIdsForOpenTip(snapshot: SessionSnapshot): readonly string[] {
+ const committed = new Set(snapshot.turns.flatMap(turn => turn.rootModelMessageIds ?? []));
+ const rootIds = snapshot.fold.threads.get(ROOT_THREAD_ID)?.modelMessageIds ?? [];
+ return rootIds.filter(id => !committed.has(id));
+}
+
+/** Commits an open tip that finished before `turn.done` was in the events page. */
+function commitFinishedOpenTip(snapshot: SessionSnapshot, turn: Turn): SessionSnapshot {
+ if (snapshot.turns.some(existing => existing.id === turn.id)) {
+ return snapshot;
+ }
+ return replaceSessionSnapshot(snapshot, {
+ turns: [
+ ...snapshot.turns,
+ {
+ ...turnToSessionRecord(turn),
+ rootModelMessageIds: rootModelMessageIdsForOpenTip(snapshot),
+ },
+ ],
+ });
+}
+
function attachRunningTurn(snapshot: SessionSnapshot, runningTurn: Turn | undefined): SessionSnapshot {
if (runningTurn == null) {
return snapshot;
@@ -536,6 +558,12 @@ function turnFromCreatedEvent(options: { sessionId: string; turnId: string; even
interface SessionTip {
/** Turn to resume and subscribe to; absent once the tip has finished. */
runningTurn?: Turn;
+ /**
+ * Open tip that finished between `listEvents` and `getTurn`. It was not in
+ * the events page as `turn.done`, so the caller must commit it or the user
+ * message painted from the progress snapshot disappears.
+ */
+ finishedTurn?: Turn;
/**
* Tip input that event ingestion could not apply, because it only folds a
* turn's input once that turn's `turn.done` arrives. Answered ask-user
@@ -548,56 +576,49 @@ interface SessionTip {
/**
* Resolves the tip turn of the active branch for resume/subscribe.
*
- * Prefer an open tip from the events window (works when listTurns is
- * oldest-first and when listEvents includes the running turn). Fall back to
- * `listTurns({ limit: 1 })` for hosts that omit the running turn from
- * listEvents and put the tip first.
+ * An open `turn.created` with no later `turn.done` is the tip. `listEvents`
+ * includes that turn, so a finished window needs no extra turns fetch.
*/
async function resolveSessionTip(options: {
server: AgentChatServer;
sessionId: string;
itemsAsc: readonly GatewaySessionEventItem[];
}): Promise<SessionTip> {
- const { server, sessionId, itemsAsc } = options;
- const open = findOpenTurnCreated(itemsAsc);
- if (open != null) {
- const continuationInput = open.event.input ?? [];
- if (typeof server.getTurn === 'function') {
- try {
- const turn = await server.getTurn({
- sessionId,
- turnId: open.turnId,
- });
- if (turn.state.status === 'running') {
- return {
- runningTurn: turn,
- continuationInput: turn.input ?? continuationInput,
- };
- }
- // Tip finished between listEvents and getTurn: nothing to
- // resume, but its answers still belong in the fold.
- return { continuationInput: turn.input ?? continuationInput };
- } catch {
- // getTurn failed; synthesize from the open turn.created below.
- }
- }
- return {
- runningTurn: turnFromCreatedEvent({
+ const open = findOpenTurnCreated(options.itemsAsc);
+ if (open == null) {
+ return { continuationInput: [] };
+ }
+
+ const { server, sessionId } = options;
+ const continuationInput = open.event.input ?? [];
+ if (typeof server.getTurn === 'function') {
+ try {
+ const turn = await server.getTurn({
sessionId,
turnId: open.turnId,
- event: open.event,
- }),
- continuationInput,
- };
+ });
+ if (turn.state.status === 'running') {
+ return {
+ runningTurn: turn,
+ continuationInput: turn.input ?? continuationInput,
+ };
+ }
+ // Tip finished between listEvents and getTurn: nothing to
+ // resume, but its answers still belong in the fold, and the turn
+ // itself must be committed so the painted user message stays.
+ return { finishedTurn: turn, continuationInput: turn.input ?? continuationInput };
+ } catch {
+ // getTurn failed; synthesize from the open turn.created below.
+ }
}
-
- // Hosts that exclude the running turn from listEvents still surface it as
- // the first row of listTurns when that API is tip-first.
- const turnsPage = await server.listTurns({ sessionId, limit: 1 });
- const tip = turnsPage.data[0];
- return tip?.state.status === 'running'
- ? { runningTurn: tip, continuationInput: tip.input ?? [] }
- : { continuationInput: [] };
+ return {
+ runningTurn: turnFromCreatedEvent({
+ sessionId,
+ turnId: open.turnId,
+ event: open.event,
+ }),
+ continuationInput,
+ };
}
/**
@@ -605,12 +626,10 @@ async function resolveSessionTip(options: {
*
* Loads the newest event page (extending only when a page boundary splits a
* turn group), then leaves older pages for `prependOlderSessionHistory`.
- * Detects a currently-running tip from an open `turn.created` in that window
- * when present; otherwise falls back to `listTurns({ limit: 1 })` for hosts
- * that omit the running turn from listEvents.
+ * A currently-running tip is an open `turn.created` in that window.
*
- * `onProgress` is called after each complete turn is ingested so callers can
- * update the UI progressively while the processing loop runs.
+ * `onProgress` fires after each complete turn, then once with the paintable
+ * window before `getTurn`, so callers can clear loading before the tip is confirmed.
*/
export async function buildSnapshotFromSessionEvents(
server: AgentChatServer,
@@ -631,6 +650,25 @@ export async function buildSnapshotFromSessionEvents(
historyPagination,
});
+ const open = findOpenTurnCreated(window.itemsAsc);
+ // The open tip is not in `turns` until `turn.done`. Attach it from the
+ // event so the first paint includes its user message.
+ const paintable =
+ open == null
+ ? withHistory
+ : attachRunningTurn(
+ withHistory,
+ turnFromCreatedEvent({
+ sessionId,
+ turnId: open.turnId,
+ event: open.event,
+ }),
+ );
+ if (open != null) {
+ applyUserToolResponsesToFold(paintable.fold, open.event.input ?? []);
+ }
+ onProgress?.(paintable);
+
const tip = await resolveSessionTip({
server,
sessionId,
@@ -638,8 +676,12 @@ export async function buildSnapshotFromSessionEvents(
});
// The tip has no turn.done in this window, so ingestion never folded its
// input. Apply it here so answered approvals / ask-user prompts are not
- // restored as pending after a refresh.
+ // restored as pending after a refresh. `getTurn` may carry answers that
+ // were not on `turn.created`; the write is keyed by tool call id.
applyUserToolResponsesToFold(withHistory.fold, tip.continuationInput);
+ if (tip.finishedTurn != null) {
+ return commitFinishedOpenTip(withHistory, tip.finishedTurn);
+ }
return attachRunningTurn(withHistory, tip.runningTurn);
}
diff --git a/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts b/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
index 1978f7bf9..a1578bd36 100644
--- a/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
+++ b/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
@@ -522,6 +522,9 @@ export function useTrueForgeAgentMessages({
const runningTurnRef = useRef<Turn | undefined>(undefined);
const loadGenerationRef = useRef(0);
const streamGenerationRef = useRef(0);
+ // Bumped once a send has applied its message. An earlier failure must not
+ // discard the in-flight load or cancel the painted tip.
+ const sendEpochRef = useRef(0);
const streamReconnectPendingRef = useRef(false);
const cancelRequestedRef = useRef(false);
const lazilyCreatedSessionIdRef = useRef<string | undefined>(undefined);
@@ -781,6 +784,7 @@ export function useTrueForgeAgentMessages({
const generation = ++loadGenerationRef.current;
++streamGenerationRef.current;
+ const sendEpoch = sendEpochRef.current;
setIsRunning(false);
markResumeUnavailable(false);
abortControllerRef.current?.abort();
@@ -793,11 +797,16 @@ export function useTrueForgeAgentMessages({
try {
const conversationSessionId = await resolveActiveSessionId(sessionId, resolveConversationSessionIdRef.current);
const loadedSnapshot = await loadSessionSnapshot(server, conversationSessionId, snap => {
- if (generation === loadGenerationRef.current) {
- setSnapshot(snap);
+ if (generation !== loadGenerationRef.current) {
+ return;
}
+ // The events window is paintable before getTurn confirms the tip.
+ setSnapshot(snap);
+ setIsLoading(false);
});
- if (generation !== loadGenerationRef.current) {
+ if (generation !== loadGenerationRef.current || sendEpoch !== sendEpochRef.current) {
+ // A send applied its message while getTurn was in flight. Applying this
+ // snapshot would drop that message and resume the old tip.
return;
}
@@ -1020,6 +1029,9 @@ export function useTrueForgeAgentMessages({
snapshotRef.current.groupRootBaseline ?? computeGroupRootBaseline(snapshotRef.current.turns);
}
+ // The message is on the snapshot. A load still awaiting getTurn must
+ // leave this send in place. Failures before this point do not count.
+ ++sendEpochRef.current;
runStreamStarted = true;
await runStream(
(signal, track) => {
@@ -1098,7 +1110,11 @@ export function useTrueForgeAgentMessages({
options.onPreTurnFailure?.();
}
if (!runStreamStarted) {
- if ('userMessage' in options) {
+ // A supersede already aborted the live stream. A send that fails
+ // before it installs a message must not cancel the painted open tip.
+ const hasIncompleteStream =
+ snapshotRef.current.activeStream != null && snapshotRef.current.activeStream.streamComplete !== true;
+ if ('userMessage' in options && (pendingUserWasSet || hasIncompleteStream)) {
const abandoned = abandonInFlightClientTurn(commitActiveStream(snapshotRef.current));
snapshotRef.current = abandoned;
setSnapshot(abandoned);
diff --git a/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts b/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
index 8e9dc016b..6dff447d3 100644
--- a/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
+++ b/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
@@ -179,28 +179,33 @@ function ancestorChainFromTurns(turns: TurnFixture[], anchorTurnId: string): Tur
return chain;
}
+function turnCreatedItem(turn: TurnFixture): SessionEventItem {
+ return {
+ turnId: turn.id,
+ event: {
+ type: 'turn.created',
+ id: `created-${turn.id}`,
+ turnId: turn.id,
+ ...(turn.input === undefined ? {} : { input: turn.input }),
+ state: { status: 'running' },
+ createdAt: turn.createdAt,
+ ...(turn.previousTurnId === undefined ? {} : { previousTurnId: turn.previousTurnId }),
+ },
+ };
+}
+
/**
* Builds session-level event items from per-turn mocks — accepts ASC or DESC
- * listTurns order; running turns excluded (matches session.listEvents). An
- * anchor selects that turn's ancestor chain, not a chronological prefix.
+ * listTurns order. Finished turns include `turn.done`. A running tip is an open
+ * `turn.created` without its content events, which `listTurnEvents` supplies.
+ * An anchor selects that turn's ancestor chain, not a chronological prefix.
*/
function sessionEventItemsFromTurns(turns: TurnFixture[], lastTurnId?: string): SessionEventItem[] {
const chain = lastTurnId == null ? toOldestFirstTurns(turns) : ancestorChainFromTurns(turns, lastTurnId);
const items: SessionEventItem[] = [];
for (const turn of chain) {
- items.push({
- turnId: turn.id,
- event: {
- type: 'turn.created',
- id: `created-${turn.id}`,
- turnId: turn.id,
- ...(turn.input === undefined ? {} : { input: turn.input }),
- state: { status: 'running' },
- createdAt: turn.createdAt,
- ...(turn.previousTurnId === undefined ? {} : { previousTurnId: turn.previousTurnId }),
- },
- });
+ items.push(turnCreatedItem(turn));
for (const event of turn.events) {
items.push({ turnId: turn.id, event });
}
@@ -214,6 +219,17 @@ function sessionEventItemsFromTurns(turns: TurnFixture[], lastTurnId?: string):
},
});
}
+
+ if (lastTurnId == null) {
+ for (const turn of turns) {
+ if (turn.state.status !== 'running' || chain.some(done => done.id === turn.id)) {
+ continue;
+ }
+ // Open tip only. Content stays on listTurnEvents so convertTurnsToThreadMessages
+ // attributes it once when it hydrates the running turn.
+ items.push(turnCreatedItem(turn));
+ }
+ }
return items;
}
@@ -2884,7 +2900,7 @@ describe('buildSnapshotFromSessionEvents', () => {
expect(messages[1]?.createdAt).toEqual(new Date(turnCompletedAt));
});
- it('detects and attaches the running turn without events', async () => {
+ it('does not attach a running turn that listEvents omits', async () => {
const runningTurn = {
id: 't2',
state: { status: 'running' },
@@ -2917,20 +2933,14 @@ describe('buildSnapshotFromSessionEvents', () => {
createdAt,
} as TurnDoneEvent,
},
- // t2 (running) has no events — it is excluded from session-level listEvents
];
const snapshot = await buildSnapshotFromSessionEvents(mockServerWithEvents([runningTurn], items), SESSION_ID);
expect(snapshot.turns).toHaveLength(1);
expect(snapshot.turns[0]?.id).toBe('t1');
- expect(snapshot.runningTurn).toBe(runningTurn);
- expect(snapshot.unstable_resume).toBe(true);
- expect(snapshot.groupRootBaseline).toEqual(['m1']);
- expect(snapshot.pendingUser).toMatchObject({
- turnId: 't2',
- content: 'in progress',
- });
+ expect(snapshot.runningTurn).toBeUndefined();
+ expect(snapshot.pendingUser).toBeUndefined();
});
it('baselines all prior root model messages when resuming a new user tip', async () => {
@@ -3163,10 +3173,10 @@ describe('buildSnapshotFromSessionEvents', () => {
progressSnapshots.push(snap.turns.length),
);
- expect(progressSnapshots).toEqual([1, 2]);
+ expect(progressSnapshots).toEqual([1, 2, 2]);
});
- it('falls back to listTurns({ limit: 1 }) when listEvents omits the running tip', async () => {
+ it('does not call listTurns when listEvents has no open tip', async () => {
const listTurns = vi.fn(async () => ({
data: [
{
@@ -3187,15 +3197,73 @@ describe('buildSnapshotFromSessionEvents', () => {
} as unknown as AgentChatServer;
const snapshot = await buildSnapshotFromSessionEvents(server, SESSION_ID);
- expect(listTurns).toHaveBeenCalledWith({ sessionId: SESSION_ID, limit: 1 });
+ expect(listTurns).not.toHaveBeenCalled();
+ expect(snapshot.runningTurn).toBeUndefined();
+ expect(snapshot.pendingUser).toBeUndefined();
+ });
+
+ it('publishes the open tip before getTurn resolves', async () => {
+ const progress: SessionSnapshot[] = [];
+ let resolveGetTurn: (turn: Turn) => void = () => undefined;
+ const getTurn = vi.fn(
+ () =>
+ new Promise<Turn>(resolve => {
+ resolveGetTurn = resolve;
+ }),
+ );
+ const items: SessionEventItem[] = [
+ {
+ turnId: 't-running',
+ event: {
+ type: 'turn.created',
+ id: 'evt-c-running',
+ turnId: 't-running',
+ input: [{ type: 'user.message', content: 'now' }],
+ state: { status: 'running' },
+ createdAt,
+ },
+ },
+ ];
+ const listTurns = vi.fn(async () => ({ data: [] }));
+ const server = {
+ listTurns,
+ getTurn,
+ listEvents: sessionEventsPage(items),
+ listTurnEvents: async () => ({ data: [] }),
+ } as unknown as AgentChatServer;
+
+ let notifyProgress: () => void = () => undefined;
+ const progressed = new Promise<void>(resolve => {
+ notifyProgress = resolve;
+ });
+ const pending = buildSnapshotFromSessionEvents(server, SESSION_ID, snap => {
+ progress.push(snap);
+ if (snap.pendingUser != null) {
+ notifyProgress();
+ }
+ });
+
+ await progressed;
+ expect(getTurn).toHaveBeenCalledWith({ sessionId: SESSION_ID, turnId: 't-running' });
+ expect(progress.at(-1)?.pendingUser?.content).toBe('now');
+ expect(progress.at(-1)?.runningTurn?.id).toBe('t-running');
+ expect(listTurns).not.toHaveBeenCalled();
+
+ resolveGetTurn({
+ id: 't-running',
+ sessionId: SESSION_ID,
+ state: { status: 'running' },
+ input: [{ type: 'user.message', content: 'now' }],
+ createdAt,
+ });
+ const snapshot = await pending;
expect(snapshot.runningTurn?.id).toBe('t-running');
expect(snapshot.pendingUser?.content).toBe('now');
});
it('attaches an open tip from events when listTurns is oldest-first and clears answered ask-user', async () => {
- // Trueforge listTurns is ASC: limit:1 returns the oldest done turn even
- // while a later tip is still running. Tip detection must use the open
- // turn.created in listEvents (which includes running turns).
+ // listEvents includes the running turn. Tip detection uses the open
+ // turn.created, because listTurns is oldest-first.
const oldestDoneTurn = {
id: 't-pause',
sessionId: SESSION_ID,
@@ -3474,6 +3542,81 @@ describe('buildSnapshotFromSessionEvents', () => {
}
});
+ it('keeps the painted user message when the open tip finished before getTurn', async () => {
+ const finishedTip = {
+ id: 't2',
+ sessionId: SESSION_ID,
+ state: { status: 'done', requiredActions: [], completedAt: createdAt },
+ input: [{ type: 'user.message', content: 'what is 2+2' }],
+ createdAt,
+ } as unknown as Turn;
+
+ const items: SessionEventItem[] = [
+ {
+ turnId: 't1',
+ event: {
+ type: 'turn.created',
+ id: 'evt-c1',
+ turnId: 't1',
+ input: [{ type: 'user.message', content: 'hello' }],
+ state: { status: 'running' },
+ createdAt,
+ },
+ },
+ {
+ turnId: 't1',
+ event: modelMessage({ id: 'm1', threadId: ROOT_THREAD_ID, content: 'hi' }),
+ },
+ {
+ turnId: 't1',
+ event: {
+ type: 'turn.done',
+ id: 'evt-d1',
+ state: { status: 'done', requiredActions: [], completedAt: createdAt },
+ createdAt,
+ } as TurnDoneEvent,
+ },
+ {
+ turnId: 't2',
+ event: {
+ type: 'turn.created',
+ id: 'evt-c2',
+ turnId: 't2',
+ previousTurnId: 't1',
+ input: [{ type: 'user.message', content: 'what is 2+2' }],
+ state: { status: 'running' },
+ createdAt,
+ },
+ },
+ {
+ turnId: 't2',
+ event: modelMessage({ id: 'm2', threadId: ROOT_THREAD_ID, content: '4' }),
+ },
+ ];
+
+ const progress: SessionSnapshot[] = [];
+ const server = {
+ listTurns: vi.fn(async () => ({ data: [] })),
+ getTurn: vi.fn(async () => finishedTip),
+ listEvents: sessionEventsPage(items),
+ listTurnEvents: async () => ({ data: [] }),
+ } as unknown as AgentChatServer;
+
+ const snapshot = await buildSnapshotFromSessionEvents(server, SESSION_ID, snap => {
+ progress.push(snap);
+ });
+
+ expect(progress.some(snap => snap.pendingUser?.content === 'what is 2+2')).toBe(true);
+ expect(snapshot.runningTurn).toBeUndefined();
+ expect(snapshot.pendingUser).toBeUndefined();
+ expect(snapshot.turns.map(turn => turn.id)).toEqual(['t1', 't2']);
+
+ const texts = projectSessionMessages(snapshot).flatMap(message =>
+ message.content.flatMap(part => (part.type === 'text' ? [part.text] : [])),
+ );
+ expect(texts).toEqual(['hello', 'hi', 'what is 2+2', '4']);
+ });
+
it('loads only the newest event page and exposes an older-history cursor', async () => {
const makeTurnItems = (id: string, text: string): SessionEventItem[] => [
{
diff --git a/packages/assistant-ui-runtime/test/useTrueForgeAgentMessages.test.tsx b/packages/assistant-ui-runtime/test/useTrueForgeAgentMessages.test.tsx
index 3033ec6a0..c34dc3b07 100644
--- a/packages/assistant-ui-runtime/test/useTrueForgeAgentMessages.test.tsx
+++ b/packages/assistant-ui-runtime/test/useTrueForgeAgentMessages.test.tsx
@@ -472,6 +472,147 @@ describe('useTrueForgeAgentMessages', () => {
);
});
+ it('clears isLoading from the progress snapshot before load resolves', async () => {
+ const progress = snapshotWithUserTurn('painted early');
+ let resolveLoad: (snapshot: SessionSnapshot) => void = () => undefined;
+ vi.mocked(loadSessionSnapshot).mockImplementation((_server, _sessionId, onProgress) => {
+ onProgress?.(progress);
+ return new Promise(resolve => {
+ resolveLoad = resolve;
+ });
+ });
+
+ const { result } = renderHook(() => useTrueForgeAgentMessages({ server: mockServer, sessionId: 'session-1' }));
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.messages).toHaveLength(1);
+ expect(result.current.messages[0]).toMatchObject({
+ role: 'user',
+ content: [{ type: 'text', text: 'painted early' }],
+ });
+ expect(resumeTurnStream).not.toHaveBeenCalled();
+
+ const runningTurn: Turn = {
+ id: 'turn-1',
+ sessionId: 'session-1',
+ input: [{ type: 'user.message', content: 'painted early' }],
+ state: { status: 'running' },
+ createdAt: new Date().toISOString(),
+ };
+ await act(async () => {
+ resolveLoad(
+ replaceSessionSnapshot(progress, {
+ runningTurn,
+ unstable_resume: true,
+ }),
+ );
+ });
+
+ await waitFor(() => expect(resumeTurnStream).toHaveBeenCalled());
+ });
+
+ it('does not apply a late load over a send started after paint', async () => {
+ const progress = snapshotWithUserTurn('painted early');
+ let resolveLoad: (snapshot: SessionSnapshot) => void = () => undefined;
+ vi.mocked(loadSessionSnapshot).mockImplementation((_server, _sessionId, onProgress) => {
+ onProgress?.(progress);
+ return new Promise(resolve => {
+ resolveLoad = resolve;
+ });
+ });
+
+ const { result } = renderHook(() => useTrueForgeAgentMessages({ server: mockServer, sessionId: 'session-1' }));
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ await act(async () => {
+ await result.current.sendTurn({ userMessage: 'also check' });
+ });
+
+ const runningTurn: Turn = {
+ id: 'turn-old',
+ sessionId: 'session-1',
+ input: [{ type: 'user.message', content: 'painted early' }],
+ state: { status: 'running' },
+ createdAt: new Date().toISOString(),
+ };
+ await act(async () => {
+ resolveLoad(
+ replaceSessionSnapshot(progress, {
+ runningTurn,
+ unstable_resume: true,
+ }),
+ );
+ });
+
+ expect(resumeTurnStream).not.toHaveBeenCalled();
+ const texts = result.current.messages.flatMap(message =>
+ message.content.flatMap(part => (part.type === 'text' ? [part.text] : [])),
+ );
+ expect(texts).toContain('also check');
+ });
+
+ it('keeps the in-flight load when a send fails before applying a message', async () => {
+ const createdAt = new Date();
+ const progress = replaceSessionSnapshot(createEmptySessionSnapshot(), {
+ pendingUser: {
+ turnId: 'turn-open',
+ content: 'what is 2+2',
+ createdAt,
+ },
+ });
+ let resolveLoad: (snapshot: SessionSnapshot) => void = () => undefined;
+ vi.mocked(loadSessionSnapshot).mockImplementation((_server, _sessionId, onProgress) => {
+ onProgress?.(progress);
+ return new Promise(resolve => {
+ resolveLoad = resolve;
+ });
+ });
+ const runningTurn: Turn = {
+ id: 'turn-open',
+ sessionId: 'session-1',
+ input: [{ type: 'user.message', content: 'what is 2+2' }],
+ state: { status: 'running' },
+ createdAt: createdAt.toISOString(),
+ };
+ const getTurnHeaders = vi.fn(async () => {
+ resolveLoad(
+ replaceSessionSnapshot(progress, {
+ runningTurn,
+ unstable_resume: true,
+ }),
+ );
+ throw new Error('headers failed');
+ });
+
+ const { result } = renderHook(() =>
+ useTrueForgeAgentMessages({
+ server: mockServer,
+ sessionId: 'session-1',
+ getTurnHeaders,
+ }),
+ );
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ await act(async () => {
+ await result.current.sendTurn({ userMessage: 'also check' }).catch(() => undefined);
+ });
+
+ expect(resumeTurnStream).toHaveBeenCalled();
+ expect(
+ result.current.messages.some(
+ message =>
+ message.role === 'assistant' && message.status.type === 'incomplete' && message.status.reason === 'cancelled',
+ ),
+ ).toBe(false);
+ const texts = result.current.messages.flatMap(message =>
+ message.content.flatMap(part => (part.type === 'text' ? [part.text] : [])),
+ );
+ expect(texts).toContain('what is 2+2');
+ expect(texts).not.toContain('also check');
+ });
+
it('loads converted session history on mount', async () => {
vi.mocked(loadSessionSnapshot).mockResolvedValue(snapshotWithUserTurn('hello'));