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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,14 @@ A folder whose `agent.yaml` names a `plugins` list now fails to load with `plugi

## Bug Fixes

### JavaScript: a live UI patch is merged onto the card the router merges it onto

`Conversation` merges an OpenUI patch onto the UI of the latest earlier turn that completed and was not interrupted, whatever its format, as the router does and as Kotlin has since #2089. It used to take the latest OpenUI card it held, so with an A2UI card in between, or after an interrupted reply, the live preview showed a card Stream Chat's copy then replaced. A patch whose base is not OpenUI now shows no UI on its turn, even a preview already merged onto an older card, and Stream Chat's copy is the one that shows.

### The assistant and demo sample apps open sessions with their tools again

The sample apps' agents name their tools in a tool group (`swift_assistant`: the assistants' device tools and `reserve_table`; `swift_demo`: `lookup_order` and `issue_refund`), which the router has required of a session's tools since #2088. Sync them again with `go run ./configure`.

### A hosted tool call in a group channel names the person who wrote

In a channel an agent config answers through `chat_channels`, a call of a tool your backend hosts (a dispatch worker) named no user, so a backend acting for "the user who asked" (`tools.ToolCallContextFrom(ctx).User.ID`) got an empty id and had to refuse. Each call now names the writer of the message its turn answers, by user id and name: Anya's turn names Anya, and Ben's next one Ben, whether the config answers every message or only its mentions. A session opened with a user's token still names that user.
Expand Down
4 changes: 2 additions & 2 deletions examples/voice_agents/react_assistant/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Stream token are all swift_assistant's, as they are for the [Android app](../and
Only the page is here.

```
package.json React and Vite over @stream-io/stream-agents (0.4.1 and up, for its
package.json React and Vite over @stream-io/stream-agents (0.5.0 and up, for its
AgentChat, with stream-chat 10) and stream-chat-react's AI components
(15.0.1 and up)
connected.html where a connector's sign-in comes back to
Expand All @@ -15,7 +15,7 @@ tests/ its pure parts (captions, the glow's phases, photos, days) and
over a fake channel and session
```

The conversation's state is stream-chat-react's `AIConversationController`: the question on its way, whether Juno thinks or writes, errors and Try again, Send turning into Stop. Its transport is the SDK's `AgentChat` (`agentChatTransport`), which reads the router's channel and session. The page keeps only what is its own, in `src/chatScreen.ts`: voice mode, and naming a new conversation to the list once it is used. Edit and regenerate are turned off (`actions`), since the router keeps the conversation in Stream Chat and can't rewind it.
The conversation's state is stream-chat-react's `AIConversationController`: the question on its way, whether Juno thinks or writes, errors and Try again, Send turning into Stop. Its transport is the SDK's `AgentChat` (`agentChatTransport`), which reads the router's channel and session. The page keeps only what is its own, in `src/chatScreen.ts`: voice mode, and naming a new conversation to the list once it is used. Regenerating a reply or editing a question asks again beside the earlier version, which the router keeps; an incognito chat keeps nothing to branch from, so it turns both off (`actions`). Answering a tool's question goes through `chat.decide`, which reads the call from the loaded messages, so a question asked before a reload or on another device is answered too.
It runs on `stream-chat` 10 and `stream-chat-react` 15, with React 19, Vite 8 and TypeScript 7.
That takes Node 22.18 or newer: `stream-chat` 10's own floor, above Vite 8's.

Expand Down
1 change: 1 addition & 0 deletions examples/voice_agents/react_assistant/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ function screenDeps(tools: Tools, incognito: boolean): ChatScreenDeps {
},
approver: approverFor,
voiceOf: (session) => VoiceSession.of(session),
incognito,
};
}

Expand Down
4 changes: 3 additions & 1 deletion examples/voice_agents/react_assistant/src/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,9 @@ export function approverFor(chat: AgentChat<LocalMessage>): AIToolApprover {
if (allowed && call.name === "add_reminder" && "Notification" in window && Notification.permission === "default") {
void Notification.requestPermission();
}
(await chat.session()).decide(call.id, { allowed });
// Read from the loaded messages, so a call asked before this page opened the session, after
// a reload or on another device, is answered too.
await chat.decide(call.id, { allowed });
},
};
}
Expand Down
7 changes: 5 additions & 2 deletions examples/voice_agents/react_assistant/src/chatScreen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export interface ChatScreenDeps {
approver(chat: AgentChat<LocalMessage>): AIToolApprover;
/** The call of a session whose voice is on. */
voiceOf(session: Session): VoiceSession;
/** Whether the chat's sessions keep nothing, so there are no earlier versions to branch from. */
incognito?: boolean;
}

export interface ChatScreenSnapshot {
Expand Down Expand Up @@ -106,8 +108,9 @@ export class ChatScreen extends Store<ChatScreenSnapshot> {
workingText: workingLabel,
}),
approver: deps.approver(this.chat),
// The router keeps the conversation in Stream Chat and can't rewind it.
actions: { edit: false, regenerate: false },
// The transport branches: a regenerate or an edit asks again beside the earlier version,
// which the router keeps. An incognito session keeps nothing to branch from.
...(deps.incognito ? { actions: { edit: false, regenerate: false } } : {}),
});
let announced = sessionId !== undefined;
this.stops.push(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,17 @@ describe("ChatScreen", () => {
expect(sessions[0]?.asked[0]?.options.uiAction).toEqual(uiAction);
});

it("offers neither editing nor regenerating, which the router can't do", () => {
it("offers editing and regenerating, which the transport branches", () => {
const { deps } = router();
const screen = new ChatScreen(undefined, deps, () => undefined);

expect(screen.conversation.actions).toMatchObject({ edit: true, regenerate: true, rate: true });
});

it("offers neither editing nor regenerating in an incognito chat, which keeps nothing to branch from", () => {
const { deps } = router();
const screen = new ChatScreen(undefined, { ...deps, incognito: true }, () => undefined);

expect(screen.conversation.actions).toMatchObject({ edit: false, regenerate: false, rate: true });
});

Expand Down
7 changes: 7 additions & 0 deletions examples/voice_agents/swift_assistant/agent.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ search: search-fast
greeting:
text: Hey, it's Juno. What's on your mind?
mode: exact
# The apps' own tools: the iOS, Android, Flutter, React and React Native assistants declare them
# on their sessions, and the trip card adds reserve_table while a table is free. The router
# offers a session only the tools a group here names, and refuses one that declares any other.
tools:
- name: device
loading: full
tools: [get_local_context, get_location, list_events, add_reminder, send_email, reserve_table]
# Each person's own Gmail and Linear. The first time the agent reaches for one the person has
# not connected, its call waits on a sign-in shown on its step in the chat, and carries on once
# they have. Google's MCP server reads, searches and drafts; sending is send_email, a tool on
Expand Down
6 changes: 6 additions & 0 deletions examples/voice_agents/swift_demo/agent.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
name: swift_demo
description: The support agent the iOS demo app talks to.
# The tools the iOS, Android and Flutter demos declare on their sessions. The router offers a
# session only the tools a group here names, and refuses one that declares any other.
tools:
- name: support
loading: full
tools: [lookup_order, issue_refund]
61 changes: 50 additions & 11 deletions sdks/js/src/conversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ export class Conversation {
private readonly uiRawByTurn = new Map<string, PendingUI>();
/** When the model last took each turn in flight up again, which a round of thinking is timed from. */
private readonly resumedAt = new Map<string, number>();
/**
* The agent turns with UI that were interrupted. Their UI still shows, but the router never
* merges a patch onto it.
*/
private readonly cut = new Set<string>();

constructor(connected: boolean) {
this.snapshot = Object.freeze({
Expand Down Expand Up @@ -307,6 +312,9 @@ export class Conversation {
case "interrupted": {
const turnId = text(frame, "turn_id");
this.settleUI(turnId, now);
if (this.snapshot.turns[this.agentTurnIndex(turnId)]?.ui) {
this.cut.add(turnId);
}
this.resumedAt.delete(turnId);
this.amend(turnId, now, (turn) => ended(settled(turn, now)), false);
return;
Expand Down Expand Up @@ -427,6 +435,10 @@ export class Conversation {
if (content === undefined) {
return;
}
if (content === null) {
this.clearUI(turnId);
return;
}
this.writeUI(
turnId,
Object.freeze({
Expand Down Expand Up @@ -460,13 +472,30 @@ export class Conversation {
this.turns(next);
}

/** The agent turn `turnId` without the UI it showed, such as a preview merged onto the wrong base. */
private clearUI(turnId: string): void {
const turns = this.snapshot.turns;
const index = this.agentTurnIndex(turnId);
const turn = turns[index];
if (!turn?.ui) {
return;
}
const { ui, ...kept } = turn;
const next = turns.slice();
next[index] = Object.freeze(kept);
this.turns(next);
}

/**
* A turn's UI as it shows: what was written, or a patch merged onto the UI before it. Of OpenUI,
* only the statements `keep` says count. Undefined when there is nothing to show yet, and for a
* patch with no UI before it here, such as after a reload: Stream Chat's copy, which the router
* merged, is the one that shows.
* A turn's UI as it shows: what was written, or a patch merged onto the router's base. The base
* is the UI of the latest earlier turn that is complete and was not cut off, whatever its
* format, earlier than this one even when its UI comes late. Of OpenUI, only the statements
* `keep` says count. Undefined when there is nothing to show yet. Null for a patch whose base
* is not OpenUI, or that has none here, such as after a reload: the turn then shows no UI, even
* one merged onto an earlier base, and Stream Chat's copy, which the router merged, is the one
* that shows.
*/
private resolveUIContent(turnId: string, { format, mode, raw }: PendingUI, keep: OpenUIKeep): string | undefined {
private resolveUIContent(turnId: string, { format, mode, raw }: PendingUI, keep: OpenUIKeep): string | null | undefined {
if (format !== "openui") {
return raw;
}
Expand All @@ -478,13 +507,23 @@ export class Conversation {
return written;
}
const turns = this.snapshot.turns;
for (let index = turns.length - 1; index >= 0; index--) {
const earlier = turns[index];
if (earlier?.speaker === "agent" && earlier.id !== turnId && earlier.ui?.format === "openui" && earlier.ui.content) {
return mergeOpenUIStatements(earlier.ui.content, written);
}
const index = this.agentTurnIndex(turnId);
// A turn we never saw begin starts after every one there is.
const earlier = index === -1 ? turns : turns.slice(0, index);
// The router's base is the card it last completed whatever its format, never one it cut off
// or one still streaming; only OpenUI takes a patch.
const base = earlier.findLast(
(turn) =>
turn.speaker === "agent" &&
turn.id !== turnId &&
!this.cut.has(turn.id) &&
turn.ui?.status === "complete" &&
turn.ui.content !== "",
)?.ui;
if (base?.format !== "openui") {
return null;
}
return undefined;
return mergeOpenUIStatements(base.content, written);
}

/**
Expand Down
45 changes: 45 additions & 0 deletions sdks/js/tests/live-ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,51 @@ describe("Conversation dynamic UI streaming", () => {
assert.equal(conversation.get().turns[1]?.ui?.content, '$party = 4\nroot = Card([hdr])\nhdr = CardHeader("Kaneo")');
});

it("merges a patch onto the card the router completed last, never one cut off", () => {
// The router never takes an interrupted reply's card as the base: the patch is merged onto
// the one before it, and Stream Chat's copy says so.
const conversation = new Conversation(true);
conversation.observe({ type: "responding", turn_id: "t1" }, 1);
conversation.observe(
{ type: "ui_completed", turn_id: "t1", format: "openui", content: 'root = Card([hdr])\nhdr = CardHeader("Kaneo")' },
2,
);
conversation.observe({ type: "responded", turn_id: "t1", text: "" }, 3);
conversation.observe({ type: "responding", turn_id: "t2" }, 4);
conversation.observe(
{ type: "ui_delta", turn_id: "t2", format: "openui", delta: 'root = Card([hdr])\nhdr = CardHeader("Nopa")\n' },
5,
);
conversation.observe({ type: "interrupted", turn_id: "t2" }, 6);
conversation.observe({ type: "responding", turn_id: "t3" }, 7);

conversation.observe({ type: "ui_delta", turn_id: "t3", format: "openui", mode: "patch", delta: "$party = 4\n" }, 8);

assert.equal(conversation.get().turns[2]?.ui?.content, 'root = Card([hdr])\nhdr = CardHeader("Kaneo")\n$party = 4');
assert.equal(conversation.get().turns[1]?.ui?.content, 'root = Card([hdr])\nhdr = CardHeader("Nopa")');
});

it("merges no patch past a card of another format, even one that completes late", () => {
// The router's base is the card it last completed whatever its format, and only OpenUI
// takes a patch: an A2UI card between leaves the patch to Stream Chat's copy, and drops a
// preview already merged onto the older OpenUI card.
const conversation = new Conversation(true);
conversation.observe({ type: "responding", turn_id: "t1" }, 1);
conversation.observe(
{ type: "ui_completed", turn_id: "t1", format: "openui", content: 'root = Card([hdr])\nhdr = CardHeader("Kaneo")' },
2,
);
conversation.observe({ type: "responding", turn_id: "t2" }, 3);
conversation.observe({ type: "responding", turn_id: "t3" }, 4);
conversation.observe({ type: "ui_delta", turn_id: "t3", format: "openui", mode: "patch", delta: "$party = 4\n" }, 5);
assert.equal(conversation.get().turns[2]?.ui?.status, "streaming");

conversation.observe({ type: "ui_completed", turn_id: "t2", format: "a2ui", version: "1.0", content: "[]" }, 6);
conversation.observe({ type: "ui_completed", turn_id: "t3", format: "openui", mode: "patch", content: "$party = 4" }, 7);

assert.equal(conversation.get().turns[2]?.ui, undefined);
});

it("shows an interrupted turn's last statement when it closed, and settles its UI", () => {
// An interrupted reply never gets ui_completed: the router drops the block with the turn.
const conversation = new Conversation(true);
Expand Down
Loading