Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(ai): make tool rendering stable during streaming (#3778)

Eric Hayes139b939bdb38
diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
index 7521919dae..2bbe5a0e75 100644
--- a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
+++ b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
@@ -1,10 +1,5 @@
import { useSplitLayout } from '@app/component/split-layout/layout';
import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';
-import { ThinkingBlock } from '@core/component/AI/component/message/ThinkingBlock';
-import { RenderTool } from '@core/component/AI/component/tool/handler';
-import { McpToolCall } from '@core/component/AI/component/tool/McpToolCall';
-import { Tool } from '@core/component/AI/component/tool/Tool';
-import { useChatContext } from '@core/component/AI/context';
import { replaceCitations } from '@core/component/LexicalMarkdown/citationsUtils';
import { ENABLE_TTFT } from '@core/constant/featureFlags';
import { createMarkdownFile } from '@core/util/create';
@@ -14,21 +9,12 @@ import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid'
import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';
import LoadingIcon from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
import { generateTitle } from '@service-cognition/client';
-import type { AssistantMessagePart } from '@service-cognition/generated/schemas/assistantMessagePart';
import type { ChatMessageContent } from '@service-cognition/generated/schemas/chatMessageContent';
import type { ChatMessageWithAttachments } from '@service-cognition/generated/schemas/chatMessageWithAttachments';
import { createCallback } from '@solid-primitives/rootless';
import { Button } from '@ui';
-import {
- createMemo,
- createSelector,
- createSignal,
- For,
- Match,
- mapArray,
- Show,
- Switch,
-} from 'solid-js';
+import { createMemo, createSignal, Match, Show, Switch } from 'solid-js';
+import { AssistantMessageParts } from './AssistantMessageParts';
function messageContentIsEmpty(content: ChatMessageContent) {
if (typeof content === 'string' || Array.isArray(content)) {
@@ -241,279 +227,3 @@ export function AssistantMessage(props: {
</div>
);
}
-
-function getAssistantPartKey(
- part: AssistantMessagePart,
- counts: Map<AssistantMessagePart['type'], number>
-): string {
- if (
- part.type === 'toolCall' ||
- part.type === 'toolCallErr' ||
- part.type === 'mcpToolCall'
- ) {
- return `${part.type}:${part.id}`;
- }
-
- const count = counts.get(part.type) ?? 0;
- counts.set(part.type, count + 1);
- return `${part.type}:${count}`;
-}
-
-function AssistantMessageParts(props: {
- parts: AssistantMessagePart[];
- message: ChatMessageWithAttachments;
- isStreaming: boolean;
-}) {
- const chat = useChatContext();
- const completedToolIds = createMemo(() => {
- const ids = new Set<string>();
- for (const part of props.parts) {
- if (part.type === 'toolCallResponseJson' || part.type === 'toolCallErr') {
- ids.add(part.id);
- }
- }
- return ids;
- });
-
- const isCompleteSelector = createSelector(
- completedToolIds,
- (id: string, completed) => completed.has(id)
- );
-
- const responseById = createMemo(() => {
- const responseMap = new Map<
- string,
- Extract<AssistantMessagePart, { type: 'toolCallResponseJson' }>
- >();
-
- for (const part of props.parts) {
- if (part.type === 'toolCallResponseJson') {
- responseMap.set(part.id, part);
- }
- }
-
- return responseMap;
- });
-
- const parts = createMemo(() => {
- return props.parts.filter(
- (part) =>
- part.type !== 'toolCallResponseJson' && part.type !== 'toolCallErr'
- );
- });
-
- const isThinkingDone = createMemo(() => {
- if (!props.isStreaming) return true;
- const p = parts();
- return p.some((part) => part.type !== 'thinking');
- });
-
- const keyedParts = createMemo(() => {
- const counts = new Map<AssistantMessagePart['type'], number>();
- const partsByKey = new Map<string, AssistantMessagePart>();
- const orderedKeys: string[] = [];
-
- for (const part of parts()) {
- const key = getAssistantPartKey(part, counts);
- orderedKeys.push(key);
- partsByKey.set(key, part);
- }
-
- return { orderedKeys, partsByKey };
- });
-
- type ToolGroupEntry = {
- key: string;
- part: Extract<AssistantMessagePart, { type: 'toolCall' | 'mcpToolCall' }>;
- index: number;
- };
- type RenderItem =
- | {
- type: 'toolGroup';
- key: string;
- entries: ToolGroupEntry[];
- }
- | {
- type: 'part';
- key: string;
- part: AssistantMessagePart;
- index: number;
- };
-
- const groupedParts = createMemo(() => {
- const itemByKey = new Map<string, RenderItem>();
- const orderedKeys: string[] = [];
- let pendingToolEntries: ToolGroupEntry[] = [];
-
- const flushToolGroup = () => {
- if (pendingToolEntries.length === 0) return;
- const key = `toolGroup:${pendingToolEntries[0].key}`;
- orderedKeys.push(key);
- itemByKey.set(key, {
- type: 'toolGroup',
- key,
- entries: pendingToolEntries,
- });
- pendingToolEntries = [];
- };
-
- keyedParts().orderedKeys.forEach((key, index) => {
- const part = keyedParts().partsByKey.get(key);
- if (!part) return;
-
- if (part.type === 'toolCall' || part.type === 'mcpToolCall') {
- pendingToolEntries.push({ key, part, index });
- return;
- }
-
- flushToolGroup();
- orderedKeys.push(key);
- itemByKey.set(key, {
- type: 'part',
- key,
- part,
- index,
- });
- });
-
- flushToolGroup();
- return { orderedKeys, itemByKey };
- });
-
- const stableRenderItems = mapArray(
- () => groupedParts().orderedKeys,
- (key) => createMemo(() => groupedParts().itemByKey.get(key))
- );
-
- const renderToolPart = (
- toolPart: Extract<
- AssistantMessagePart,
- { type: 'toolCall' | 'mcpToolCall' }
- >,
- index: number,
- grouped: boolean
- ) => {
- if (toolPart.type === 'toolCall') {
- return (
- <RenderTool
- tool_id={toolPart.id}
- chat_id={chat.chatId()}
- json={toolPart.json}
- name={toolPart.name}
- response={responseById().get(toolPart.id)}
- message_id={props.message.id}
- part_index={index}
- isComplete={isCompleteSelector(toolPart.id)}
- renderContext={{
- renderContext: {
- isStreaming: props.isStreaming,
- grouped,
- },
- }}
- />
- );
- }
-
- return (
- <McpToolCall
- name={toolPart.name}
- service={toolPart.service}
- display_name={toolPart.display_name ?? undefined}
- isComplete={isCompleteSelector(toolPart.id)}
- renderContext={{
- renderContext: {
- isStreaming: props.isStreaming,
- grouped,
- },
- }}
- />
- );
- };
-
- return (
- <div class="flex flex-col gap-1">
- <For each={stableRenderItems()}>
- {(item) => {
- const currentItem = () => item();
- if (!currentItem()) return null;
-
- const type = () => currentItem()?.type;
-
- return (
- <Switch>
- <Match when={type() === 'toolGroup'}>
- {(() => {
- const toolGroup = () =>
- currentItem() as Extract<RenderItem, { type: 'toolGroup' }>;
- const isGrouped = () => toolGroup().entries.length > 1;
- const singleEntry = () => toolGroup().entries[0];
- return (
- <Show
- when={isGrouped()}
- fallback={renderToolPart(
- singleEntry().part,
- singleEntry().index,
- false
- )}
- >
- <Tool.Group>
- <For each={toolGroup().entries}>
- {(entry) =>
- renderToolPart(entry.part, entry.index, true)
- }
- </For>
- </Tool.Group>
- </Show>
- );
- })()}
- </Match>
- <Match when={type() === 'part'}>
- {(() => {
- const partItem = () =>
- currentItem() as Extract<RenderItem, { type: 'part' }>;
- const part = () => partItem().part;
- return (
- <Switch>
- <Match when={part().type === 'text'}>
- {(() => {
- const text = () => {
- const p = part();
- return p.type === 'text' ? p.text : '';
- };
- return (
- <Show when={text().trim().length > 0}>
- <ChatMessageMarkdown
- text={text()}
- generating={() => props.isStreaming}
- />
- </Show>
- );
- })()}
- </Match>
- <Match when={part().type === 'thinking'}>
- {(() => {
- const thinking = () => {
- const p = part();
- return p.type === 'thinking' ? p.thinking : '';
- };
- return (
- <Show when={thinking().trim().length > 0}>
- <ThinkingBlock
- thinking={thinking()}
- isStreaming={!isThinkingDone()}
- />
- </Show>
- );
- })()}
- </Match>
- </Switch>
- );
- })()}
- </Match>
- </Switch>
- );
- }}
- </For>
- </div>
- );
-}
diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessageParts.test.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessageParts.test.tsx
new file mode 100644
index 0000000000..7fb4ed5f35
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/message/AssistantMessageParts.test.tsx
@@ -0,0 +1,245 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { asChatMessage } from '@core/component/AI/util/message';
+import type { ChatStream } from '@service-cognition/generated/schemas';
+import type { AssistantMessagePart } from '@service-cognition/generated/schemas/assistantMessagePart';
+import { render, waitFor } from '@solidjs/testing-library';
+import { createMemo, createRoot, createSignal, type JSX, Show } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { AssistantMessageParts } from './AssistantMessageParts';
+
+const lifecycle = vi.hoisted(() => ({
+ markdownCleanups: 0,
+ markdownMounts: 0,
+ mcpCleanups: new Map<string, number>(),
+ mcpMounts: new Map<string, number>(),
+ thinkingCleanups: 0,
+ thinkingMounts: 0,
+ toolCleanups: new Map<string, number>(),
+ toolMounts: new Map<string, number>(),
+}));
+
+vi.mock('@core/component/AI/context', () => ({
+ useChatContext: () => ({
+ chatId: () => 'chat-1',
+ }),
+}));
+
+vi.mock('@core/component/AI/component/tool/Tool', () => ({
+ Tool: {
+ Group: (props: { children: JSX.Element }) => (
+ <div data-testid="tool-group">{props.children}</div>
+ ),
+ },
+}));
+
+vi.mock(
+ '@core/component/AI/component/message/ChatMessageMarkdown',
+ async () => {
+ const solid = await vi.importActual<typeof import('solid-js')>('solid-js');
+
+ return {
+ ChatMessageMarkdown: (props: { text: string }) => {
+ solid.onMount(() => {
+ lifecycle.markdownMounts += 1;
+ });
+ solid.onCleanup(() => {
+ lifecycle.markdownCleanups += 1;
+ });
+ return <div data-testid="markdown">{props.text}</div>;
+ },
+ };
+ }
+);
+
+vi.mock('@core/component/AI/component/message/ThinkingBlock', async () => {
+ const solid = await vi.importActual<typeof import('solid-js')>('solid-js');
+
+ return {
+ ThinkingBlock: (props: { thinking: string; isStreaming: boolean }) => {
+ solid.onMount(() => {
+ lifecycle.thinkingMounts += 1;
+ });
+ solid.onCleanup(() => {
+ lifecycle.thinkingCleanups += 1;
+ });
+ return (
+ <div data-testid="thinking" data-streaming={String(props.isStreaming)}>
+ {props.thinking}
+ </div>
+ );
+ },
+ };
+});
+
+vi.mock('@core/component/AI/component/tool/handler', async () => {
+ const solid = await vi.importActual<typeof import('solid-js')>('solid-js');
+
+ return {
+ RenderTool: (props: { tool_id: string; isComplete: boolean }) => {
+ solid.onMount(() => {
+ lifecycle.toolMounts.set(
+ props.tool_id,
+ (lifecycle.toolMounts.get(props.tool_id) ?? 0) + 1
+ );
+ });
+ solid.onCleanup(() => {
+ lifecycle.toolCleanups.set(
+ props.tool_id,
+ (lifecycle.toolCleanups.get(props.tool_id) ?? 0) + 1
+ );
+ });
+ return (
+ <div data-complete={String(props.isComplete)} data-testid="tool">
+ {props.tool_id}
+ </div>
+ );
+ },
+ triggerToolCall: vi.fn(),
+ };
+});
+
+vi.mock('@core/component/AI/component/tool/McpToolCall', async () => {
+ const solid = await vi.importActual<typeof import('solid-js')>('solid-js');
+
+ return {
+ McpToolCall: (props: { name: string }) => {
+ solid.onMount(() => {
+ lifecycle.mcpMounts.set(
+ props.name,
+ (lifecycle.mcpMounts.get(props.name) ?? 0) + 1
+ );
+ });
+ solid.onCleanup(() => {
+ lifecycle.mcpCleanups.set(
+ props.name,
+ (lifecycle.mcpCleanups.get(props.name) ?? 0) + 1
+ );
+ });
+ return <div data-testid="mcp-tool">{props.name}</div>;
+ },
+ };
+});
+
+function response(
+ content: Extract<ChatStream, { type: 'chat_message_response' }>['content']
+): ChatStream {
+ return {
+ chat_id: 'chat-1',
+ content,
+ message_id: 'message-1',
+ stream_id: 'message-1',
+ type: 'chat_message_response',
+ };
+}
+
+function StreamedAssistantParts(props: { data: () => ChatStream[] }) {
+ const message = createMemo(() => asChatMessage(props.data()));
+
+ return (
+ <Show when={message()}>
+ {(msg) => (
+ <AssistantMessageParts
+ parts={msg().content as AssistantMessagePart[]}
+ message={msg()}
+ isStreaming
+ />
+ )}
+ </Show>
+ );
+}
+
+describe('AssistantMessageParts streaming identity', () => {
+ beforeEach(() => {
+ lifecycle.markdownCleanups = 0;
+ lifecycle.markdownMounts = 0;
+ lifecycle.mcpCleanups.clear();
+ lifecycle.mcpMounts.clear();
+ lifecycle.thinkingCleanups = 0;
+ lifecycle.thinkingMounts = 0;
+ lifecycle.toolCleanups.clear();
+ lifecycle.toolMounts.clear();
+ });
+
+ it('keeps mixed streamed parts mounted as later chunks arrive', async () => {
+ let append!: (item: ChatStream) => void;
+ let disposeStream!: () => void;
+ const data = createRoot((dispose) => {
+ disposeStream = dispose;
+ const [items, setItems] = createSignal<ChatStream[]>([]);
+ append = (item) => setItems((prev) => [...prev, item]);
+ return items;
+ });
+
+ render(() => <StreamedAssistantParts data={data} />);
+
+ append(response({ thinking: 'Need', type: 'thinking' }));
+ await waitFor(() => expect(lifecycle.thinkingMounts).toBe(1));
+
+ append(response({ thinking: ' context', type: 'thinking' }));
+ await waitFor(() => {
+ expect(lifecycle.thinkingMounts).toBe(1);
+ expect(lifecycle.thinkingCleanups).toBe(0);
+ });
+
+ append(
+ response({
+ id: 'tool-1',
+ json: { channelId: 'channel-1' },
+ name: 'ReadChannelMessages',
+ type: 'toolCall',
+ })
+ );
+ await waitFor(() => expect(lifecycle.toolMounts.get('tool-1')).toBe(1));
+ expect(lifecycle.thinkingMounts).toBe(1);
+ expect(lifecycle.thinkingCleanups).toBe(0);
+
+ append(
+ response({
+ id: 'tool-1',
+ json: { messages: [] },
+ name: 'ReadChannelMessages',
+ type: 'toolCallResponseJson',
+ })
+ );
+ await waitFor(() => {
+ expect(lifecycle.toolMounts.get('tool-1')).toBe(1);
+ expect(lifecycle.toolCleanups.get('tool-1') ?? 0).toBe(0);
+ });
+
+ append(
+ response({
+ display_name: 'Search issues',
+ id: 'mcp-1',
+ json: { query: 'streaming' },
+ name: 'search',
+ service: 'linear',
+ type: 'mcpToolCall',
+ })
+ );
+ await waitFor(() => expect(lifecycle.mcpMounts.get('search')).toBe(1));
+ expect(lifecycle.toolMounts.get('tool-1')).toBe(1);
+ expect(lifecycle.toolCleanups.get('tool-1') ?? 0).toBe(0);
+
+ append(response({ text: 'Done', type: 'text' }));
+ await waitFor(() => expect(lifecycle.markdownMounts).toBe(1));
+ expect(lifecycle.mcpMounts.get('search')).toBe(1);
+ expect(lifecycle.mcpCleanups.get('search') ?? 0).toBe(0);
+
+ append(response({ text: '.', type: 'text' }));
+ await waitFor(() => {
+ expect(lifecycle.markdownMounts).toBe(1);
+ expect(lifecycle.markdownCleanups).toBe(0);
+ });
+
+ expect(lifecycle.thinkingMounts).toBe(1);
+ expect(lifecycle.thinkingCleanups).toBe(0);
+ expect(lifecycle.toolMounts.get('tool-1')).toBe(1);
+ expect(lifecycle.toolCleanups.get('tool-1') ?? 0).toBe(0);
+ expect(lifecycle.mcpMounts.get('search')).toBe(1);
+ expect(lifecycle.mcpCleanups.get('search') ?? 0).toBe(0);
+ disposeStream();
+ });
+});
diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessageParts.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessageParts.tsx
new file mode 100644
index 0000000000..473aaaf5bf
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/message/AssistantMessageParts.tsx
@@ -0,0 +1,312 @@
+import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';
+import { ThinkingBlock } from '@core/component/AI/component/message/ThinkingBlock';
+import { RenderTool } from '@core/component/AI/component/tool/handler';
+import { McpToolCall } from '@core/component/AI/component/tool/McpToolCall';
+import { Tool } from '@core/component/AI/component/tool/Tool';
+import { useChatContext } from '@core/component/AI/context';
+import type { AssistantMessagePart } from '@service-cognition/generated/schemas/assistantMessagePart';
+import type { ChatMessageWithAttachments } from '@service-cognition/generated/schemas/chatMessageWithAttachments';
+import {
+ type Accessor,
+ createMemo,
+ createSelector,
+ Match,
+ mapArray,
+ Show,
+ Switch,
+} from 'solid-js';
+
+function getAssistantPartKey(
+ part: AssistantMessagePart,
+ counts: Map<AssistantMessagePart['type'], number>
+): string {
+ if (
+ part.type === 'toolCall' ||
+ part.type === 'toolCallErr' ||
+ part.type === 'mcpToolCall'
+ ) {
+ return `${part.type}:${part.id}`;
+ }
+
+ const count = counts.get(part.type) ?? 0;
+ counts.set(part.type, count + 1);
+ return `${part.type}:${count}`;
+}
+
+type ToolGroupEntry = {
+ key: string;
+ part: Extract<AssistantMessagePart, { type: 'toolCall' | 'mcpToolCall' }>;
+ index: number;
+};
+
+type RenderItem =
+ | {
+ type: 'toolGroup';
+ key: string;
+ entries: ToolGroupEntry[];
+ }
+ | {
+ type: 'part';
+ key: string;
+ part: AssistantMessagePart;
+ index: number;
+ };
+
+export function AssistantMessageParts(props: {
+ parts: AssistantMessagePart[];
+ message: ChatMessageWithAttachments;
+ isStreaming: boolean;
+}) {
+ const outer = props;
+ const chat = useChatContext();
+ const completedToolIds = createMemo(() => {
+ const ids = new Set<string>();
+ for (const part of props.parts) {
+ if (part.type === 'toolCallResponseJson' || part.type === 'toolCallErr') {
+ ids.add(part.id);
+ }
+ }
+ return ids;
+ });
+
+ const isCompleteSelector = createSelector(
+ completedToolIds,
+ (id: string, completed) => completed.has(id)
+ );
+
+ const responseById = createMemo(() => {
+ const responseMap = new Map<
+ string,
+ Extract<AssistantMessagePart, { type: 'toolCallResponseJson' }>
+ >();
+
+ for (const part of props.parts) {
+ if (part.type === 'toolCallResponseJson') {
+ responseMap.set(part.id, part);
+ }
+ }
+
+ return responseMap;
+ });
+
+ const parts = createMemo(() => {
+ return props.parts.filter(
+ (part) =>
+ part.type !== 'toolCallResponseJson' && part.type !== 'toolCallErr'
+ );
+ });
+
+ const isThinkingDone = createMemo(() => {
+ if (!props.isStreaming) return true;
+ const p = parts();
+ return p.some((part) => part.type !== 'thinking');
+ });
+
+ const keyedParts = createMemo(() => {
+ const counts = new Map<AssistantMessagePart['type'], number>();
+ const partsByKey = new Map<string, AssistantMessagePart>();
+ const orderedKeys: string[] = [];
+
+ for (const part of parts()) {
+ const key = getAssistantPartKey(part, counts);
+ orderedKeys.push(key);
+ partsByKey.set(key, part);
+ }
+
+ return { orderedKeys, partsByKey };
+ });
+
+ const groupedParts = createMemo(() => {
+ const itemByKey = new Map<string, RenderItem>();
+ const orderedKeys: string[] = [];
+ let pendingToolEntries: ToolGroupEntry[] = [];
+
+ const flushToolGroup = () => {
+ if (pendingToolEntries.length === 0) return;
+ const key = `toolGroup:${pendingToolEntries[0].key}`;
+ orderedKeys.push(key);
+ itemByKey.set(key, {
+ type: 'toolGroup',
+ key,
+ entries: pendingToolEntries,
+ });
+ pendingToolEntries = [];
+ };
+
+ keyedParts().orderedKeys.forEach((key, index) => {
+ const part = keyedParts().partsByKey.get(key);
+ if (!part) return;
+
+ if (part.type === 'toolCall' || part.type === 'mcpToolCall') {
+ pendingToolEntries.push({ key, part, index });
+ return;
+ }
+
+ flushToolGroup();
+ orderedKeys.push(key);
+ itemByKey.set(key, {
+ type: 'part',
+ key,
+ part,
+ index,
+ });
+ });
+
+ flushToolGroup();
+ return { orderedKeys, itemByKey };
+ });
+
+ const stableRenderItems = mapArray(
+ () => groupedParts().orderedKeys,
+ (key) => {
+ const item = createMemo(() => groupedParts().itemByKey.get(key));
+ return <RenderItemView item={item} />;
+ }
+ );
+
+ function ToolEntry(props: { entry: Accessor<ToolGroupEntry> }) {
+ const toolPart = () => props.entry().part;
+
+ return (
+ <Switch>
+ <Match when={toolPart().type === 'toolCall'}>
+ {(() => {
+ const part = () =>
+ toolPart() as Extract<AssistantMessagePart, { type: 'toolCall' }>;
+
+ return (
+ <RenderTool
+ tool_id={part().id}
+ chat_id={chat.chatId()}
+ json={part().json}
+ name={part().name}
+ response={responseById().get(part().id)}
+ message_id={outer.message.id}
+ part_index={props.entry().index}
+ isComplete={isCompleteSelector(part().id)}
+ renderContext={{
+ renderContext: {
+ isStreaming: outer.isStreaming,
+ grouped: true,
+ },
+ }}
+ />
+ );
+ })()}
+ </Match>
+ <Match when={toolPart().type === 'mcpToolCall'}>
+ {(() => {
+ const part = () =>
+ toolPart() as Extract<
+ AssistantMessagePart,
+ { type: 'mcpToolCall' }
+ >;
+
+ return (
+ <McpToolCall
+ name={part().name}
+ service={part().service}
+ display_name={part().display_name ?? undefined}
+ isComplete={isCompleteSelector(part().id)}
+ renderContext={{
+ renderContext: {
+ isStreaming: outer.isStreaming,
+ grouped: true,
+ },
+ }}
+ />
+ );
+ })()}
+ </Match>
+ </Switch>
+ );
+ }
+
+ function ToolGroupView(props: {
+ item: Accessor<Extract<RenderItem, { type: 'toolGroup' }>>;
+ }) {
+ const entriesByKey = createMemo(() => {
+ const map = new Map<string, ToolGroupEntry>();
+ for (const entry of props.item().entries) {
+ map.set(entry.key, entry);
+ }
+ return map;
+ });
+
+ const entries = mapArray(
+ () => props.item().entries.map((entry) => entry.key),
+ (key) => {
+ const entry = createMemo(() => entriesByKey().get(key)!);
+ return <ToolEntry entry={entry} />;
+ }
+ );
+
+ return <Tool.Group>{entries()}</Tool.Group>;
+ }
+
+ function PartView(props: {
+ item: Accessor<Extract<RenderItem, { type: 'part' }>>;
+ }) {
+ const part = () => props.item().part;
+
+ return (
+ <Switch>
+ <Match when={part().type === 'text'}>
+ {(() => {
+ const text = () => {
+ const p = part();
+ return p.type === 'text' ? p.text : '';
+ };
+ return (
+ <Show when={text().trim().length > 0}>
+ <ChatMessageMarkdown
+ text={text()}
+ generating={() => outer.isStreaming}
+ />
+ </Show>
+ );
+ })()}
+ </Match>
+ <Match when={part().type === 'thinking'}>
+ {(() => {
+ const thinking = () => {
+ const p = part();
+ return p.type === 'thinking' ? p.thinking : '';
+ };
+ return (
+ <Show when={thinking().trim().length > 0}>
+ <ThinkingBlock
+ thinking={thinking()}
+ isStreaming={!isThinkingDone()}
+ />
+ </Show>
+ );
+ })()}
+ </Match>
+ </Switch>
+ );
+ }
+
+ function RenderItemView(props: { item: Accessor<RenderItem | undefined> }) {
+ const type = () => props.item()?.type;
+
+ return (
+ <Switch>
+ <Match when={type() === 'toolGroup'}>
+ <ToolGroupView
+ item={
+ props.item as Accessor<Extract<RenderItem, { type: 'toolGroup' }>>
+ }
+ />
+ </Match>
+ <Match when={type() === 'part'}>
+ <PartView
+ item={props.item as Accessor<Extract<RenderItem, { type: 'part' }>>}
+ />
+ </Match>
+ </Switch>
+ );
+ }
+
+ return <div class="flex flex-col gap-1">{stableRenderItems()}</div>;
+}