Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(web-studio): standardize streamed event rendering (#3517)

yufengc67222c3d46d
diff --git a/bot/tests/test_openapi_auth.py b/bot/tests/test_openapi_auth.py
index a90e4d6f6..6f154f63c 100644
--- a/bot/tests/test_openapi_auth.py
+++ b/bot/tests/test_openapi_auth.py
@@ -1116,6 +1116,56 @@ class TestOpenAPIAuth:
assert pending.events[0]["type"] == "response"
assert pending.events[0]["data"] == {"content": "hello", "response_id": "resp-123"}
+ @pytest.mark.asyncio
+ async def test_send_forwards_iteration_to_bot_stream(self, message_bus, temp_workspace):
+ channel = OpenAPIChannel(
+ OpenAPIChannelConfig(),
+ message_bus,
+ workspace_path=temp_workspace,
+ )
+ pending = PendingResponse()
+ channel._bot_pending["default"] = {"session-1": pending}
+
+ await channel.send(
+ OutboundMessage(
+ session_key=SessionKey(
+ type="bot_api",
+ channel_id="default",
+ chat_id="session-1",
+ ),
+ content="Iteration 2/10",
+ event_type=OutboundEventType.ITERATION,
+ )
+ )
+
+ assert pending.events[0]["type"] == "iteration"
+ assert pending.events[0]["data"] == "Iteration 2/10"
+
+ @pytest.mark.asyncio
+ async def test_send_forwards_iteration_to_openapi_stream(self, message_bus, temp_workspace):
+ channel = OpenAPIChannel(
+ OpenAPIChannelConfig(),
+ message_bus,
+ workspace_path=temp_workspace,
+ )
+ pending = PendingResponse()
+ channel._pending["session-1"] = pending
+
+ await channel.send(
+ OutboundMessage(
+ session_key=SessionKey(
+ type="cli",
+ channel_id="default",
+ chat_id="session-1",
+ ),
+ content="Iteration 2/10",
+ event_type=OutboundEventType.ITERATION,
+ )
+ )
+
+ assert pending.events[0]["type"] == "iteration"
+ assert pending.events[0]["data"] == "Iteration 2/10"
+
def test_feedback_requires_existing_response(self, message_bus, temp_workspace):
channel = OpenAPIChannel(
OpenAPIChannelConfig(),
diff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.py
index 3c54cc3b7..53b0e7db5 100644
--- a/bot/vikingbot/channels/openapi.py
+++ b/bot/vikingbot/channels/openapi.py
@@ -264,6 +264,8 @@ class OpenAPIChannel(BaseChannel):
await pending.add_event("tool_call", msg.content)
elif msg.event_type == OutboundEventType.TOOL_RESULT:
await pending.add_event("tool_result", msg.content)
+ elif msg.event_type == OutboundEventType.ITERATION:
+ await pending.add_event("iteration", msg.content)
return
# Handle as normal OpenAPIChannel message
@@ -295,6 +297,8 @@ class OpenAPIChannel(BaseChannel):
await pending.add_event("tool_call", msg.content)
elif msg.event_type == OutboundEventType.TOOL_RESULT:
await pending.add_event("tool_result", msg.content)
+ elif msg.event_type == OutboundEventType.ITERATION:
+ await pending.add_event("iteration", msg.content)
def get_router(self) -> APIRouter:
"""Get or create the FastAPI router."""
diff --git a/openviking/server/routers/bot.py b/openviking/server/routers/bot.py
index 4eda08dad..2646fae99 100644
--- a/openviking/server/routers/bot.py
+++ b/openviking/server/routers/bot.py
@@ -313,10 +313,8 @@ async def chat_stream(
response.raise_for_status()
# Stream the response content
- async for line in response.aiter_lines():
- if line:
- # Forward the SSE line as-is
- yield f"{line}\n"
+ async for chunk in response.aiter_text():
+ yield chunk
except httpx.RequestError as e:
logger.error(f"Failed to connect to bot service: {e}")
error_event = {
diff --git a/tests/server/test_bot_proxy_auth.py b/tests/server/test_bot_proxy_auth.py
index 553517c59..062684b27 100644
--- a/tests/server/test_bot_proxy_auth.py
+++ b/tests/server/test_bot_proxy_auth.py
@@ -219,3 +219,55 @@ async def test_chat_proxy_forwards_trusted_request_without_root_api_key(monkeypa
}
assert "X-Gateway-Token" not in forwarded["headers"]
assert forwarded["timeout"] == 300.0
+
+
+async def test_chat_stream_proxy_preserves_sse_event_boundaries(monkeypatch):
+ payload = (
+ 'data: {"event":"reasoning_delta","data":"thinking"}\n\n'
+ 'data: {"event":"response","data":{"content":"done"}}\n\n'
+ )
+
+ class FakeResponse:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return None
+
+ def raise_for_status(self):
+ return None
+
+ async def aiter_text(self):
+ yield payload[:30]
+ yield payload[30:]
+
+ class FakeClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return None
+
+ def stream(self, *args, **kwargs):
+ return FakeResponse()
+
+ monkeypatch.setattr(bot_router_module, "BOT_API_URL", "http://127.0.0.1:18790")
+ monkeypatch.setattr(bot_router_module, "_create_bot_proxy_client", lambda: FakeClient())
+
+ app = FastAPI()
+ app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)
+ app.state.auth_plugin = DevAuthPlugin()
+ app.include_router(bot_router_module.router, prefix="/bot/v1")
+
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app),
+ base_url="http://testserver",
+ ) as client:
+ response = await client.post(
+ "/bot/v1/chat/stream",
+ json={"message": "hello"},
+ )
+
+ assert response.status_code == 200
+ assert response.text == payload
diff --git a/web-studio/package-lock.json b/web-studio/package-lock.json
index 38f4ff404..75a302a12 100644
--- a/web-studio/package-lock.json
+++ b/web-studio/package-lock.json
@@ -28,6 +28,7 @@
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.42.1",
"@fontsource-variable/noto-sans": "^5.2.10",
+ "@microsoft/fetch-event-source": "^2.0.1",
"@streamdown/cjk": "^1.0.3",
"@streamdown/code": "^1.1.1",
"@tailwindcss/vite": "^4.1.18",
@@ -2547,6 +2548,12 @@
"langium": "^4.0.0"
}
},
+ "node_modules/@microsoft/fetch-event-source": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@microsoft/fetch-event-source/-/fetch-event-source-2.0.1.tgz",
+ "integrity": "sha512-W6CLUJ2eBMw3Rec70qrsEW0jOm/3twwJv21mrmj2yORiaVmVYGS4sSS5yUwvQc1ZlDLYGPnClVWmUUMagKNsfA==",
+ "license": "MIT"
+ },
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.29.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
diff --git a/web-studio/package.json b/web-studio/package.json
index 8b33c5957..a258d9e55 100644
--- a/web-studio/package.json
+++ b/web-studio/package.json
@@ -38,6 +38,7 @@
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.42.1",
"@fontsource-variable/noto-sans": "^5.2.10",
+ "@microsoft/fetch-event-source": "^2.0.1",
"@streamdown/cjk": "^1.0.3",
"@streamdown/code": "^1.1.1",
"@tailwindcss/vite": "^4.1.18",
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index db547e4bf..2cf72bb1f 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -297,7 +297,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
defaultOpen
className="flex h-svh overflow-hidden bg-sidebar"
>
- <Sidebar variant="sidebar" collapsible="icon" className="!border-r-0">
+ <Sidebar variant="sidebar" collapsible="icon">
<SidebarHeader className="h-12 border-b border-sidebar-border/70 px-2 py-0">
<div className="flex h-full items-center justify-between gap-2 group-data-[collapsible=icon]:justify-center">
<div className="min-w-0 flex-1 group-data-[collapsible=icon]:hidden">
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index 1cacce22e..b9434af84 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -1007,6 +1007,8 @@ const en = {
update: 'Updated',
delete: 'Deleted',
},
+ allTypes: 'All',
+ filterByType: 'Filter by memory type',
before: 'Before',
after: 'After',
addedContent: 'Added content',
@@ -1113,7 +1115,6 @@ const en = {
},
},
agent: {
- autoRetrieve: 'The Agent retrieves on its own from messages and tools',
history: 'Session history',
newSession: 'New session',
creating: 'Creating Playground session...',
@@ -1147,6 +1148,12 @@ const en = {
},
},
terminal: {
+ header: 'Terminal',
+ history: 'Command history',
+ historyTitle: 'Command history',
+ historyDescription: 'Review commands run in this browser.',
+ clearHistory: 'Clear command history',
+ noHistory: 'No command history',
welcomeTitle: 'Terminal connected to the context tree',
welcomeBody:
'Run /status, /ls, /search, /read, /add-resource. /search is global by default; add --scope . to use the current directory, or --scope viking://resources/... to limit it to a directory.',
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 25203867b..c3ab0daa8 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -973,6 +973,8 @@ const zhCN = {
update: '更新',
delete: '删除',
},
+ allTypes: '全部',
+ filterByType: '按记忆分类筛选',
before: '变更前',
after: '变更后',
addedContent: '新增内容',
@@ -1072,7 +1074,6 @@ const zhCN = {
},
},
agent: {
- autoRetrieve: 'Agent 会根据消息和工具自主检索',
history: '历史会话',
newSession: '新建会话',
creating: '正在创建 Playground 会话...',
@@ -1105,6 +1106,12 @@ const zhCN = {
},
},
terminal: {
+ header: '终端',
+ history: '命令历史',
+ historyTitle: '命令历史',
+ historyDescription: '查看当前浏览器中执行过的命令。',
+ clearHistory: '清空命令历史',
+ noHistory: '暂无命令历史',
welcomeTitle: 'Terminal 已连接上下文目录',
welcomeBody:
'可执行 /status、/ls、/search、/read、/add-resource。/search 默认全局检索,可通过 --scope . 使用当前目录,或通过 --scope viking://resources/... 指定目录。',
diff --git a/web-studio/src/lib/sessions/api.test.ts b/web-studio/src/lib/sessions/api.test.ts
index 7f634e3a6..02a7029f5 100644
--- a/web-studio/src/lib/sessions/api.test.ts
+++ b/web-studio/src/lib/sessions/api.test.ts
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { OvClientError } from '#/lib/ov-client'
-import { fetchSessionMessages } from './api'
+import { fetchSessionMessages, serializeParts } from './api'
const {
getSessionBySessionIdMock,
@@ -121,3 +121,38 @@ describe('fetchSessionMessages', () => {
)
})
})
+
+describe('serializeParts', () => {
+ it('keeps persisted content order while filtering timeline-only events', () => {
+ expect(
+ serializeParts([
+ { type: 'iteration', iteration: 1 },
+ { type: 'reasoning', reasoning: 'thinking' },
+ {
+ type: 'tool',
+ tool_id: 'tool-1',
+ tool_name: 'search',
+ tool_uri: '',
+ skill_uri: '',
+ tool_status: 'completed',
+ tool_output: 'result',
+ },
+ {
+ type: 'tool_result',
+ tool_id: 'tool-1',
+ tool_name: 'search',
+ tool_output: 'result',
+ is_error: false,
+ },
+ { type: 'text', text: 'done' },
+ ]),
+ ).toEqual([
+ expect.objectContaining({
+ type: 'tool',
+ tool_id: 'tool-1',
+ tool_output: 'result',
+ }),
+ { type: 'text', text: 'done' },
+ ])
+ })
+})
diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.ts
index b84cbae79..8cfebccf1 100644
--- a/web-studio/src/lib/sessions/api.ts
+++ b/web-studio/src/lib/sessions/api.ts
@@ -18,6 +18,7 @@ import {
OvClientError,
ovClient,
} from '#/lib/ov-client'
+import { fetchSse } from '#/lib/sse'
import { parseSessionMemoryDiff } from './memory-diff'
import type { BotChatRequest, BotChatResponse } from '@ov-server/bot/v1/chat'
@@ -416,18 +417,20 @@ export async function fetchBotHealth(): Promise<unknown> {
}
/**
- * Send a streaming chat request. Returns the raw Response for SSE parsing.
- * Use parseSseStream() from ./sse.ts to iterate over events.
+ * Send a streaming chat request and return standards-compliant SSE messages.
*/
export async function sendChatStream(
request: BotChatRequest,
signal?: AbortSignal,
-): Promise<Response> {
+): Promise<ReturnType<typeof fetchSse>> {
const baseUrl = ovClient.getOptions().baseUrl
const conn = ovClient.getConnection()
- const response = await fetch(`${baseUrl}/bot/v1/chat/stream`, {
+ return fetchSse(`${baseUrl}/bot/v1/chat/stream`, {
method: 'POST',
- headers: buildFetchHeaders(),
+ headers: {
+ ...buildFetchHeaders(),
+ Accept: 'text/event-stream',
+ },
body: JSON.stringify({
...request,
user_id: request.user_id || conn.userId || undefined,
@@ -435,15 +438,6 @@ export async function sendChatStream(
}),
signal,
})
-
- if (!response.ok) {
- const text = await response.text().catch(() => '')
- throw normalizeOvClientError(
- new Error(`Chat stream request failed (${response.status}): ${text}`),
- )
- }
-
- return response
}
/** Send a non-streaming chat request. */
@@ -469,18 +463,27 @@ export async function sendChat(
export function serializeParts(
parts: MessagePart[],
): Array<Record<string, unknown>> {
- return parts.map((part) => {
+ return parts.flatMap((part) => {
if (part.type === 'text') {
- return { type: 'text', text: part.text }
+ return [{ type: 'text', text: part.text }]
}
if (part.type === 'context') {
- return {
- type: 'context',
- uri: part.uri,
- context_type: part.context_type,
- abstract: part.abstract,
- }
+ return [
+ {
+ type: 'context',
+ uri: part.uri,
+ context_type: part.context_type,
+ abstract: part.abstract,
+ },
+ ]
}
+ if (
+ part.type === 'reasoning' ||
+ part.type === 'iteration' ||
+ part.type === 'tool_result'
+ )
+ return []
+
// tool
const d: Record<string, unknown> = {
type: 'tool',
@@ -496,6 +499,6 @@ export function serializeParts(
if (part.prompt_tokens != null) d.prompt_tokens = part.prompt_tokens
if (part.completion_tokens != null)
d.completion_tokens = part.completion_tokens
- return d
+ return [d]
})
}
diff --git a/web-studio/src/lib/sessions/sse.ts b/web-studio/src/lib/sessions/sse.ts
index 9ba246ad6..56da258e5 100644
--- a/web-studio/src/lib/sessions/sse.ts
+++ b/web-studio/src/lib/sessions/sse.ts
@@ -2,6 +2,7 @@ import type {
ChatStreamEvent,
ChatStreamEventType,
} from '@ov-server/bot/v1/chat'
+import type { SseMessage } from '#/lib/sse'
const VALID_EVENT_TYPES = new Set<string>([
'response',
@@ -40,15 +41,9 @@ export function streamEventDataToText(data: unknown): string {
}
}
-function parseSseLine(line: string): ChatStreamEvent | null {
- const trimmed = line.trim()
- if (!trimmed || !trimmed.startsWith('data:')) return null
-
- const jsonStr = trimmed.slice(5).trim()
- if (!jsonStr) return null
-
+function parseSseMessage(message: SseMessage): ChatStreamEvent | null {
try {
- const parsed = JSON.parse(jsonStr) as Record<string, unknown>
+ const parsed = JSON.parse(message.data) as Record<string, unknown>
if (
typeof parsed.event !== 'string' ||
!VALID_EVENT_TYPES.has(parsed.event)
@@ -69,53 +64,18 @@ function parseSseLine(line: string): ChatStreamEvent | null {
}
/**
- * Parse an SSE response body into an async generator of ChatStreamEvents.
+ * Validate standard SSE messages as chat protocol events.
*
* Backend format (from openapi.py):
* data: {"event":"response","data":"...","timestamp":"..."}\n\n
*
- * All events use `data:` prefix. Event type is inside the JSON payload.
- * The OpenViking bot proxy currently forwards non-empty SSE lines, so the
- * browser may receive `data:` lines without the blank separator. Parse each
- * complete data line immediately to keep the chat UI live during streaming.
+ * Event type is inside the JSON payload.
*/
export async function* parseSseStream(
- response: Response,
+ messages: AsyncIterable<SseMessage>,
): AsyncGenerator<ChatStreamEvent> {
- const body = response.body
- if (!body) return
-
- const reader = body.getReader()
- const decoder = new TextDecoder()
- let buffer = ''
-
- try {
- for (;;) {
- const { done, value } = await reader.read()
- if (done) break
-
- buffer += decoder.decode(value, { stream: true })
-
- let newlineIndex = buffer.indexOf('\n')
- while (newlineIndex >= 0) {
- const line = buffer.slice(0, newlineIndex)
- buffer = buffer.slice(newlineIndex + 1)
-
- const event = parseSseLine(line)
- if (event) yield event
-
- newlineIndex = buffer.indexOf('\n')
- }
- }
-
- // Process any remaining buffer
- if (buffer.trim()) {
- for (const line of buffer.split('\n')) {
- const event = parseSseLine(line)
- if (event) yield event
- }
- }
- } finally {
- reader.releaseLock()
+ for await (const message of messages) {
+ const event = parseSseMessage(message)
+ if (event) yield event
}
}
diff --git a/web-studio/src/lib/sessions/types/message.ts b/web-studio/src/lib/sessions/types/message.ts
index 5496708f6..a14c188ad 100644
--- a/web-studio/src/lib/sessions/types/message.ts
+++ b/web-studio/src/lib/sessions/types/message.ts
@@ -11,6 +11,12 @@ export interface ReasoningPart {
is_running?: boolean
}
+/** Agent-loop iteration marker used by the event timeline UI. */
+export interface IterationPart {
+ type: 'iteration'
+ iteration: number
+}
+
/** Context reference part (memory / resource / skill). */
export interface ContextPart {
type: 'context'
@@ -34,7 +40,22 @@ export interface ToolPart {
completion_tokens?: number
}
-export type MessagePart = TextPart | ReasoningPart | ContextPart | ToolPart
+/** Tool result event kept separately to preserve SSE arrival order in the UI. */
+export interface ToolResultPart {
+ type: 'tool_result'
+ tool_id: string
+ tool_name: string
+ tool_output: string
+ is_error: boolean
+}
+
+export type MessagePart =
+ | TextPart
+ | ReasoningPart
+ | IterationPart
+ | ContextPart
+ | ToolPart
+ | ToolResultPart
/** A single message in a session (matches backend Message.to_dict()). */
export interface Message {
diff --git a/web-studio/src/lib/sessions/use-chat-timeline.test.tsx b/web-studio/src/lib/sessions/use-chat-timeline.test.tsx
new file mode 100644
index 000000000..ae17f28cc
--- /dev/null
+++ b/web-studio/src/lib/sessions/use-chat-timeline.test.tsx
@@ -0,0 +1,312 @@
+// @vitest-environment jsdom
+
+import { act, renderHook } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { fetchSse } from '#/lib/sse'
+import { useChat } from './use-chat'
+
+const { sendChatStreamMock } = vi.hoisted(() => ({
+ sendChatStreamMock: vi.fn(),
+}))
+
+vi.mock('./api', () => ({
+ addMessage: vi.fn(),
+ sendChatStream: sendChatStreamMock,
+ serializeParts: vi.fn(),
+}))
+
+vi.mock('./use-session-titles', () => ({
+ setSessionTitle: vi.fn(),
+}))
+
+vi.mock('../browser-crypto', () => ({
+ createBrowserId: vi.fn((prefix: string) => `${prefix}-id`),
+}))
+
+function streamResponse(
+ events: Array<{ event: string; data: unknown }>,
+): Response {
+ const payload = events
+ .map((event) => `data: ${JSON.stringify(event)}\n\n`)
+ .join('')
+ return new Response(payload, {
+ headers: { 'Content-Type': 'text/event-stream' },
+ })
+}
+
+function streamMessages(events: Array<{ event: string; data: unknown }>) {
+ return fetchSse('/stream', {
+ fetch: vi.fn().mockResolvedValue(streamResponse(events)),
+ })
+}
+
+describe('useChat event timeline', () => {
+ beforeEach(() => {
+ sendChatStreamMock.mockReset()
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ callback(0)
+ return 1
+ })
+ vi.stubGlobal('cancelAnimationFrame', vi.fn())
+ })
+
+ it('keeps grouped event blocks in SSE arrival order', async () => {
+ sendChatStreamMock.mockResolvedValue(
+ streamMessages([
+ { event: 'iteration', data: 'Iteration 1/10' },
+ { event: 'reasoning_delta', data: 'first reasoning' },
+ { event: 'content_delta', data: 'checking' },
+ { event: 'tool_call', data: 'search({})' },
+ { event: 'tool_result', data: '{"ok":true}' },
+ { event: 'iteration', data: 'Iteration 2/10' },
+ { event: 'reasoning', data: 'second reasoning' },
+ { event: 'content_delta', data: 'final' },
+ { event: 'response', data: { content: 'final' } },
+ ]),
+ )
+
+ const { result } = renderHook(() =>
+ useChat({
+ identityScopeKey: 'identity',
+ persistMessages: false,
+ sessionId: 'session-1',
+ }),
+ )
+
+ await act(async () => {
+ await result.current.send('hello')
+ })
+
+ expect(result.current.messages[1]?.parts.map((part) => part.type)).toEqual([
+ 'iteration',
+ 'reasoning',
+ 'text',
+ 'tool',
+ 'tool_result',
+ 'iteration',
+ 'reasoning',
+ 'text',
+ ])
+ expect(result.current.messages[1]?.parts[3]).toMatchObject({
+ tool_name: 'search',
+ tool_output: '{"ok":true}',
+ tool_status: 'completed',
+ })
+ expect(result.current.messages[1]?.parts[4]).toMatchObject({
+ tool_name: 'search',
+ tool_output: '{"ok":true}',
+ type: 'tool_result',
+ })
+ expect(
+ result.current.messages[1]?.parts
+ .filter((part) => part.type === 'reasoning')
+ .map((part) => part.is_running),
+ ).toEqual([false, false])
+ })
+
+ it('keeps only the latest reasoning block running', async () => {
+ let controller!: ReadableStreamDefaultController<Uint8Array>
+ const encoder = new TextEncoder()
+ sendChatStreamMock.mockResolvedValue(
+ fetchSse('/stream', {
+ fetch: vi.fn().mockResolvedValue(
+ new Response(
+ new ReadableStream<Uint8Array>({
+ start(streamController) {
+ controller = streamController
+ },
+ }),
+ { headers: { 'Content-Type': 'text/event-stream' } },
+ ),
+ ),
+ }),
+ )
+
+ const { result } = renderHook(() =>
+ useChat({
+ identityScopeKey: 'identity',
+ persistMessages: false,
+ sessionId: 'session-1',
+ }),
+ )
+
+ let sendPromise!: Promise<void>
+ await act(async () => {
+ sendPromise = result.current.send('hello')
+ controller.enqueue(
+ encoder.encode(
+ [
+ { event: 'reasoning_delta', data: 'first' },
+ { event: 'tool_call', data: 'search({})' },
+ { event: 'tool_result', data: '{}' },
+ { event: 'reasoning_delta', data: 'second' },
+ ]
+ .map((event) => `data: ${JSON.stringify(event)}\n\n`)
+ .join(''),
+ ),
+ )
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+
+ expect(
+ result.current.streamingParts
+ .filter((part) => part.type === 'reasoning')
+ .map((part) => part.is_running),
+ ).toEqual([false, true])
+
+ await act(async () => {
+ controller.close()
+ await sendPromise
+ })
+ })
+
+ it('renders a complete reasoning event as completed', async () => {
+ let controller!: ReadableStreamDefaultController<Uint8Array>
+ const encoder = new TextEncoder()
+ sendChatStreamMock.mockResolvedValue(
+ fetchSse('/stream', {
+ fetch: vi.fn().mockResolvedValue(
+ new Response(
+ new ReadableStream<Uint8Array>({
+ start(streamController) {
+ controller = streamController
+ },
+ }),
+ { headers: { 'Content-Type': 'text/event-stream' } },
+ ),
+ ),
+ }),
+ )
+
+ const { result } = renderHook(() =>
+ useChat({
+ identityScopeKey: 'identity',
+ persistMessages: false,
+ sessionId: 'session-1',
+ }),
+ )
+
+ let sendPromise!: Promise<void>
+ await act(async () => {
+ sendPromise = result.current.send('hello')
+ controller.enqueue(
+ encoder.encode(
+ `data: ${JSON.stringify({
+ event: 'reasoning',
+ data: 'complete reasoning',
+ })}\n\n`,
+ ),
+ )
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+
+ expect(result.current.streamingParts).toContainEqual({
+ type: 'reasoning',
+ reasoning: 'complete reasoning',
+ is_running: false,
+ })
+
+ await act(async () => {
+ controller.close()
+ await sendPromise
+ })
+ })
+
+ it('finalizes when the response event arrives before the stream closes', async () => {
+ let streamReleased = false
+ async function* stream() {
+ try {
+ yield {
+ data: JSON.stringify({ event: 'response', data: 'final response' }),
+ event: '',
+ id: '',
+ }
+ await new Promise(() => {})
+ } finally {
+ streamReleased = true
+ }
+ }
+ sendChatStreamMock.mockResolvedValue(stream())
+
+ const { result } = renderHook(() =>
+ useChat({
+ identityScopeKey: 'identity',
+ persistMessages: false,
+ sessionId: 'session-1',
+ }),
+ )
+
+ await act(async () => {
+ await result.current.send('hello')
+ })
+
+ expect(result.current.status).toBe('idle')
+ expect(result.current.messages[1]?.parts).toContainEqual({
+ text: 'final response',
+ type: 'text',
+ })
+ expect(streamReleased).toBe(true)
+ })
+
+ it('keeps reasoning and tool timeline when aborted before content arrives', async () => {
+ let controller!: ReadableStreamDefaultController<Uint8Array>
+ const encoder = new TextEncoder()
+ sendChatStreamMock.mockImplementation((_request, signal: AbortSignal) =>
+ fetchSse('/stream', {
+ signal,
+ fetch: vi.fn().mockResolvedValue(
+ new Response(
+ new ReadableStream<Uint8Array>({
+ start(streamController) {
+ controller = streamController
+ },
+ }),
+ { headers: { 'Content-Type': 'text/event-stream' } },
+ ),
+ ),
+ }),
+ )
+
+ const { result } = renderHook(() =>
+ useChat({
+ identityScopeKey: 'identity',
+ persistMessages: false,
+ sessionId: 'session-1',
+ }),
+ )
+
+ let sendPromise!: Promise<void>
+ await act(async () => {
+ sendPromise = result.current.send('hello')
+ controller.enqueue(
+ encoder.encode(
+ [
+ { event: 'reasoning_delta', data: 'checking' },
+ { event: 'tool_call', data: 'search({})' },
+ ]
+ .map((event) => `data: ${JSON.stringify(event)}\n\n`)
+ .join(''),
+ ),
+ )
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ result.current.abort()
+ await sendPromise
+ })
+
+ expect(result.current.status).toBe('idle')
+ expect(result.current.streamingParts).toEqual([])
+ expect(result.current.messages[1]?.parts).toMatchObject([
+ {
+ is_running: false,
+ reasoning: 'checking',
+ type: 'reasoning',
+ },
+ {
+ tool_name: 'search',
+ tool_status: 'running',
+ type: 'tool',
+ },
+ ])
+ })
+})
diff --git a/web-studio/src/lib/sessions/use-chat.ts b/web-studio/src/lib/sessions/use-chat.ts
index 1eee8f973..17bc3999a 100644
--- a/web-studio/src/lib/sessions/use-chat.ts
+++ b/web-studio/src/lib/sessions/use-chat.ts
@@ -5,9 +5,11 @@ import type {
Message,
MessagePart,
ContextPart,
+ IterationPart,
ReasoningPart,
TextPart,
ToolPart,
+ ToolResultPart,
} from './types/message'
import { addMessage, sendChatStream, serializeParts } from './api'
import { parseSseStream, streamEventDataToText } from './sse'
@@ -58,11 +60,15 @@ function clonePart(part: MessagePart): MessagePart {
return { ...part } satisfies TextPart
case 'reasoning':
return { ...part } satisfies ReasoningPart
+ case 'iteration':
+ return { ...part } satisfies IterationPart
case 'tool':
return {
...part,
tool_input: part.tool_input ? { ...part.tool_input } : undefined,
} satisfies ToolPart
+ case 'tool_result':
+ return { ...part } satisfies ToolResultPart
case 'context':
return { ...part } satisfies ContextPart
}
@@ -259,6 +265,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {
const accParts: MessagePart[] = []
let lastToolCall: StreamToolCall | null = null
let currentReasoningPart: ReasoningPart | null = null
+ let currentReasoningHasDelta = false
let currentTextPart: TextPart | null = null
let currentIteration = 0
let lastPaintAt = 0
@@ -292,7 +299,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {
await waitForNextFrame()
}
- const appendReasoning = (text: string, replaceIfEmpty: boolean) => {
+ const appendReasoning = (text: string) => {
if (!text) return
if (!currentReasoningPart || accParts.at(-1) !== currentReasoningPart) {
currentReasoningPart = {
@@ -302,33 +309,37 @@ export function useChat(options: UseChatOptions): UseChatReturn {
}
accParts.push(currentReasoningPart)
}
- currentReasoningPart.reasoning =
- replaceIfEmpty && !currentReasoningPart.reasoning
- ? text
- : currentReasoningPart.reasoning + text
+ currentReasoningPart.reasoning += text
publishStreamingParts()
}
+ const finishCurrentReasoning = () => {
+ if (!currentReasoningPart) return
+ currentReasoningPart.is_running = false
+ currentReasoningPart = null
+ currentReasoningHasDelta = false
+ }
+
const appendText = (text: string) => {
if (!text) return
+ finishCurrentReasoning()
if (!currentTextPart || accParts.at(-1) !== currentTextPart) {
currentTextPart = { type: 'text', text: '' }
accParts.push(currentTextPart)
}
currentTextPart.text += text
- currentReasoningPart = null
publishStreamingParts()
}
const setFinalText = (text: string) => {
if (!text) return
+ finishCurrentReasoning()
if (currentTextPart) {
currentTextPart.text = text
} else {
currentTextPart = { type: 'text', text }
accParts.push(currentTextPart)
}
- currentReasoningPart = null
publishStreamingPartsNow()
}
@@ -338,7 +349,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {
controller.signal,
)
- for await (const event of parseSseStream(response)) {
+ stream: for await (const event of parseSseStream(response)) {
if (controller.signal.aborted) break
switch (event.event) {
@@ -348,6 +359,20 @@ export function useChat(options: UseChatOptions): UseChatReturn {
if (match) {
currentIteration = Number(match[1])
setIteration(currentIteration)
+ finishCurrentReasoning()
+ currentTextPart = null
+ const previousPart = accParts.at(-1)
+ if (
+ previousPart?.type !== 'iteration' ||
+ previousPart.iteration !== currentIteration
+ ) {
+ accParts.push({
+ type: 'iteration',
+ iteration: currentIteration,
+ })
+ publishStreamingParts()
+ await yieldToRenderer()
+ }
}
break
}
@@ -365,17 +390,21 @@ export function useChat(options: UseChatOptions): UseChatReturn {
const delta = streamEventDataToText(event.data)
accReasoning += delta
setStreamingReasoning(accReasoning)
- appendReasoning(delta, false)
+ appendReasoning(delta)
+ currentReasoningHasDelta = true
await yieldToRenderer()
break
}
case 'reasoning': {
// Complete reasoning block (fallback if no deltas were sent)
- if (!accReasoning) {
- accReasoning = streamEventDataToText(event.data)
+ if (!currentReasoningHasDelta) {
+ const reasoning = streamEventDataToText(event.data)
+ accReasoning += reasoning
setStreamingReasoning(accReasoning)
- appendReasoning(accReasoning, true)
+ appendReasoning(reasoning)
+ finishCurrentReasoning()
+ publishStreamingPartsNow()
await yieldToRenderer()
}
break
@@ -392,7 +421,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {
tc.iteration === currentIteration &&
tc.name === name &&
tc.arguments === args &&
- !tc.result,
+ tc.result === undefined,
)
if (duplicate) {
lastToolCall = duplicate
@@ -421,8 +450,8 @@ export function useChat(options: UseChatOptions): UseChatReturn {
} catch {
if (args) toolPart.tool_input = { raw: args }
}
+ finishCurrentReasoning()
accParts.push(toolPart)
- currentReasoningPart = null
currentTextPart = null
setStreamingToolCalls(dedupeToolCalls(accToolCalls))
publishStreamingParts()
@@ -431,7 +460,10 @@ export function useChat(options: UseChatOptions): UseChatReturn {
}
case 'tool_result': {
- const pendingToolCall = accToolCalls.find((tc) => !tc.result)
+ finishCurrentReasoning()
+ const pendingToolCall = accToolCalls.find(
+ (tc) => tc.result === undefined,
+ )
const pendingToolPart = accParts.find(
(part): part is ToolPart =>
part.type === 'tool' &&
@@ -440,13 +472,20 @@ export function useChat(options: UseChatOptions): UseChatReturn {
)
if (pendingToolCall) {
const result = streamEventDataToText(event.data)
+ const isError = isToolErrorResult(result)
pendingToolCall.result = result
if (pendingToolPart) {
pendingToolPart.tool_output = result
- pendingToolPart.tool_status = isToolErrorResult(result)
- ? 'error'
- : 'completed'
+ pendingToolPart.tool_status = isError ? 'error' : 'completed'
+ accParts.push({
+ type: 'tool_result',
+ tool_id: pendingToolPart.tool_id,
+ tool_name: pendingToolPart.tool_name,
+ tool_output: result,
+ is_error: isError,
+ })
}
+ currentTextPart = null
setStreamingToolCalls(dedupeToolCalls(accToolCalls))
publishStreamingParts()
await yieldToRenderer()
@@ -459,12 +498,13 @@ export function useChat(options: UseChatOptions): UseChatReturn {
accContent = streamEventDataToText(event.data)
setStreamingContent(accContent)
setFinalText(accContent)
- break
+ break stream
}
}
}
// Build assistant message and finalize
+ finishCurrentReasoning()
const assistantMsg = buildAssistantMessage(
accContent,
dedupeToolCalls(accToolCalls),
@@ -505,7 +545,8 @@ export function useChat(options: UseChatOptions): UseChatReturn {
} catch (err) {
if (controller.signal.aborted) {
// Aborted intentionally — still finalize any partial content
- if (accContent) {
+ if (accContent || accParts.length > 0) {
+ finishCurrentReasoning()
const partialMsg = buildAssistantMessage(
accContent,
dedupeToolCalls(accToolCalls),
@@ -516,6 +557,11 @@ export function useChat(options: UseChatOptions): UseChatReturn {
setStreamingReasoning('')
setStreamingParts([])
setMessages((prev) => [...prev, partialMsg])
+ } else {
+ setStreamingContent('')
+ setStreamingToolCalls([])
+ setStreamingReasoning('')
+ setStreamingParts([])
}
setStatus('idle')
} else {
diff --git a/web-studio/src/lib/sse.test.ts b/web-studio/src/lib/sse.test.ts
new file mode 100644
index 000000000..dde46f168
--- /dev/null
+++ b/web-studio/src/lib/sse.test.ts
@@ -0,0 +1,123 @@
+// @vitest-environment jsdom
+
+import { describe, expect, it, vi } from 'vitest'
+
+import { fetchSse, SseResponseError } from './sse'
+
+function sseResponse(chunks: Array<string>): Response {
+ const encoder = new TextEncoder()
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(encoder.encode(chunk))
+ controller.close()
+ },
+ }),
+ { headers: { 'Content-Type': 'text/event-stream; charset=utf-8' } },
+ )
+}
+
+describe('fetchSse', () => {
+ it('supports POST and parses standard SSE event boundaries', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ sseResponse([
+ ': heartbeat\r\n',
+ 'id: event-1\r\nevent: update\r\ndata: first\r\n',
+ 'data: second\r\n\r\n',
+ ]),
+ )
+
+ const messages = []
+ for await (const message of fetchSse('/stream', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: '{"message":"hello"}',
+ fetch: fetchMock,
+ })) {
+ messages.push(message)
+ }
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/stream',
+ expect.objectContaining({
+ body: '{"message":"hello"}',
+ method: 'POST',
+ }),
+ )
+ expect(messages).toEqual([
+ {
+ data: 'first\nsecond',
+ event: 'update',
+ id: 'event-1',
+ retry: undefined,
+ },
+ ])
+ })
+
+ it('rejects non-SSE responses without retrying the POST', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response('invalid request', {
+ status: 400,
+ headers: { 'Content-Type': 'text/plain' },
+ }),
+ )
+
+ const consume = async () => {
+ for await (const _message of fetchSse('/stream', {
+ method: 'POST',
+ fetch: fetchMock,
+ })) {
+ // No messages expected.
+ }
+ }
+
+ await expect(consume()).rejects.toBeInstanceOf(SseResponseError)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('aborts an active POST stream', async () => {
+ const controller = new AbortController()
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(new ReadableStream<Uint8Array>(), {
+ headers: { 'Content-Type': 'text/event-stream' },
+ }),
+ )
+
+ const consume = async () => {
+ for await (const _message of fetchSse('/stream', {
+ method: 'POST',
+ fetch: fetchMock,
+ signal: controller.signal,
+ })) {
+ // No messages expected.
+ }
+ }
+ const consuming = consume()
+ await Promise.resolve()
+ controller.abort()
+
+ await expect(consuming).rejects.toMatchObject({ name: 'AbortError' })
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not start a POST when the signal is already aborted', async () => {
+ const controller = new AbortController()
+ const fetchMock = vi.fn()
+ controller.abort()
+
+ const consume = async () => {
+ for await (const _message of fetchSse('/stream', {
+ method: 'POST',
+ fetch: fetchMock,
+ signal: controller.signal,
+ })) {
+ // No messages expected.
+ }
+ }
+
+ await expect(consume()).rejects.toMatchObject({ name: 'AbortError' })
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/web-studio/src/lib/sse.ts b/web-studio/src/lib/sse.ts
new file mode 100644
index 000000000..895546799
--- /dev/null
+++ b/web-studio/src/lib/sse.ts
@@ -0,0 +1,121 @@
+import {
+ EventStreamContentType,
+ fetchEventSource,
+} from '@microsoft/fetch-event-source'
+
+import type {
+ EventSourceMessage,
+ FetchEventSourceInit,
+} from '@microsoft/fetch-event-source'
+
+export type SseMessage = EventSourceMessage
+
+export type FetchSseOptions = Omit<
+ FetchEventSourceInit,
+ 'onopen' | 'onmessage' | 'onclose' | 'onerror' | 'signal'
+> & {
+ signal?: AbortSignal
+}
+
+export class SseResponseError extends Error {
+ readonly response: Response
+ readonly responseBody: string
+
+ constructor(response: Response, responseBody: string) {
+ super(
+ response.ok
+ ? `Expected ${EventStreamContentType} response`
+ : `SSE request failed (${response.status}): ${responseBody}`,
+ )
+ this.name = 'SseResponseError'
+ this.response = response
+ this.responseBody = responseBody
+ }
+}
+
+/**
+ * Make a Fetch-compatible SSE request and expose its messages as an async
+ * iterable. Unlike the browser EventSource API, this supports POST bodies,
+ * custom headers, and AbortSignal.
+ */
+export async function* fetchSse(
+ input: RequestInfo,
+ { signal, ...options }: FetchSseOptions = {},
+): AsyncGenerator<SseMessage> {
+ if (signal?.aborted) {
+ throw (
+ signal.reason ??
+ new DOMException('The operation was aborted', 'AbortError')
+ )
+ }
+
+ const controller = new AbortController()
+ const messages: Array<SseMessage> = []
+ const state: { completed: boolean; failure?: unknown } = { completed: false }
+ let wakeConsumer: (() => void) | undefined
+
+ const wake = () => {
+ wakeConsumer?.()
+ wakeConsumer = undefined
+ }
+ const abort = () => {
+ state.failure =
+ signal?.reason ??
+ new DOMException('The operation was aborted', 'AbortError')
+ controller.abort(state.failure)
+ }
+
+ signal?.addEventListener('abort', abort, { once: true })
+
+ const request = fetchEventSource(input, {
+ ...options,
+ signal: controller.signal,
+ openWhenHidden: true,
+ async onopen(response) {
+ const contentType = response.headers.get('content-type') ?? ''
+ if (response.ok && contentType.includes(EventStreamContentType)) return
+
+ const responseBody = await response.text().catch(() => '')
+ throw new SseResponseError(response, responseBody)
+ },
+ onmessage(message) {
+ messages.push(message)
+ wake()
+ },
+ onerror(error) {
+ // Chat POST requests must not be replayed automatically.
+ throw error
+ },
+ }).then(
+ () => {
+ state.completed = true
+ wake()
+ },
+ (error: unknown) => {
+ state.failure = error
+ state.completed = true
+ wake()
+ },
+ )
+
+ try {
+ while (!state.completed || messages.length > 0) {
+ const message = messages.shift()
+ if (message) {
+ yield message
+ continue
+ }
+
+ await new Promise<void>((resolve) => {
+ wakeConsumer = resolve
+ })
+ }
+
+ if (state.failure) throw state.failure
+ await request
+ } finally {
+ signal?.removeEventListener('abort', abort)
+ controller.abort()
+ await request.catch(() => undefined)
+ }
+}
diff --git a/web-studio/src/routes/playground/-components/agent-panel.test.tsx b/web-studio/src/routes/playground/-components/agent-panel.test.tsx
new file mode 100644
index 000000000..84aa4636c
--- /dev/null
+++ b/web-studio/src/routes/playground/-components/agent-panel.test.tsx
@@ -0,0 +1,40 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { AgentToolbar } from './agent-panel'
+
+afterEach(() => {
+ cleanup()
+ document.body.innerHTML = ''
+})
+
+describe('AgentToolbar', () => {
+ it('portals the active session title beside the panel controls', () => {
+ const container = document.createElement('div')
+ const onNewSession = vi.fn()
+ const onOpenHistory = vi.fn()
+ document.body.append(container)
+
+ render(
+ <AgentToolbar
+ container={container}
+ historyLabel="History"
+ isCreatingSession={false}
+ newSessionLabel="New session"
+ onNewSession={onNewSession}
+ onOpenHistory={onOpenHistory}
+ sessionTitle="Current session"
+ />,
+ )
+
+ expect(container.textContent).toContain('Current session')
+ fireEvent.click(screen.getByTitle('History'))
+ fireEvent.click(screen.getByTitle('New session'))
+ expect(onOpenHistory).toHaveBeenCalledOnce()
+ expect(onNewSession).toHaveBeenCalledOnce()
+
+ container.remove()
+ })
+})
diff --git a/web-studio/src/routes/playground/-components/agent-panel.tsx b/web-studio/src/routes/playground/-components/agent-panel.tsx
index 63052a167..a9e3d8016 100644
--- a/web-studio/src/routes/playground/-components/agent-panel.tsx
+++ b/web-studio/src/routes/playground/-components/agent-panel.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import {
- BotIcon,
CheckCircle2Icon,
CircleAlertIcon,
HistoryIcon,
@@ -44,10 +44,12 @@ export function AgentPanel({
initialSessionId,
onOpenResource,
onSessionChange,
+ toolbarContainer,
}: {
initialSessionId?: string
onOpenResource: ResourceOpenHandler
onSessionChange: (sessionId: string) => void
+ toolbarContainer: HTMLDivElement | null
}) {
const { t } = useTranslation('playground')
const { identityScopeKey } = useAppConnection()
@@ -164,6 +166,9 @@ export function AgentPanel({
const isStreaming = chat.status === 'streaming'
const botModeError = botHealth.isError ? getErrorMessage(botHealth.error) : ''
+ const sessionTitle = getTitle(sessionId)
+ const displayedSessionTitle =
+ sessionTitle === sessionId ? t('agent.newSessionTitle') : sessionTitle
const reversedSessions = useMemo(() => {
// `sessions` is already sorted by recency (newest first). Filter to
// sessions that were opened in this playground, preserving recency order.
@@ -180,41 +185,16 @@ export function AgentPanel({
return (
<>
+ <AgentToolbar
+ container={toolbarContainer}
+ historyLabel={t('agent.history')}
+ isCreatingSession={isCreatingSession}
+ newSessionLabel={t('agent.newSession')}
+ onNewSession={() => void handleNewSession()}
+ onOpenHistory={() => setHistoryOpen(true)}
+ sessionTitle={displayedSessionTitle}
+ />
<div className="flex min-h-0 flex-1 flex-col">
- <div className="flex h-14 shrink-0 items-center border-b bg-background/70 px-4">
- <div className="flex min-w-0 flex-1 items-center gap-2 text-xs text-muted-foreground">
- <BotIcon className="size-3.5 shrink-0" />
- <span className="min-w-0 flex-1 truncate">
- {t('agent.autoRetrieve')}
- </span>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- className="size-7 shrink-0"
- title={t('agent.history')}
- onClick={() => setHistoryOpen(true)}
- >
- <HistoryIcon className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- className="size-7 shrink-0"
- title={t('agent.newSession')}
- disabled={isCreatingSession}
- onClick={() => void handleNewSession()}
- >
- {isCreatingSession ? (
- <Loader2Icon className="size-3.5 animate-spin" />
- ) : (
- <SquarePenIcon className="size-3.5" />
- )}
- </Button>
- </div>
- </div>
-
<div
ref={scrollRef}
className="min-h-0 flex-1 overflow-y-auto px-4 py-4"
@@ -354,6 +334,63 @@ export function AgentPanel({
)
}
+export function AgentToolbar({
+ container,
+ historyLabel,
+ isCreatingSession,
+ newSessionLabel,
+ onNewSession,
+ onOpenHistory,
+ sessionTitle,
+}: {
+ container: HTMLDivElement | null
+ historyLabel: string
+ isCreatingSession: boolean
+ newSessionLabel: string
+ onNewSession: () => void
+ onOpenHistory: () => void
+ sessionTitle: string
+}) {
+ if (!container) return null
+
+ return createPortal(
+ <>
+ <span
+ className="min-w-0 max-w-48 truncate px-1 text-sm font-medium text-foreground"
+ title={sessionTitle}
+ >
+ {sessionTitle}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 shrink-0"
+ title={historyLabel}
+ onClick={onOpenHistory}
+ >
+ <HistoryIcon className="size-3.5" />
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 shrink-0"
+ title={newSessionLabel}
+ disabled={isCreatingSession}
+ onClick={onNewSession}
+ >
+ {isCreatingSession ? (
+ <Loader2Icon className="size-3.5 animate-spin" />
+ ) : (
+ <SquarePenIcon className="size-3.5" />
+ )}
+ </Button>
+ </>,
+ container,
+ )
+}
+
export function BotModePrompt({
detail,
onRetry,
diff --git a/web-studio/src/routes/playground/-components/context-explorer.tsx b/web-studio/src/routes/playground/-components/context-explorer.tsx
index 2cd243912..65bd60d65 100644
--- a/web-studio/src/routes/playground/-components/context-explorer.tsx
+++ b/web-studio/src/routes/playground/-components/context-explorer.tsx
@@ -181,7 +181,7 @@ export function ContextTree({
</div>
) : rootQuery.isError ? (
<div className="px-1.5 text-xs leading-7 text-destructive">
- {t('dirBrowser.error')}
+ {t('dirBrowser.error', { ns: 'resources' })}
</div>
) : namespaces.length === 0 ? (
<div className="px-1.5 text-xs leading-7 text-muted-foreground/60">
diff --git a/web-studio/src/routes/playground/-components/terminal-panel.tsx b/web-studio/src/routes/playground/-components/terminal-panel.tsx
index 9991b67fb..5badcaa23 100644
--- a/web-studio/src/routes/playground/-components/terminal-panel.tsx
+++ b/web-studio/src/routes/playground/-components/terminal-panel.tsx
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import {
ArrowRightIcon,
@@ -7,7 +8,6 @@ import {
Loader2Icon,
SendIcon,
SparklesIcon,
- TerminalIcon,
TrashIcon,
XCircleIcon,
} from 'lucide-react'
@@ -450,6 +450,7 @@ export function TerminalPanel({
openingUri,
onSessionChange,
sessionId,
+ toolbarContainer,
}: {
currentUri: string
entries: VikingFsEntry[]
@@ -458,6 +459,7 @@ export function TerminalPanel({
openingUri: string | null
onSessionChange: (sessionId: string) => void
sessionId?: string
+ toolbarContainer: HTMLDivElement | null
}) {
const { t } = useTranslation('playground')
const { connectionRole, identityScopeKey } = useAppConnection()
@@ -1373,31 +1375,30 @@ export function TerminalPanel({
return (
<>
+ {toolbarContainer
+ ? createPortal(
+ <>
+ <span
+ className="min-w-0 max-w-40 truncate rounded-md border bg-muted/40 px-2 py-1 font-mono text-[11px] text-foreground"
+ title={currentUri}
+ >
+ {t('terminal.scopeLabel', { uri: currentUri })}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 shrink-0"
+ title={t('terminal.history')}
+ onClick={() => setHistoryOpen(true)}
+ >
+ <HistoryIcon className="size-3.5" />
+ </Button>
+ </>,
+ toolbarContainer,
+ )
+ : null}
<div className="flex min-h-0 flex-1 flex-col">
- <div className="border-b bg-background/70 px-4 py-3">
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <TerminalIcon className="size-3.5 shrink-0" />
- <span className="min-w-0 flex-1 truncate">
- {t('terminal.header')}
- </span>
- <span
- className="min-w-0 max-w-[60%] truncate rounded-md border bg-muted/40 px-2 py-1 font-mono text-[11px] text-foreground"
- title={currentUri}
- >
- {t('terminal.scopeLabel', { uri: currentUri })}
- </span>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- className="size-7 shrink-0"
- title={t('terminal.history')}
- onClick={() => setHistoryOpen(true)}
- >
- <HistoryIcon className="size-3.5" />
- </Button>
- </div>
- </div>
<div
ref={scrollRef}
className="min-h-0 flex-1 overflow-y-auto px-4 py-4"
diff --git a/web-studio/src/routes/playground/-lib/constants.ts b/web-studio/src/routes/playground/-lib/constants.ts
index a9eb82972..5238c63d0 100644
--- a/web-studio/src/routes/playground/-lib/constants.ts
+++ b/web-studio/src/routes/playground/-lib/constants.ts
@@ -7,6 +7,8 @@ export const PLAYGROUND_RIGHT_WIDTH_STORAGE_KEY =
'openviking.playground.rightWidth'
export const PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY =
'openviking.playground.agentSessions'
+export const PLAYGROUND_EXPANDED_URIS_STORAGE_KEY =
+ 'openviking.playground.expandedUris'
export const PLAYGROUND_LEFT_WIDTH = {
default: 330,
max: 620,
diff --git a/web-studio/src/routes/playground/-lib/utils.test.ts b/web-studio/src/routes/playground/-lib/utils.test.ts
index 915558b99..3596a8cb9 100644
--- a/web-studio/src/routes/playground/-lib/utils.test.ts
+++ b/web-studio/src/routes/playground/-lib/utils.test.ts
@@ -1,6 +1,16 @@
-import { describe, expect, it } from 'vitest'
+// @vitest-environment jsdom
-import { createIdentityStorageKey } from './utils'
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import {
+ createIdentityStorageKey,
+ readPlaygroundExpandedUris,
+ writePlaygroundExpandedUris,
+} from './utils'
+
+beforeEach(() => {
+ localStorage.clear()
+})
describe('createIdentityStorageKey', () => {
it('isolates persisted Playground state by identity scope', () => {
@@ -20,3 +30,18 @@ describe('createIdentityStorageKey', () => {
expect(key).not.toContain('\u0000')
})
})
+
+describe('Playground expanded directory persistence', () => {
+ it('restores normalized expanded URIs for the same identity', () => {
+ writePlaygroundExpandedUris('account-a\u0000alice', [
+ 'viking://user/default',
+ 'viking://resources/',
+ ])
+
+ expect(readPlaygroundExpandedUris('account-a\u0000alice')).toEqual([
+ 'viking://user/default/',
+ 'viking://resources/',
+ ])
+ expect(readPlaygroundExpandedUris('account-a\u0000bob')).toEqual([])
+ })
+})
diff --git a/web-studio/src/routes/playground/-lib/utils.ts b/web-studio/src/routes/playground/-lib/utils.ts
index f7dd45765..b9ab8d083 100644
--- a/web-studio/src/routes/playground/-lib/utils.ts
+++ b/web-studio/src/routes/playground/-lib/utils.ts
@@ -9,7 +9,11 @@ import type { FindResultItem, GroupedFindResult } from '#/lib/retrieval'
import { cleanVikingUri } from '#/lib/viking-uri'
-import { ROOT_URI, PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY } from './constants'
+import {
+ ROOT_URI,
+ PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,
+ PLAYGROUND_EXPANDED_URIS_STORAGE_KEY,
+} from './constants'
import type { ResourceRef } from './types'
export { cleanVikingUri }
@@ -146,6 +150,33 @@ export function registerPlaygroundAgentSessionId(
return next
}
+export function readPlaygroundExpandedUris(identityScopeKey: string): string[] {
+ return readStoredJsonArray(
+ createIdentityStorageKey(
+ PLAYGROUND_EXPANDED_URIS_STORAGE_KEY,
+ identityScopeKey,
+ ),
+ (uri) =>
+ typeof uri === 'string' && uri.startsWith(ROOT_URI)
+ ? normalizeDirUri(uri)
+ : undefined,
+ 500,
+ )
+}
+
+export function writePlaygroundExpandedUris(
+ identityScopeKey: string,
+ uris: Iterable<string>,
+): void {
+ writeStoredJson(
+ createIdentityStorageKey(
+ PLAYGROUND_EXPANDED_URIS_STORAGE_KEY,
+ identityScopeKey,
+ ),
+ [...uris],
+ )
+}
+
export function createEntryFromUri(uri: string, isDir: boolean): VikingFsEntry {
const normalized = isDir ? normalizeDirUri(uri) : normalizeFileUri(uri)
return {
diff --git a/web-studio/src/routes/playground/route.tsx b/web-studio/src/routes/playground/route.tsx
index ff004bf14..e93323beb 100644
--- a/web-studio/src/routes/playground/route.tsx
+++ b/web-studio/src/routes/playground/route.tsx
@@ -11,6 +11,7 @@ import {
import { toast } from 'sonner'
import { Button } from '#/components/ui/button'
+import { useAppConnection } from '#/hooks/use-app-connection'
import {
Dialog,
DialogContent,
@@ -70,8 +71,10 @@ import {
isDirectoryLevelFile,
mergeExpanded,
normalizePlaygroundResourceUri,
+ readPlaygroundExpandedUris,
readStoredNumber,
visibleContextEntries,
+ writePlaygroundExpandedUris,
} from './-lib/utils'
export const Route = createFileRoute('/playground')({
@@ -98,6 +101,7 @@ function PlaygroundRoute() {
function PlaygroundWorkbench() {
const { t } = useTranslation(['playground', 'resources'])
+ const { identityScopeKey } = useAppConnection()
const search = Route.useSearch()
const navigate = useNavigate({ from: Route.fullPath })
const initialCurrentUri = useMemo(
@@ -114,8 +118,11 @@ function PlaygroundWorkbench() {
? createEntryFromUri(search.file, false)
: createEntryFromUri(initialCurrentUri, true),
)
- const [expandedKeys, setExpandedKeys] = useState<Set<string>>(
- () => new Set(getAncestorUris(initialCurrentUri)),
+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(() =>
+ mergeExpanded(
+ new Set(readPlaygroundExpandedUris(identityScopeKey)),
+ getAncestorUris(initialCurrentUri),
+ ),
)
const [activePanel, setActivePanel] = useState<PlaygroundPanel>(
search.panel ?? 'agent',
@@ -190,6 +197,15 @@ function PlaygroundWorkbench() {
[navigate],
)
+ useEffect(() => {
+ setExpandedKeys(
+ mergeExpanded(
+ new Set(readPlaygroundExpandedUris(identityScopeKey)),
+ getAncestorUris(initialCurrentUri),
+ ),
+ )
+ }, [identityScopeKey, initialCurrentUri])
+
useEffect(() => {
const normalized = search.file
? normalizeDirUri(parentUri(search.file))
@@ -203,6 +219,14 @@ function PlaygroundWorkbench() {
setExpandedKeys((prev) => mergeExpanded(prev, getAncestorUris(normalized)))
}, [search.file, search.uri])
+ const handleExpandedKeysChange = useCallback(
+ (next: Set<string>) => {
+ setExpandedKeys(next)
+ writePlaygroundExpandedUris(identityScopeKey, next)
+ },
+ [identityScopeKey],
+ )
+
useEffect(() => {
if (search.panel === 'agent' || search.panel === 'terminal') {
setActivePanel(search.panel)
@@ -505,7 +529,7 @@ function PlaygroundWorkbench() {
selectedFile && !selectedFile.isDir ? selectedFile.uri : null
}
expandedKeys={expandedKeys}
- onExpandedKeysChange={setExpandedKeys}
+ onExpandedKeysChange={handleExpandedKeysChange}
onSelectDirectory={handleSelectDirectory}
onSelectFile={handleSelectFile}
/>
@@ -700,14 +724,20 @@ function PlaygroundActionPanel({
sessionId?: string
}) {
const { t } = useTranslation('playground')
+ const [toolbarContainer, setToolbarContainer] =
+ useState<HTMLDivElement | null>(null)
return (
<div className="flex h-full min-h-0 flex-col">
- <div className="flex h-14 shrink-0 items-center border-b px-3">
+ <div className="flex h-14 shrink-0 items-center gap-2 border-b px-3">
<PlaygroundActionTabs
activePanel={activePanel}
onPanelChange={onPanelChange}
/>
+ <div
+ ref={setToolbarContainer}
+ className="ml-auto flex min-w-0 items-center gap-1"
+ />
</div>
<PlaygroundActionContent
@@ -719,6 +749,7 @@ function PlaygroundActionPanel({
onSessionChange={onSessionChange}
openingUri={openingUri}
sessionId={sessionId}
+ toolbarContainer={toolbarContainer}
/>
</div>
)
@@ -750,6 +781,8 @@ function PlaygroundMobileActionScreen({
sessionId?: string
}) {
const { t } = useTranslation(['playground', 'resources'])
+ const [toolbarContainer, setToolbarContainer] =
+ useState<HTMLDivElement | null>(null)
if (!open) {
return null
@@ -772,6 +805,10 @@ function PlaygroundMobileActionScreen({
activePanel={activePanel}
onPanelChange={onPanelChange}
/>
+ <div
+ ref={setToolbarContainer}
+ className="ml-auto flex min-w-0 items-center gap-1"
+ />
</div>
<div className="min-h-0 flex-1">
<PlaygroundActionContent
@@ -783,6 +820,7 @@ function PlaygroundMobileActionScreen({
onSessionChange={onSessionChange}
openingUri={openingUri}
sessionId={sessionId}
+ toolbarContainer={toolbarContainer}
/>
</div>
</div>
@@ -825,6 +863,7 @@ function PlaygroundActionContent({
onSessionChange,
openingUri,
sessionId,
+ toolbarContainer,
}: {
activePanel: PlaygroundPanel
currentUri: string
@@ -834,6 +873,7 @@ function PlaygroundActionContent({
onSessionChange: (sessionId: string) => void
openingUri: string | null
sessionId?: string
+ toolbarContainer: HTMLDivElement | null
}) {
return (
<div className="flex h-full min-h-0 flex-col">
@@ -846,12 +886,14 @@ function PlaygroundActionContent({
onSessionChange={onSessionChange}
openingUri={openingUri}
sessionId={sessionId}
+ toolbarContainer={toolbarContainer}
/>
) : (
<AgentPanel
initialSessionId={sessionId}
onOpenResource={onOpenResource}
onSessionChange={onSessionChange}
+ toolbarContainer={toolbarContainer}
/>
)}
</div>
diff --git a/web-studio/src/routes/sessions/-components/composer.tsx b/web-studio/src/routes/sessions/-components/composer.tsx
index 61f0375d1..b878b91ea 100644
--- a/web-studio/src/routes/sessions/-components/composer.tsx
+++ b/web-studio/src/routes/sessions/-components/composer.tsx
@@ -58,7 +58,7 @@ export function Composer({
<div
className={cn(
'mx-auto w-full border border-border/50 bg-background/95',
- isCompact ? 'max-w-none' : 'max-w-3xl',
+ isCompact ? 'max-w-none' : 'max-w-[clamp(48rem,68vw,72rem)]',
isCompact ? 'rounded-xl' : 'rounded-2xl',
'shadow-lg shadow-black/8 dark:shadow-black/25',
)}
diff --git a/web-studio/src/routes/sessions/-components/memory-impact.test.tsx b/web-studio/src/routes/sessions/-components/memory-impact.test.tsx
new file mode 100644
index 000000000..5be22d464
--- /dev/null
+++ b/web-studio/src/routes/sessions/-components/memory-impact.test.tsx
@@ -0,0 +1,85 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { MemoryImpact } from './memory-impact'
+import type { SessionMemoryDiff } from '#/lib/sessions/memory-diff'
+import type { SessionMeta } from '@ov-server/api/v1/sessions'
+
+const { useSessionMemoryDiffsMock } = vi.hoisted(() => ({
+ useSessionMemoryDiffsMock: vi.fn(),
+}))
+
+vi.mock('#/lib/sessions/use-sessions', () => ({
+ useSessionMemoryDiffs: useSessionMemoryDiffsMock,
+}))
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: { resolvedLanguage: 'en' },
+ t: (key: string) => key,
+ }),
+}))
+
+afterEach(cleanup)
+
+const diffs: SessionMemoryDiff[] = [
+ {
+ archiveId: 'archive-1',
+ archiveUri: 'viking://session/archive-1',
+ extractedAt: '2026-07-26T00:00:00Z',
+ operations: [
+ {
+ after: 'profile',
+ kind: 'add',
+ memoryType: 'profile',
+ uri: 'viking://user/profile',
+ },
+ {
+ after: 'preference',
+ kind: 'delete',
+ memoryType: 'preferences',
+ uri: 'viking://user/preferences',
+ },
+ ],
+ summary: { adds: 1, deletes: 1, updates: 0 },
+ },
+ {
+ archiveId: 'archive-2',
+ archiveUri: 'viking://session/archive-2',
+ extractedAt: '2026-07-26T01:00:00Z',
+ operations: [
+ {
+ after: 'preference',
+ kind: 'update',
+ memoryType: 'preferences',
+ uri: 'viking://user/preferences/second',
+ },
+ ],
+ summary: { adds: 0, deletes: 0, updates: 1 },
+ },
+]
+
+describe('MemoryImpact', () => {
+ it('filters archives and recomputes per-archive counts by memory type', () => {
+ useSessionMemoryDiffsMock.mockReturnValue({
+ data: diffs,
+ isError: false,
+ isLoading: false,
+ refetch: vi.fn(),
+ })
+
+ render(
+ <MemoryImpact session={{ commit_count: 2 } as unknown as SessionMeta} />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'impact.open' }))
+ fireEvent.click(screen.getByRole('tab', { name: 'profile' }))
+
+ const visibleArchive = screen.getByText('archive-1').closest('section')
+ expect(visibleArchive?.textContent).toContain('+1')
+ expect(visibleArchive?.textContent).not.toContain('−1')
+ expect(screen.queryByText('archive-2')).toBeNull()
+ })
+})
diff --git a/web-studio/src/routes/sessions/-components/memory-impact.tsx b/web-studio/src/routes/sessions/-components/memory-impact.tsx
index 05e8471e8..6f12446b2 100644
--- a/web-studio/src/routes/sessions/-components/memory-impact.tsx
+++ b/web-studio/src/routes/sessions/-components/memory-impact.tsx
@@ -27,6 +27,8 @@ interface MemoryImpactProps {
session?: SessionMeta
}
+const ALL_MEMORY_TYPES = 'all'
+
const KIND_STYLES: Record<
MemoryDiffKind,
{ icon: typeof FilePlus2Icon; text: string }
@@ -48,6 +50,7 @@ const KIND_STYLES: Record<
export function MemoryImpact({ session }: MemoryImpactProps) {
const { i18n, t } = useTranslation('sessions')
const [open, setOpen] = useState(false)
+ const [memoryType, setMemoryType] = useState(ALL_MEMORY_TYPES)
const diffsQuery = useSessionMemoryDiffs(session, open)
const diffs = diffsQuery.data ?? []
const totals = useMemo(
@@ -63,6 +66,41 @@ export function MemoryImpact({ session }: MemoryImpactProps) {
[diffs],
)
const totalChanges = totals.adds + totals.updates + totals.deletes
+ const memoryTypes = useMemo(
+ () =>
+ Array.from(
+ new Set(
+ diffs.flatMap((diff) =>
+ diff.operations.map((operation) => operation.memoryType),
+ ),
+ ),
+ ).sort(),
+ [diffs],
+ )
+ const activeMemoryType = memoryTypes.includes(memoryType)
+ ? memoryType
+ : ALL_MEMORY_TYPES
+ const visibleDiffs = useMemo(
+ () =>
+ diffs.flatMap((diff) => {
+ const operations =
+ activeMemoryType === ALL_MEMORY_TYPES
+ ? diff.operations
+ : diff.operations.filter(
+ (operation) => operation.memoryType === activeMemoryType,
+ )
+ return operations.length > 0
+ ? [
+ {
+ ...diff,
+ operations,
+ summary: summarizeOperations(operations),
+ },
+ ]
+ : []
+ }),
+ [activeMemoryType, diffs],
+ )
if (!session || session.commit_count <= 0) return null
@@ -81,7 +119,7 @@ export function MemoryImpact({ session }: MemoryImpactProps) {
</Button>
<Sheet open={open} onOpenChange={setOpen}>
- <SheetContent className="gap-0 sm:max-w-2xl">
+ <SheetContent className="gap-0 data-[side=right]:sm:max-w-3xl">
<SheetHeader className="border-b px-6 py-5">
<div className="flex items-center gap-3 pr-10">
<div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary ring-1 ring-primary/15">
@@ -140,9 +178,28 @@ export function MemoryImpact({ session }: MemoryImpactProps) {
/>
</div>
+ <div
+ aria-label={t('impact.filterByType')}
+ className="flex gap-1 overflow-x-auto border-b px-6 py-3"
+ role="tablist"
+ >
+ {[ALL_MEMORY_TYPES, ...memoryTypes].map((type) => (
+ <Button
+ aria-selected={activeMemoryType === type}
+ key={type}
+ onClick={() => setMemoryType(type)}
+ role="tab"
+ size="xs"
+ variant={activeMemoryType === type ? 'secondary' : 'ghost'}
+ >
+ {type === ALL_MEMORY_TYPES ? t('impact.allTypes') : type}
+ </Button>
+ ))}
+ </div>
+
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
<div className="space-y-6">
- {diffs.map((diff) => (
+ {visibleDiffs.map((diff) => (
<section key={diff.archiveId} className="space-y-2.5">
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2">
@@ -181,6 +238,18 @@ export function MemoryImpact({ session }: MemoryImpactProps) {
)
}
+function summarizeOperations(operations: SessionMemoryDiffOperation[]) {
+ return operations.reduce(
+ (summary, operation) => {
+ if (operation.kind === 'add') summary.adds += 1
+ if (operation.kind === 'update') summary.updates += 1
+ if (operation.kind === 'delete') summary.deletes += 1
+ return summary
+ },
+ { adds: 0, deletes: 0, updates: 0 },
+ )
+}
+
function ImpactCounts({
totals,
}: {
diff --git a/web-studio/src/routes/sessions/-components/message-list.test.tsx b/web-studio/src/routes/sessions/-components/message-list.test.tsx
new file mode 100644
index 000000000..ec77ef034
--- /dev/null
+++ b/web-studio/src/routes/sessions/-components/message-list.test.tsx
@@ -0,0 +1,122 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import type { MessagePart } from '#/lib/sessions/types/message'
+import { MessageList } from './message-list'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+afterEach(cleanup)
+
+const toolParts: MessagePart[] = [
+ {
+ type: 'tool',
+ tool_id: 'tool-1',
+ tool_name: 'auto_memory_search',
+ tool_uri: '',
+ skill_uri: '',
+ tool_status: 'completed',
+ tool_input: { query: 'hello' },
+ tool_output: 'result',
+ },
+ {
+ type: 'tool_result',
+ tool_id: 'tool-1',
+ tool_name: 'auto_memory_search',
+ tool_output: 'result',
+ is_error: false,
+ },
+]
+
+describe('MessageList tool calls', () => {
+ it.each([
+ { state: 'completed', status: 'completed', isOpen: false },
+ { state: 'streaming', status: 'running', isOpen: true },
+ ] as const)(
+ 'merges tool input and result into one disclosure for $state messages',
+ ({ state, status, isOpen }) => {
+ const parts = toolParts.map((part) =>
+ part.type === 'tool' ? { ...part, tool_status: status } : part,
+ )
+
+ render(
+ <MessageList
+ messages={
+ state === 'completed'
+ ? [
+ {
+ id: 'message-1',
+ role: 'assistant',
+ parts,
+ created_at: new Date().toISOString(),
+ },
+ ]
+ : []
+ }
+ streaming={
+ state === 'streaming' ? { iteration: 1, parts } : undefined
+ }
+ />,
+ )
+
+ const toolName = screen.getByText('auto_memory_search')
+ expect(screen.getAllByText('auto_memory_search')).toHaveLength(1)
+ expect(toolName.closest('details')).toHaveProperty('open', isOpen)
+ expect(toolName.closest('details')?.className).toContain('group/tool')
+ expect(screen.getByText(/"query": "hello"/)).toBeTruthy()
+ expect(screen.getByText('result')).toBeTruthy()
+ },
+ )
+})
+
+describe('MessageList reasoning', () => {
+ it.each([
+ { isRunning: false, label: 'chat.reasoning' },
+ { isRunning: true, label: 'chat.thinking' },
+ ])('renders $label as a lightweight disclosure', ({ isRunning, label }) => {
+ render(
+ <MessageList
+ messages={
+ isRunning
+ ? []
+ : [
+ {
+ id: 'message-1',
+ role: 'assistant',
+ parts: [
+ {
+ type: 'reasoning',
+ reasoning: 'Inspect the relevant memories.',
+ is_running: false,
+ },
+ ],
+ created_at: new Date().toISOString(),
+ },
+ ]
+ }
+ streaming={
+ isRunning
+ ? {
+ iteration: 1,
+ parts: [
+ {
+ type: 'reasoning',
+ reasoning: 'Inspect the relevant memories.',
+ is_running: true,
+ },
+ ],
+ }
+ : undefined
+ }
+ />,
+ )
+
+ const details = screen.getByText(label).closest('details')
+ expect(details).toHaveProperty('open', isRunning)
+ expect(details?.className).toContain('group/reasoning')
+ })
+})
diff --git a/web-studio/src/routes/sessions/-components/message-list.tsx b/web-studio/src/routes/sessions/-components/message-list.tsx
index 49bcdae3d..6b74983b2 100644
--- a/web-studio/src/routes/sessions/-components/message-list.tsx
+++ b/web-studio/src/routes/sessions/-components/message-list.tsx
@@ -4,8 +4,18 @@ import { CheckIcon, CopyIcon, UserIcon } from 'lucide-react'
import type { TFunction } from 'i18next'
import { resolvePublicAsset } from '#/lib/public-path'
-import type { Message, MessagePart, ToolPart } from '#/lib/sessions/types/message'
-import { MarkdownContent, ReasoningBlock, ToolCallBlock } from './message-parts'
+import type {
+ Message,
+ MessagePart,
+ ToolPart,
+ ToolResultPart,
+} from '#/lib/sessions/types/message'
+import {
+ IterationDivider,
+ MarkdownContent,
+ ReasoningBlock,
+ ToolCallBlock,
+} from './message-parts'
const OPENVIKING_ICON_SRC = resolvePublicAsset('favicon-32.png')
@@ -48,6 +58,14 @@ function getTextFromParts(message: Message): string {
.join('\n')
}
+function getToolResultsById(parts: MessagePart[]): Map<string, ToolResultPart> {
+ return new Map(
+ parts
+ .filter((part): part is ToolResultPart => part.type === 'tool_result')
+ .map((part) => [part.tool_id, part]),
+ )
+}
+
function stripPlaygroundContextSuffix(text: string): string {
return text
.replace(/\n\n当前选中的上下文资源:\s*viking:\/\/[\s\S]*$/u, '')
@@ -92,7 +110,9 @@ function TypingIndicator() {
function BotAvatar({ compact }: { compact?: boolean }) {
const sizeClass = compact ? 'size-6' : 'size-7'
return (
- <div className={`flex ${sizeClass} shrink-0 items-center justify-center rounded-full ring-1 ring-border/20 overflow-hidden`}>
+ <div
+ className={`flex ${sizeClass} shrink-0 items-center justify-center rounded-full ring-1 ring-border/20 overflow-hidden`}
+ >
<img src={OPENVIKING_ICON_SRC} alt="OpenViking" className={sizeClass} />
</div>
)
@@ -171,7 +191,7 @@ const UserMessage = memo(function UserMessage({
return (
<div
- className={`${expanded ? 'w-full' : 'w-full max-w-3xl'} group/msg flex gap-2 justify-end ${compact ? 'mb-1.5' : 'mb-5'}`}
+ className={`${expanded ? 'w-full' : 'w-full max-w-[clamp(48rem,68vw,72rem)]'} group/msg flex gap-2 justify-end ${compact ? 'mb-1.5' : 'mb-5'}`}
>
<div className="flex items-end gap-1.5 self-end opacity-0 transition-opacity group-hover/msg:opacity-100">
<span className="text-[10px] text-muted-foreground/40 opacity-0 transition-opacity group-hover/msg:opacity-100 select-none">
@@ -179,7 +199,11 @@ const UserMessage = memo(function UserMessage({
</span>
<CopyButton text={text} />
</div>
- <div className={expanded ? 'max-w-[88%] space-y-1.5' : 'max-w-[75%] space-y-1.5'}>
+ <div
+ className={
+ expanded ? 'max-w-[88%] space-y-1.5' : 'max-w-[75%] space-y-1.5'
+ }
+ >
{text && (
<div className="whitespace-pre-wrap rounded-2xl rounded-tr-sm border border-border/70 bg-muted/70 px-4 py-2.5 text-sm leading-6 text-foreground shadow-sm">
{text}
@@ -213,13 +237,18 @@ const AssistantMessage = memo(function AssistantMessage({
}) {
const { t } = useTranslation('sessions')
const textContent = getTextFromParts(message)
+ const toolResultsById = getToolResultsById(message.parts)
return (
<div
- className={`${expanded ? 'w-full' : 'w-full max-w-3xl'} group/msg flex gap-2 items-start ${compact ? 'mb-1.5' : 'mb-5'}`}
+ className={`${expanded ? 'w-full' : 'w-full max-w-[clamp(48rem,68vw,72rem)]'} group/msg flex gap-2 items-start ${compact ? 'mb-1.5' : 'mb-5'}`}
>
- {!compact ? <BotAvatar compact={expanded} /> : <div className="w-6 shrink-0" />}
- <div className="relative max-w-full min-w-0 flex-1 rounded-2xl rounded-tl-sm bg-background/95 px-4 py-3 text-sm shadow-sm ring-1 ring-border/30">
+ {!compact ? (
+ <BotAvatar compact={expanded} />
+ ) : (
+ <div className="w-6 shrink-0" />
+ )}
+ <div className="relative max-w-full min-w-0 flex-1 rounded-2xl rounded-tl-sm border border-border bg-muted/30 px-4 py-3 text-sm shadow-md shadow-black/5 dark:border-white/10 dark:bg-card/95 dark:shadow-black/30">
{(Array.isArray(message.parts) ? message.parts : []).map((part, i) => {
switch (part.type) {
case 'text':
@@ -232,18 +261,24 @@ const AssistantMessage = memo(function AssistantMessage({
isRunning={false}
/>
)
- case 'tool':
+ case 'iteration':
+ return <IterationDivider key={i} iteration={part.iteration} />
+ case 'tool': {
+ const toolResult = toolResultsById.get(part.tool_id)
return (
<ToolCallBlock
key={i}
toolName={part.tool_name}
args={part.tool_input}
- result={part.tool_output}
- isError={part.tool_status === 'error'}
+ result={toolResult?.tool_output ?? part.tool_output}
+ isError={toolResult?.is_error ?? part.tool_status === 'error'}
isRunning={false}
onResourceClick={onResourceClick}
/>
)
+ }
+ case 'tool_result':
+ return null
case 'context':
return null
}
@@ -266,35 +301,27 @@ const AssistantMessage = memo(function AssistantMessage({
function StreamingAssistantMessage({
expanded,
parts = [],
- iteration,
onResourceClick,
}: {
expanded?: boolean
parts?: MessagePart[]
- iteration: number
onResourceClick?: (uri: string) => void
}) {
- const { t } = useTranslation('sessions')
const safeParts = Array.isArray(parts) ? parts : []
const hasContent = safeParts.length > 0
+ const toolResultsById = getToolResultsById(safeParts)
return (
- <div className={`${expanded ? 'w-full' : 'w-full max-w-3xl'} mb-5 flex gap-2 items-start`}>
+ <div
+ className={`${expanded ? 'w-full' : 'w-full max-w-[clamp(48rem,68vw,72rem)]'} mb-5 flex gap-2 items-start`}
+ >
<BotAvatar compact={expanded} />
- <div className="max-w-full min-w-0 flex-1 rounded-2xl rounded-tl-sm bg-background/95 px-4 py-3 text-sm shadow-sm ring-1 ring-border/30">
- {iteration > 1 && (
- <div className="mb-2">
- <span className="inline-flex items-center rounded-full bg-primary/10 px-2.5 py-0.5 text-[11px] font-medium text-primary">
- {t('chat.iteration', { count: iteration })}
- </span>
- </div>
+ <div className="max-w-full min-w-0 flex-1 rounded-2xl rounded-tl-sm border border-border bg-muted/30 px-4 py-3 text-sm shadow-md shadow-black/5 dark:border-white/10 dark:bg-card/95 dark:shadow-black/30">
+ {safeParts.map((part, i) =>
+ renderStreamingPart(part, i, toolResultsById, onResourceClick),
)}
- {safeParts.map((part, i) => renderStreamingPart(part, i, onResourceClick))}
-
- {!hasContent ? (
- <TypingIndicator />
- ) : null}
+ {!hasContent ? <TypingIndicator /> : null}
</div>
</div>
)
@@ -303,6 +330,7 @@ function StreamingAssistantMessage({
function renderStreamingPart(
part: MessagePart,
index: number,
+ toolResultsById: Map<string, ToolResultPart>,
onResourceClick?: (uri: string) => void,
) {
switch (part.type) {
@@ -314,14 +342,19 @@ function renderStreamingPart(
isRunning={part.is_running ?? true}
/>
)
+ case 'iteration':
+ return <IterationDivider key={index} iteration={part.iteration} />
case 'tool':
return (
<StreamingToolPart
key={index}
part={part}
+ result={toolResultsById.get(part.tool_id)}
onResourceClick={onResourceClick}
/>
)
+ case 'tool_result':
+ return null
case 'text':
return <MarkdownContent key={index} content={part.text} isStreaming />
case 'context':
@@ -331,18 +364,22 @@ function renderStreamingPart(
function StreamingToolPart({
part,
+ result,
onResourceClick,
}: {
part: ToolPart
+ result?: ToolResultPart
onResourceClick?: (uri: string) => void
}) {
return (
<ToolCallBlock
toolName={part.tool_name}
args={part.tool_input}
- result={part.tool_output}
- isError={part.tool_status === 'error'}
- isRunning={part.tool_status === 'running' || part.tool_status === 'pending'}
+ result={result?.tool_output ?? part.tool_output}
+ isError={result?.is_error ?? part.tool_status === 'error'}
+ isRunning={
+ part.tool_status === 'running' || part.tool_status === 'pending'
+ }
onResourceClick={onResourceClick}
/>
)
diff --git a/web-studio/src/routes/sessions/-components/message-parts.tsx b/web-studio/src/routes/sessions/-components/message-parts.tsx
index 0dec044e8..e6c331928 100644
--- a/web-studio/src/routes/sessions/-components/message-parts.tsx
+++ b/web-studio/src/routes/sessions/-components/message-parts.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next'
import {
CheckCircle2Icon,
ChevronDownIcon,
+ ChevronRightIcon,
CircleAlertIcon,
FileTextIcon,
LoaderIcon,
@@ -84,21 +85,35 @@ export function ReasoningBlock({ reasoning, isRunning }: ReasoningBlockProps) {
if (!reasoning) return null
return (
- <details
- className="mb-3 rounded-lg border border-border/30 bg-muted/20"
- open={isRunning}
- >
- <summary className="flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs font-medium text-muted-foreground select-none">
- {isRunning && <LoaderIcon className="size-3 animate-spin" />}
+ <details className="group/reasoning mb-3" open={isRunning}>
+ <summary className="flex w-fit cursor-pointer list-none items-center gap-1.5 rounded-md px-1 py-1 text-xs font-medium text-muted-foreground/70 transition-colors hover:bg-muted/50 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 select-none [&::-webkit-details-marker]:hidden">
+ <ChevronRightIcon className="size-3.5 transition-transform duration-200 group-open/reasoning:rotate-90 motion-reduce:transition-none" />
+ {isRunning && (
+ <LoaderIcon className="size-3 animate-spin motion-reduce:animate-none" />
+ )}
<span>{isRunning ? t('chat.thinking') : t('chat.reasoning')}</span>
</summary>
- <div className="border-t border-border/30 px-3 py-2 text-xs text-muted-foreground/80 leading-relaxed whitespace-pre-wrap">
+ <div className="ml-[7px] mt-1 border-l border-border/50 py-1 pl-4 text-[13px] leading-6 text-muted-foreground/75 whitespace-pre-wrap">
{reasoning}
</div>
</details>
)
}
+export function IterationDivider({ iteration }: { iteration: number }) {
+ const { t } = useTranslation('sessions')
+
+ return (
+ <div className="my-3 flex items-center gap-2 text-[11px] text-muted-foreground/70">
+ <span className="h-px flex-1 bg-border/40" />
+ <span className="rounded-full bg-muted/50 px-2 py-0.5 font-medium">
+ {t('chat.iteration', { count: iteration })}
+ </span>
+ <span className="h-px flex-1 bg-border/40" />
+ </div>
+ )
+}
+
// ---------------------------------------------------------------------------
// ToolCallBlock
// ---------------------------------------------------------------------------
@@ -131,10 +146,11 @@ export function ToolCallBlock({
}, [result])
return (
- <details className="my-2 rounded-lg border border-border/30 bg-muted/20">
- <summary className="flex cursor-pointer items-center gap-2 px-3 py-2 text-xs select-none">
+ <details className="group/tool my-2" open={isRunning}>
+ <summary className="flex w-full cursor-pointer list-none items-center gap-1.5 rounded-md px-1 py-1 text-xs text-muted-foreground/70 transition-colors hover:bg-muted/50 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 select-none [&::-webkit-details-marker]:hidden">
+ <ChevronRightIcon className="size-3.5 shrink-0 transition-transform duration-200 group-open/tool:rotate-90 motion-reduce:transition-none" />
<ToolStatusIcon isRunning={isRunning} isError={isError} />
- <WrenchIcon className="size-3 text-muted-foreground/60" />
+ <WrenchIcon className="size-3 shrink-0 text-muted-foreground/60" />
<span className="font-mono font-medium text-foreground/80">
{toolName}
</span>
@@ -146,26 +162,26 @@ export function ToolCallBlock({
: t('chat.toolStatus.completed')}
</span>
</summary>
- <div className="space-y-2 border-t border-border/30 px-3 py-2">
+ <div className="ml-[7px] mt-1 space-y-3 border-l border-border/50 py-1 pl-4">
{args && Object.keys(args).length > 0 && (
<div>
- <div className="mb-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/50">
+ <div className="mb-1.5 text-[11px] font-medium text-muted-foreground/60">
{t('chat.toolInput')}
</div>
- <pre className="overflow-x-auto rounded-md bg-muted/50 p-2 text-xs leading-relaxed">
+ <pre className="overflow-x-auto rounded-md bg-muted/40 p-2.5 text-xs leading-relaxed">
{JSON.stringify(args, null, 2)}
</pre>
</div>
)}
{result !== undefined && (
<div>
- <div className="mb-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/50">
+ <div className="mb-1.5 text-[11px] font-medium text-muted-foreground/60">
{t('chat.toolResult')}
</div>
<pre
className={cn(
- 'max-h-48 overflow-x-auto overflow-y-auto rounded-md p-2 text-xs leading-relaxed',
- isError ? 'bg-destructive/10 text-destructive' : 'bg-muted/50',
+ 'max-h-48 overflow-x-auto overflow-y-auto rounded-md p-2.5 text-xs leading-relaxed',
+ isError ? 'bg-destructive/10 text-destructive' : 'bg-muted/40',
)}
>
{result}
@@ -217,7 +233,9 @@ function ToolStatusIcon({
isError?: boolean
}) {
if (isRunning)
- return <LoaderIcon className="size-3 animate-spin text-muted-foreground" />
+ return (
+ <LoaderIcon className="size-3 animate-spin text-muted-foreground motion-reduce:animate-none" />
+ )
if (isError) return <CircleAlertIcon className="size-3 text-destructive" />
return <CheckCircle2Icon className="size-3 text-primary/70" />
}