Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(webui): support to set fallback model in web UI (#1699)
DavdGao4725df77381c
diff --git a/examples/web_ui/frontend/package.json b/examples/web_ui/frontend/package.jsonindex 7b9d191a5..dda64f21e 100644--- a/examples/web_ui/frontend/package.json+++ b/examples/web_ui/frontend/package.json@@ -11,7 +11,7 @@"preview": "vite preview"},"dependencies": {- "@agentscope-ai/agentscope": "^0.0.5",+ "@agentscope-ai/agentscope": "^0.0.6","@fontsource-variable/geist": "^5.2.8","@tailwindcss/vite": "^4.3.0","class-variance-authority": "^0.7.1",@@ -35,6 +35,7 @@"react-router-dom": "^7.15.1","remark-gfm": "^4.0.1","shadcn": "^4.7.0",+ "shadcn-prose": "^1.2.1","sonner": "^2.0.7","tailwind-merge": "^3.6.0","tailwindcss": "^4.3.0",@@ -43,6 +44,7 @@},"devDependencies": {"@eslint/js": "^10.0.1",+ "@tailwindcss/typography": "^0.5.19","@types/mime-types": "^3.0.1","@types/node": "^24.12.3","@types/react": "^19.2.14",diff --git a/examples/web_ui/frontend/src/App.css b/examples/web_ui/frontend/src/App.cssdeleted file mode 100644index 5a05fcc70..000000000--- a/examples/web_ui/frontend/src/App.css+++ /dev/null@@ -1,145 +0,0 @@-.counter {- font-size: 16px;- padding: 5px 10px;- border-radius: 5px;- color: var(--accent);- background: var(--accent-bg);- border: 2px solid transparent;- transition: border-color 0.3s;- margin-bottom: 24px;-- &:hover {- border-color: var(--accent-border);- }- &:focus-visible {- outline: 2px solid var(--accent);- outline-offset: 2px;- }-}--#center {- display: flex;- flex-direction: column;- gap: 25px;- place-content: center;- place-items: center;- flex-grow: 1;-- @media (max-width: 1024px) {- padding: 32px 20px 24px;- gap: 18px;- }-}--#next-steps {- display: flex;- border-top: 1px solid var(--border);- text-align: left;-- & > div {- flex: 1 1 0;- padding: 32px;- @media (max-width: 1024px) {- padding: 24px 20px;- }- }-- .icon {- margin-bottom: 16px;- width: 22px;- height: 22px;- }-- @media (max-width: 1024px) {- flex-direction: column;- text-align: center;- }-}--#docs {- border-right: 1px solid var(--border);-- @media (max-width: 1024px) {- border-right: none;- border-bottom: 1px solid var(--border);- }-}--#next-steps ul {- list-style: none;- padding: 0;- display: flex;- gap: 8px;- margin: 32px 0 0;-- .logo {- height: 18px;- }-- a {- color: var(--text-h);- font-size: 16px;- border-radius: 6px;- background: var(--social-bg);- display: flex;- padding: 6px 12px;- align-items: center;- gap: 8px;- text-decoration: none;- transition: box-shadow 0.3s;-- &:hover {- box-shadow: var(--shadow);- }- .button-icon {- height: 18px;- width: 18px;- }- }-- @media (max-width: 1024px) {- margin-top: 20px;- flex-wrap: wrap;- justify-content: center;-- li {- flex: 1 1 calc(50% - 8px);- }-- a {- width: 100%;- justify-content: center;- box-sizing: border-box;- }- }-}--#spacer {- height: 88px;- border-top: 1px solid var(--border);- @media (max-width: 1024px) {- height: 48px;- }-}--.ticks {- position: relative;- width: 100%;-- &::before,- &::after {- content: '';- position: absolute;- top: -4.5px;- border: 5px solid transparent;- }-- &::before {- left: 0;- border-left-color: var(--border);- }- &::after {- right: 0;- border-right-color: var(--border);- }-}diff --git a/examples/web_ui/frontend/src/api/agent.ts b/examples/web_ui/frontend/src/api/agent.tsindex 86036631d..30a6f6faf 100644--- a/examples/web_ui/frontend/src/api/agent.ts+++ b/examples/web_ui/frontend/src/api/agent.ts@@ -2,6 +2,7 @@ import { client } from './client';import type {AgentListResponse,AgentRecord,+ AgentSchemaResponse,CreateAgentRequest,CreateAgentResponse,UpdateAgentRequest,@@ -10,6 +11,8 @@ import type {export const agentApi = {list: () => client.get<AgentListResponse>('/agent/'),+ getSchema: () => client.get<AgentSchemaResponse>('/agent/schema'),+create: (body: CreateAgentRequest) => client.post<CreateAgentResponse>('/agent/', body),update: (agentId: string, body: UpdateAgentRequest) =>diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.tsindex 2b69405b7..8496d49b4 100644--- a/examples/web_ui/frontend/src/api/types.ts+++ b/examples/web_ui/frontend/src/api/types.ts@@ -64,6 +64,17 @@ export interface AgentListResponse {total: number;}+/**+ * JSON Schema fragments returned by `GET /agent/schema`. Each fragment is a+ * self-contained JSON Schema object (no `$ref`s across fragments) covering+ * one section of the agent create / edit form.+ */+export interface AgentSchemaResponse {+ identity: JSONSchema;+ context_config: JSONSchema;+ react_config: JSONSchema;+}+// ─── Session ──────────────────────────────────────────────────────────────────export type SessionSource = 'user' | 'schedule';@@ -71,6 +82,8 @@ export type SessionSource = 'user' | 'schedule';export interface SessionConfig {name: string;chat_model_config: ChatModelConfig;+ /** Fallback model used when the primary model fails. */+ fallback_chat_model_config: ChatModelConfig | null;workspace_id: string;}@@ -90,6 +103,8 @@ export interface CreateSessionRequest {agent_id: string;workspace_id?: string;chat_model_config?: ChatModelConfig | null;+ /** Optional fallback model. Omit (or pass null) for no fallback. */+ fallback_chat_model_config?: ChatModelConfig | null;}export interface CreateSessionResponse {@@ -99,6 +114,13 @@ export interface CreateSessionResponse {export interface UpdateSessionRequest {name?: string;chat_model_config?: ChatModelConfig;+ /**+ * New fallback model. PATCH semantics:+ * - omit the field → leave unchanged+ * - set to `null` → clear the existing fallback+ * - set to a value → replace the existing fallback+ */+ fallback_chat_model_config?: ChatModelConfig | null;permission_mode?: PermissionMode;}@@ -107,9 +129,14 @@ export interface SessionListResponse {total: number;}-// ─── Credential ───────────────────────────────────────────────────────────────+// ─── JSON Schema ──────────────────────────────────────────────────────────────-export interface CredentialSchemaProperty {+/**+ * Subset of JSON Schema property fields the frontend renders. Sourced from+ * Pydantic's `model_json_schema()` output, including the `format: textarea`+ * hint we add via `json_schema_extra` for multi-line strings.+ */+export interface JSONSchemaProperty {type?: string;format?: string;description?: string;@@ -118,13 +145,29 @@ export interface CredentialSchemaProperty {anyOf?: Array<{ type: string }>;title?: string;writeOnly?: boolean;+ minimum?: number;+ maximum?: number;+ exclusiveMinimum?: number;+ exclusiveMaximum?: number;+}++export interface JSONSchema {+ title?: string;+ type?: string;+ properties: Record<string, JSONSchemaProperty>;+ required?: string[];}-export interface CredentialSchema {+// ─── Credential ───────────────────────────────────────────────────────────────++export type CredentialSchemaProperty = JSONSchemaProperty;++// Credential schemas always include title + type (Pydantic always emits them+// for credential data classes); we narrow the generic JSONSchema here so call+// sites that read `schema.title` don't have to do null-checks.+export interface CredentialSchema extends JSONSchema {title: string;type: string;- properties: Record<string, CredentialSchemaProperty>;- required?: string[];}export interface CredentialSchemasResponse {diff --git a/examples/web_ui/frontend/src/components/chat/ConfirmCard.tsx b/examples/web_ui/frontend/src/components/chat/ConfirmCard.tsxindex b7ee0b592..dd1bfcfe4 100644--- a/examples/web_ui/frontend/src/components/chat/ConfirmCard.tsx+++ b/examples/web_ui/frontend/src/components/chat/ConfirmCard.tsx@@ -52,7 +52,7 @@ export function ConfirmCard({}, [onUserConfirm, selected, options]);return (- <div className="ring ring-border rounded-xl w-full p-4 space-y-4 text-sm">+ <div className="ring ring-border rounded-xl w-full p-4 space-y-4 text-sm overflow-hidden"><div className="flex flex-col gap-y-2"><strong className="text-secondary-foreground">{getDisplayName(toolCall, t)}</strong><div className="px-4 py-2 bg-white rounded-sm">@@ -88,7 +88,7 @@ export function ConfirmCard({{hasSuggestedRules && (<ButtonclassName={cn(- 'flex justify-start cursor-pointer',+ 'flex flex-wrap justify-start items-start cursor-pointer h-auto text-left',selected === 'yes_with_rule' ? 'text-primary' : 'text-muted-foreground',)}size="sm"@@ -100,26 +100,26 @@ export function ConfirmCard({onUserConfirm(true, [toolCall.suggested_rules![0]]);}}>- <ChevronRight- className={cn(- 'size-4',- selected === 'yes_with_rule' ? 'visible' : 'invisible',- )}- />- 2.{' '}- {t('confirmCard.yesWithRule', {- toolName: toolCall.suggested_rules![0].tool_name,- ruleContent: toolCall.suggested_rules![0].rule_content,- })}- <div- className={cn(- selected === 'yes_with_rule'- ? 'text-muted-foreground'- : 'invisible',- )}- >- (<Kbd>Enter</Kbd> {t('confirmCard.toConfirm')})- </div>+ <span className="flex items-start gap-1 w-full break-words whitespace-normal min-w-0">+ <ChevronRight+ className={cn(+ 'size-4 shrink-0 mt-0.5',+ selected === 'yes_with_rule' ? 'visible' : 'invisible',+ )}+ />+ <span className="break-words min-w-0">+ 2.{' '}+ {t('confirmCard.yesWithRule', {+ toolName: toolCall.suggested_rules![0].tool_name,+ ruleContent: toolCall.suggested_rules![0].rule_content,+ })}+ {selected === 'yes_with_rule' && (+ <span className="text-muted-foreground ml-1 whitespace-nowrap">+ (<Kbd>Enter</Kbd> {t('confirmCard.toConfirm')})+ </span>+ )}+ </span>+ </span></Button>)}<Buttondiff --git a/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx b/examples/web_ui/frontend/src/components/chat/MessageBubble.tsxindex 28e18119d..6da38abfd 100644--- a/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx+++ b/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx@@ -1,346 +1,128 @@-import type {- ContentBlock,- Msg,- ToolCallBlock,- ToolResultBlock,-} from '@agentscope-ai/agentscope/message';-import { ArrowDown, ArrowUp, Circle, Copy } from 'lucide-react';-import type { ReactNode } from 'react';+import type { ContentBlock, Msg, ToolCallBlock } from '@agentscope-ai/agentscope/message';+import { ArrowDown, ArrowUp, CheckCircle, Copy, Loader2 } from 'lucide-react';+import { useEffect, useState } from 'react';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';import { ConfirmCard } from './ConfirmCard';-import { getDisplayName, renderCallArgs, renderResult } from './tool-renderers';-import lineCornerSvg from '@/assets/images/line-corner.svg';-import lineVerticalSvg from '@/assets/images/line-vertical.svg';+import { renderToolGroup } from './tool-renderers';+import type { TFunction, ToolCallWithResult } from './tool-renderers/types';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { useTranslation } from '@/i18n/useI18n';-import { formatNumber } from '@/utils/common';+import { formatNumber, formatTime } from '@/utils/common';-// Tool call group, containing multiple tool_call and tool_result pairsinterface ToolCallGroupBlock {type: 'tool_call_group';id: string;- groupType: 'read_group' | 'glob_group' | 'grep_group' | 'tool_group';- calls: Array<{- call: ToolCallBlock;- result?: ToolResultBlock;- }>;+ toolName: string;+ calls: ToolCallWithResult[];}-// Extend ContentBlock type to include ToolCallGroupBlocktype ExtendedContentBlock = ContentBlock | ToolCallGroupBlock;/**- * Combine adjacent tool_call and tool_result in message content into tool_call_group- * Consecutive Read/Glob/Grep tools will be grouped into their respective groups- * Other tools will be mixed into tool_group- * @param content- * @returns The processed content with tool calls grouped together for better rendering.+ * Group consecutive tool_call blocks of the same name into a single+ * `tool_call_group`. tool_result blocks are matched by id back onto the+ * call inside the current group. Any non-tool block (or a tool_call with+ * a different name) flushes the current group.*/function groupToolCalls(content: ContentBlock[]): ExtendedContentBlock[] {const result: ExtendedContentBlock[] = [];- let currentGroup: Array<{ call: ToolCallBlock; result?: ToolResultBlock }> = [];- let currentGroupType: 'read_group' | 'glob_group' | 'grep_group' | 'tool_group' | null = null;+ let currentGroup: ToolCallWithResult[] = [];+ let currentToolName: string | null = null;- const getGroupType = (- toolName: string,- ): 'read_group' | 'glob_group' | 'grep_group' | 'tool_group' => {- if (toolName === 'Read') return 'read_group';- if (toolName === 'Glob') return 'glob_group';- if (toolName === 'Grep') return 'grep_group';- return 'tool_group';- };-- const flushCurrentGroup = () => {- if (currentGroup.length > 0 && currentGroupType) {+ const flush = () => {+ if (currentGroup.length > 0 && currentToolName) {result.push({type: 'tool_call_group',id: crypto.randomUUID(),- groupType: currentGroupType,+ toolName: currentToolName,calls: currentGroup,});currentGroup = [];- currentGroupType = null;+ currentToolName = null;}};for (const block of content) {if (block.type === 'tool_call') {- const toolGroupType = getGroupType(block.name);-- // If it's Read/Glob/Grep and the group type is different from the current one, start a new group- if (toolGroupType !== 'tool_group' && currentGroupType !== toolGroupType) {- flushCurrentGroup();- currentGroupType = toolGroupType;- } else if (toolGroupType === 'tool_group' && currentGroupType !== 'tool_group') {- // If it's another tool and the current group is not tool_group, start a new group- flushCurrentGroup();- currentGroupType = 'tool_group';- } else if (!currentGroupType) {- // If there's no current group yet, set the group type- currentGroupType = toolGroupType;+ if (currentToolName !== null && currentToolName !== block.name) {+ flush();}-- // Collect tool_call+ currentToolName = block.name;currentGroup.push({ call: block });} else if (block.type === 'tool_result') {- // Find the corresponding tool_call and add resultconst matchingCall = currentGroup.find((item) => item.call.id === block.id);if (matchingCall) {matchingCall.result = block;} else {- // If no corresponding call is found, create a new group (this should not happen in theory)+ // No matching call in the current group — emit a synthetic group+ // so the result still renders. Should not happen in practice.+ flush();+ currentToolName = block.name;currentGroup.push({call: {type: 'tool_call',id: block.id,name: block.name,input: '',- state: 'pending',+ state: 'finished',},result: block,});+ flush();}} else {- // When encountering a non-tool_call/tool_result block, end the current group- flushCurrentGroup();+ flush();result.push(block);}}- // Process the last group- flushCurrentGroup();-+ flush();return result;}/**- * Get the appropriate line connector image based on position in a list.- * @param index - The current item index- * @param total - The total number of items- * @returns The appropriate line connector image (corner or vertical)- */-function getLineImage(index: number, total: number): string {- return index === total - 1 ? lineCornerSvg : lineVerticalSvg;-}--/**- * The ToolStateIcon component renders an icon representing the state of a tool call based on its states.- * @param root0- * @param root0.states- * @returns A ReactNode representing the icon corresponding to the tool call state.- */-function ToolStateIcon({ states }: { states: (ToolResultBlock['state'] | undefined)[] }) {- // If any of the states is 'running' or any one is undefined- if (states.includes('running') || states.includes(undefined)) {- return (- <Circle className="size-2.5 text-muted-foreground fill-muted-foreground animate-pulse shrink-0" />- );- }-- // If all the states are 'success', show success;- if (states.every((state) => state === 'success')) {- return <Circle className="size-2.5 text-green-500 fill-green-500 shrink-0" />;- }-- // If any of the states is 'error', show error;- if (states.some((state) => state === 'error')) {- return <Circle className="size-2.5 text-red-500 fill-red-500 shrink-0" />;- }-- // if any of the states is 'interrupted', show interrupted;- if (states.some((state) => state === 'interrupted')) {- return <Circle className="size-2.5 text-yellow-500 fill-yellow-500 shrink-0" />;- }-- // Return a default icon if none of the above conditions are met- return <Circle className="size-2.5 text-muted-foreground fill-muted-foreground shrink-0" />;-}--/**- * Renders a grouped list of tool calls (Read / Glob / Grep) with a header and indented items.- * @param root0 - The component props- * @param root0.calls - Array of tool calls with their results- * @param root0.label - The label to display for the group- * @param root0.paramKey - The parameter key to extract from each call- * @param root0.inline - Whether to display items inline or stacked- * @returns A ReactNode representing the grouped tool call list- */-function ToolCallGroupList({- calls,- label,- inline,-}: {- calls: Array<{ call: ToolCallBlock; result?: ToolResultBlock }>;- label: ReactNode;- inline?: boolean;-}) {- return (- <div className="flex flex-col w-full">- <div className="flex flex-row gap-x-2 w-full max-w-full items-center">- <ToolStateIcon states={calls.map((item) => item.result?.state)} />- {label}- </div>- <div className={`flex ${inline ? 'flex-row' : 'flex-col'} gap-x-2 pl-6 max-w-full`}>- {calls.map((item, index) => (- <div- key={index}- className="flex flex-row gap-x-2 w-full max-w-full items-stretch"- >- <div className="flex-shrink-0 h-full items-center">- <img- src={getLineImage(index, calls.length)}- alt=""- className="w-3 h-full"- />- </div>- <div className="truncate flex-1 min-w-0 text-sm">- {renderCallArgs(item.call, () => '')}- </div>- </div>- ))}- </div>- </div>- );-}--/**- * The RenderToolCallGroup component renders a group of tool calls and their results in a structured format.- *- * @param root0- * @param root0.block- * @param root0.index- * @param root0.onUserConfirm- * @returns A ReactNode representing the rendered tool call group.- */-function ToolCallGroup({- block,- index,- onUserConfirm,-}: {- block: ToolCallGroupBlock;- index: number;- onUserConfirm?: (- toolCallBlock: ToolCallBlock,- confirm: boolean,- rules?: ToolCallBlock['suggested_rules'],- ) => void;-}): ReactNode {- const { t } = useTranslation();- if (block.calls.length === 0) return null;-- const firstNeedConfirm = block.calls.findIndex((item) => item.call.state === 'asking');-- const renderToolCalls =- firstNeedConfirm === -1 ? block.calls : block.calls.slice(0, firstNeedConfirm + 1);-- const elements: ReactNode[] = [];-- if (block.groupType === 'read_group') {- elements.push(- <ToolCallGroupList- key="read"- calls={renderToolCalls}- label={- <span className="text-sm">- <strong className="truncate text-primary">{t('tool.read.name')} </strong>- {t('tool.read.fileCount', { count: renderToolCalls.length })}- </span>- }- />,- );- } else if (block.groupType === 'glob_group' || block.groupType === 'grep_group') {- elements.push(- <ToolCallGroupList- key="search"- calls={renderToolCalls}- inline- label={- <strong className="truncate text-primary text-sm">- {block.groupType === 'glob_group'- ? t('tool.glob.name')- : t('tool.grep.name')}- </strong>- }- />,- );- } else {- for (const { call, result } of renderToolCalls) {- const displayName = getDisplayName(call, t);- const args = renderCallArgs(call, t);- const resultContent = result ? renderResult(call, result, t) : null;-- elements.push(- <div className="flex flex-col w-full max-w-full text-sm">- <div className="flex flex-row gap-x-2 w-full max-w-full items-center">- <ToolStateIcon states={[result?.state]} />- <span className="truncate">- <strong className="truncate text-primary">{displayName}</strong>- {args && <>({args})</>}- </span>- </div>- {resultContent && (- <div className="flex flex-row gap-x-2 pl-6 max-w-full">- <div className="flex-shrink-0">- <img src={lineCornerSvg} alt="" className="w-3 h-4" />- </div>- {resultContent}- </div>- )}- </div>,- );- }- }-- // Need to confirm- if (firstNeedConfirm !== -1) {- const { call } = block.calls[firstNeedConfirm];- elements.push(- <ConfirmCard- toolCall={call}- onUserConfirm={(confirm, rules) => {- if (onUserConfirm) onUserConfirm(call, confirm, rules);- }}- />,- );- }-- return (- <div key={index} className="flex flex-col gap-y-4 text-muted-foreground">- {elements}- </div>- );-}--/**- * Renders a content block based on its type.- *- * @param block - The content block to render.- * @param index - The index of the block in the content array.- * @param onUserConfirm- * @returns A React element representing the rendered block.+ * Render a single content block. Tool call groups are dispatched to+ * `renderToolGroup`; the per-group truncation at the first `asking` call+ * (and the trailing ConfirmCard) lives here so renderers only see a clean+ * list of calls.*/function renderBlock(block: ExtendedContentBlock,index: number,+ t: TFunction,onUserConfirm?: (toolCallBlock: ToolCallBlock,confirm: boolean,rules?: ToolCallBlock['suggested_rules'],) => void,- t?: (key: string) => string,) {switch (block.type) {- case 'tool_call_group':- return <ToolCallGroup block={block} index={index} onUserConfirm={onUserConfirm} />;+ case 'tool_call_group': {+ const firstAsk = block.calls.findIndex((item) => item.call.state === 'asking');+ const visible = firstAsk === -1 ? block.calls : block.calls.slice(0, firstAsk + 1);+ const askingCall = firstAsk === -1 ? null : block.calls[firstAsk].call;+ return (+ <div key={index} className="flex flex-col gap-y-4 text-muted-foreground">+ {renderToolGroup(block.toolName, visible, t)}+ {askingCall && (+ <ConfirmCard+ toolCall={askingCall}+ onUserConfirm={(confirm, rules) => {+ if (onUserConfirm) onUserConfirm(askingCall, confirm, rules);+ }}+ />+ )}+ </div>+ );+ }case 'text':return (- <div className="prose text-sm w-full min-w-full">+ <div key={index} className="prose text-sm w-full min-w-full"><ReactMarkdownremarkPlugins={[remarkGfm]}- // rehypePlugins={[rehypeRaw]}components={{code: ({ className, children, ...props }) => {const isInline = !String(className ?? '').startsWith('language-');@@ -386,7 +168,7 @@ function renderBlock(return (<details key={index} className="text-xs text-muted-foreground"><summary className="cursor-pointer select-none">- {t ? t('messageBubble.thinking') : 'Thinking'}+ {t('messageBubble.thinking')}</summary><p className="mt-1 whitespace-pre-wrap">{block.thinking}</p></details>@@ -402,11 +184,11 @@ function renderBlock(}switch (dataType) {case 'image':- return <img src={data} alt="Uploaded image" />;+ return <img key={index} src={data} alt="Uploaded image" />;case 'audio':- return <audio controls src={data} />;+ return <audio key={index} controls src={data} />;case 'video':- return <video controls src={data} />;+ return <video key={index} controls src={data} />;}return null;}@@ -428,55 +210,97 @@ interface MessageBubbleProps {/*** A message bubble component that displays a chat message.*- * @param root0 - The component props.- * @param root0.message - The message object to display.- * @param root0.onUserConfirm- * @returns A MessageBubble component.+ * Running state is derived from `message.finished_at`: a missing or null+ * `finished_at` means the agent is still producing this reply. The bottom+ * status row shows a single left-aligned badge laid out as+ * `[state-icon] [duration] [↑in ↓out]`:+ * - State icon: spinning `Loader2` while running, static `CheckCircle`+ * once finished.+ * - Duration is `now - created_at` while running (ticking each second),+ * `finished_at - created_at` once complete.+ * - Token counts only appear once `usage` is populated with non-zero+ * values — typically after the message finishes.+ *+ * When `content` is empty and the message is still running, the bubble+ * body is omitted entirely so only the bottom status row renders.*/export function MessageBubble({ message, onUserConfirm }: MessageBubbleProps) {const isUser = message.role === 'user';const { t } = useTranslation();- const renderContent = () => {- if (typeof message.content === 'string') {- return <p className="whitespace-pre-wrap">{message.content}</p>;- }- // Combine adjacent tool_call and tool_result into tool_call_group- const processedContent = groupToolCalls(message.content);- return processedContent.map((block, i) =>- renderBlock(- block,- i,- (- toolCall: ToolCallBlock,- confirm: boolean,- rules?: ToolCallBlock['suggested_rules'],- ) => {- onUserConfirm(toolCall, confirm, message.id, rules);- toolCall.state = confirm ? 'allowed' : 'finished';- // Remove confirmation UI while preserving denied state- },- t,- ),- );- };+ const isRunning = !message.finished_at;+ const hasUsage =+ !!message.usage &&+ ((message.usage.input_tokens ?? 0) > 0 || (message.usage.output_tokens ?? 0) > 0);++ // Tick once per second while running so the elapsed time updates live.+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!isRunning) return;+ const id = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(id);+ }, [isRunning]);++ const blocks = groupToolCalls(message.content);+ const showBody = blocks.length > 0;+ const showFooter = !isUser;++ const startMs = new Date(message.created_at).getTime();+ const endMs = isRunning ? now : new Date(message.finished_at!).getTime();+ const elapsedSeconds = Math.max(0, (endMs - startMs) / 1000);+ const elapsedText = formatTime(elapsedSeconds);return (<divclassName={`flex flex-col w-full max-w-full ${isUser ? 'items-end' : 'items-start'} mb-4`}>- <div- className={`p-4 rounded-xl space-y-2 max-w-full ${isUser ? 'w-fit bg-secondary' : 'w-full min-w-full'}`}- >- {renderContent()}- </div>- {isUser ? null : (- <div className="flex flex-row text-muted-foreground gap-x-4 px-2">- <Badge variant="secondary">- <ArrowUp data-icon="inline-start" />- {formatNumber(message.usage?.inputTokens || 0)}- <ArrowDown data-icon="inline-start" className="ml-1" />- {formatNumber(message.usage?.outputTokens || 0)}+ {showBody && (+ <div+ className={`p-4 rounded-xl space-y-2 max-w-full ${+ isUser ? 'w-fit bg-secondary' : 'w-full min-w-full'+ }`}+ >+ {blocks.map((block, i) =>+ renderBlock(+ block,+ i,+ t,+ (+ toolCall: ToolCallBlock,+ confirm: boolean,+ rules?: ToolCallBlock['suggested_rules'],+ ) => {+ onUserConfirm(toolCall, confirm, message.id, rules);+ toolCall.state = confirm ? 'allowed' : 'finished';+ },+ ),+ )}+ </div>+ )}+ {showFooter && (+ <div className="flex flex-row items-center text-muted-foreground gap-x-4 px-2 w-full">+ <Badge+ variant="secondary"+ aria-label={isRunning ? t('messageBubble.running') : undefined}+ >+ {isRunning ? (+ <Loader2 data-icon="inline-start" className="animate-spin" />+ ) : (+ <CheckCircle data-icon="inline-start" />+ )}+ <span className="tabular-nums tracking-tighter">{elapsedText}</span>+ {hasUsage && (+ <>+ <ArrowUp data-icon="inline-start" className="ml-1" />+ <span className="tabular-nums">+ {formatNumber(message.usage?.input_tokens ?? 0)}+ </span>+ <ArrowDown data-icon="inline-start" className="ml-1" />+ <span className="tabular-nums">+ {formatNumber(message.usage?.output_tokens ?? 0)}+ </span>+ </>+ )}</Badge></div>)}diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/BashRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/BashRenderer.tsxindex 194338ae3..82b5f3765 100644--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/BashRenderer.tsx+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/BashRenderer.tsx@@ -1,3 +1,9 @@+import {+ defaultGetDisplayName,+ defaultRenderCallArgs,+ defaultRenderGroup,+ defaultRenderResult,+} from './DefaultRenderer';import type { ToolRenderer } from './types';function parseInput(input: string): Record<string, unknown> {@@ -38,4 +44,15 @@ export const BashRenderer: ToolRenderer = {</div>);},++ renderGroup: (calls, t) =>+ defaultRenderGroup(calls, t, {+ getDisplayName: (call) =>+ BashRenderer.getDisplayName?.(call, t) ?? defaultGetDisplayName(call),+ renderCallArgs: (call) =>+ BashRenderer.renderCallArgs?.(call, t) ?? defaultRenderCallArgs(call),+ renderResult: (call, result) =>+ BashRenderer.renderResult?.(call, result, t) ??+ defaultRenderResult(call, result, t),+ }),};diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/DefaultRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/DefaultRenderer.tsxindex a7a85c80d..8d8bda5ac 100644--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/DefaultRenderer.tsx+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/DefaultRenderer.tsx@@ -2,7 +2,8 @@ import type { ToolCallBlock, ToolResultBlock } from '@agentscope-ai/agentscope/mimport * as mime from 'mime-types';import type { ReactNode } from 'react';-import type { TFunction } from './types';+import { CornerLine, ToolStateIcon } from './_shared';+import type { TFunction, ToolCallWithResult } from './types';function processToolInput(input: string): string {try {@@ -74,3 +75,49 @@ export function defaultRenderConfirmBody(call: ToolCallBlock): ReactNode {</div>);}++/**+ * Default group layout: each call is an independent block with a state icon,+ * `displayName(args)` header line, and (optionally) a corner-line-prefixed+ * result block beneath it. Used by tools without a custom `renderGroup`,+ * e.g. arbitrary MCP tools.+ *+ * `getDisplayName` / `renderCallArgs` / `renderResult` are passed in from+ * `index.ts` so this function stays decoupled from the renderer registry.+ */+export function defaultRenderGroup(+ calls: ToolCallWithResult[],+ _t: TFunction,+ resolvers: {+ getDisplayName: (call: ToolCallBlock) => string;+ renderCallArgs: (call: ToolCallBlock) => ReactNode;+ renderResult: (call: ToolCallBlock, result: ToolResultBlock) => ReactNode;+ },+): ReactNode {+ return (+ <>+ {calls.map(({ call, result }) => {+ const displayName = resolvers.getDisplayName(call);+ const args = resolvers.renderCallArgs(call);+ const resultContent = result ? resolvers.renderResult(call, result) : null;+ return (+ <div key={call.id} className="flex flex-col w-full max-w-full text-sm">+ <div className="flex flex-row gap-x-2 w-full max-w-full items-center">+ <ToolStateIcon states={[result?.state]} />+ <span className="truncate">+ <strong className="truncate text-primary">{displayName}</strong>+ {args && <>({args})</>}+ </span>+ </div>+ {resultContent && (+ <div className="flex flex-row gap-x-2 pl-6 max-w-full">+ <CornerLine />+ {resultContent}+ </div>+ )}+ </div>+ );+ })}+ </>+ );+}diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsxnew file mode 100644index 000000000..d4433b454--- /dev/null+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsx@@ -0,0 +1,45 @@+import {+ defaultGetDisplayName,+ defaultRenderCallArgs,+ defaultRenderGroup,+ defaultRenderResult,+} from './DefaultRenderer';+import type { ToolRenderer } from './types';++function parseInput(input: string): Record<string, unknown> {+ try {+ return JSON.parse(input);+ } catch {+ return {};+ }+}++function getFilePath(input: string): string {+ const { file_path } = parseInput(input) as { file_path?: string };+ return file_path || input;+}++// TODO: render old_string / new_string as a side-by-side or unified diff+// inside `renderGroup` once a diff component is available.+export const EditRenderer: ToolRenderer = {+ getDisplayName: (call) => call.name,++ renderCallArgs: (call) => getFilePath(call.input),++ renderConfirmBody: (call) => (+ <div className="w-full max-w-full overflow-hidden text-ellipsis truncate">+ <div className="text-secondary-foreground">{getFilePath(call.input)}</div>+ </div>+ ),++ renderGroup: (calls, t) =>+ defaultRenderGroup(calls, t, {+ getDisplayName: (call) =>+ EditRenderer.getDisplayName?.(call, t) ?? defaultGetDisplayName(call),+ renderCallArgs: (call) =>+ EditRenderer.renderCallArgs?.(call, t) ?? defaultRenderCallArgs(call),+ renderResult: (call, result) =>+ EditRenderer.renderResult?.(call, result, t) ??+ defaultRenderResult(call, result, t),+ }),+};diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/GlobRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/GlobRenderer.tsxnew file mode 100644index 000000000..e8233676e--- /dev/null+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/GlobRenderer.tsx@@ -0,0 +1,30 @@+import { ToolCallGroupList } from './_shared';+import type { ToolRenderer } from './types';++function parseInput(input: string): Record<string, unknown> {+ try {+ return JSON.parse(input);+ } catch {+ return {};+ }+}++function getPattern(input: string): string {+ const { pattern } = parseInput(input) as { pattern?: string };+ return pattern || input;+}++export const GlobRenderer: ToolRenderer = {+ getDisplayName: (_call, t) => t('tool.glob.name'),++ renderCallArgs: (call) => getPattern(call.input),++ renderGroup: (calls, t) => (+ <ToolCallGroupList+ calls={calls}+ inline+ label={<strong className="truncate text-primary text-sm">{t('tool.glob.name')}</strong>}+ renderItem={(item) => getPattern(item.call.input)}+ />+ ),+};diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/GrepRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/GrepRenderer.tsxnew file mode 100644index 000000000..656c3ec35--- /dev/null+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/GrepRenderer.tsx@@ -0,0 +1,30 @@+import { ToolCallGroupList } from './_shared';+import type { ToolRenderer } from './types';++function parseInput(input: string): Record<string, unknown> {+ try {+ return JSON.parse(input);+ } catch {+ return {};+ }+}++function getPattern(input: string): string {+ const { pattern } = parseInput(input) as { pattern?: string };+ return pattern || input;+}++export const GrepRenderer: ToolRenderer = {+ getDisplayName: (_call, t) => t('tool.grep.name'),++ renderCallArgs: (call) => getPattern(call.input),++ renderGroup: (calls, t) => (+ <ToolCallGroupList+ calls={calls}+ inline+ label={<strong className="truncate text-primary text-sm">{t('tool.grep.name')}</strong>}+ renderItem={(item) => getPattern(item.call.input)}+ />+ ),+};diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/ReadRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/ReadRenderer.tsxindex e9c60f4cb..66c4f0841 100644--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/ReadRenderer.tsx+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/ReadRenderer.tsx@@ -1,4 +1,11 @@-import type { ToolRenderer } from './types';+/* eslint-disable react-refresh/only-export-components -- renderer constant is co-located with its inline component by design */+import type { ToolResultBlock } from '@agentscope-ai/agentscope/message';+import { useState } from 'react';++import { CornerLine, ToolStateIcon } from './_shared';+import type { TFunction, ToolCallWithResult, ToolRenderer } from './types';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';+import { formatNumber } from '@/utils/common';function parseInput(input: string): Record<string, unknown> {try {@@ -8,20 +15,111 @@ function parseInput(input: string): Record<string, unknown> {}}+function getFilePath(input: string): string {+ const { file_path } = parseInput(input) as { file_path?: string };+ return file_path || input;+}++/** Count lines in a tool result's output string, including text content from+ * non-text blocks. Returns 0 when the result is missing or empty. */+function countResultLines(result?: ToolResultBlock): number {+ if (!result) return 0;+ let str: string;+ if (typeof result.output === 'string') {+ str = result.output;+ } else {+ str = result.output.map((b) => (b.type === 'text' ? b.text : '')).join('\n');+ }+ if (!str) return 0;+ return str.split('\n').length;+}++/** Collapse consecutive Read calls of the same `file_path` into one bucket so+ * the path is shown once, followed by one corner-row per call. Order is+ * preserved; a different path or a re-occurrence after another path starts a+ * new bucket. */+function groupByConsecutivePath(+ calls: ToolCallWithResult[],+): Array<{ path: string; calls: ToolCallWithResult[] }> {+ const groups: Array<{ path: string; calls: ToolCallWithResult[] }> = [];+ for (const item of calls) {+ const path = getFilePath(item.call.input);+ const last = groups[groups.length - 1];+ if (last && last.path === path) {+ last.calls.push(item);+ } else {+ groups.push({ path, calls: [item] });+ }+ }+ return groups;+}++function ReadGroup({ calls, t }: { calls: ToolCallWithResult[]; t: TFunction }) {+ const [open, setOpen] = useState(false);+ const name = t('tool.read.name');++ return (+ <Collapsible open={open} onOpenChange={setOpen} className="flex flex-col w-full ">+ <CollapsibleTrigger className="flex flex-row gap-x-2 w-full max-w-full items-center cursor-pointer text-left">+ <ToolStateIcon states={calls.map((c) => c.result?.state)} />+ <span className="text-sm flex-1 min-w-0 truncate">+ <strong className="text-primary">{name} </strong>+ {t('tool.read.fileCount', { count: calls.length })}+ {!open && <span className="text-muted-foreground"> ...</span>}+ </span>+ {/*<ChevronRight*/}+ {/* className={`size-4 shrink-0 transition-transform ${open ? 'rotate-90' : ''}`}*/}+ {/*/>*/}+ </CollapsibleTrigger>+ <CollapsibleContent className="pl-6 pt-2 flex flex-col gap-y-2 text-sm">+ {groupByConsecutivePath(calls).map((group, gIdx) => (+ <div key={gIdx} className="flex flex-col min-w-0">+ <div className="truncate">+ {/*<strong className="text-primary">{name}</strong>*/}+ {/*<span className="text-muted-foreground">({group.path})</span>*/}+ <span+ className={+ 'text-xs !overflow-visible !whitespace-normal !text-clip break-all'+ }+ >+ {group.path}+ </span>+ </div>+ {group.calls.map(({ call, result }) => {+ if (!result) return null;+ const lines = countResultLines(result);+ return (+ <div+ key={call.id}+ className="flex flex-row gap-x-2 items-center pl-2 text-xs"+ >+ <CornerLine />+ <span className="text-muted-foreground">+ {t('tool.read.lineCount', {+ count: lines,+ formatted: formatNumber(lines),+ })}+ </span>+ </div>+ );+ })}+ </div>+ ))}+ </CollapsibleContent>+ </Collapsible>+ );+}+export const ReadRenderer: ToolRenderer = {- getDisplayName: () => 'Read',-- renderCallArgs: (call) => {- const { file_path } = parseInput(call.input) as { file_path?: string };- return file_path || call.input;- },-- renderConfirmBody: (call) => {- const { file_path } = parseInput(call.input) as { file_path?: string };- return (- <div className="w-full max-w-full overflow-hidden text-ellipsis truncate">- <div className="text-secondary-foreground">{file_path}</div>- </div>- );- },+ getDisplayName: (_call, t) => t('tool.read.name'),++ renderCallArgs: (call) => getFilePath(call.input),++ renderConfirmBody: (call) => (+ <div className="w-full max-w-full overflow-hidden text-ellipsis truncate">+ <div className="text-secondary-foreground">{getFilePath(call.input)}</div>+ </div>+ ),++ renderGroup: (calls, t) => <ReadGroup calls={calls} t={t} />,};diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/SearchRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/SearchRenderer.tsxdeleted file mode 100644index d89943ecf..000000000--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/SearchRenderer.tsx+++ /dev/null@@ -1,18 +0,0 @@-import type { ToolRenderer } from './types';--function parseInput(input: string): Record<string, unknown> {- try {- return JSON.parse(input);- } catch {- return {};- }-}--export const SearchRenderer: ToolRenderer = {- getDisplayName: (call) => call.name,-- renderCallArgs: (call) => {- const { pattern } = parseInput(call.input) as { pattern?: string };- return pattern || call.input;- },-};diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/WriteRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/WriteRenderer.tsxindex 1d858b78c..a2e2e7cb5 100644--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/WriteRenderer.tsx+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/WriteRenderer.tsx@@ -1,3 +1,9 @@+import {+ defaultGetDisplayName,+ defaultRenderCallArgs,+ defaultRenderGroup,+ defaultRenderResult,+} from './DefaultRenderer';import type { ToolRenderer } from './types';function parseInput(input: string): Record<string, unknown> {@@ -8,20 +14,30 @@ function parseInput(input: string): Record<string, unknown> {}}+function getFilePath(input: string): string {+ const { file_path } = parseInput(input) as { file_path?: string };+ return file_path || input;+}+export const WriteRenderer: ToolRenderer = {getDisplayName: (call) => call.name,- renderCallArgs: (call) => {- const { file_path } = parseInput(call.input) as { file_path?: string };- return file_path || call.input;- },+ renderCallArgs: (call) => getFilePath(call.input),++ renderConfirmBody: (call) => (+ <div className="w-full max-w-full overflow-hidden text-ellipsis truncate">+ <div className="text-secondary-foreground">{getFilePath(call.input)}</div>+ </div>+ ),- renderConfirmBody: (call) => {- const { file_path } = parseInput(call.input) as { file_path?: string };- return (- <div className="w-full max-w-full overflow-hidden text-ellipsis truncate">- <div className="text-secondary-foreground">{file_path}</div>- </div>- );- },+ renderGroup: (calls, t) =>+ defaultRenderGroup(calls, t, {+ getDisplayName: (call) =>+ WriteRenderer.getDisplayName?.(call, t) ?? defaultGetDisplayName(call),+ renderCallArgs: (call) =>+ WriteRenderer.renderCallArgs?.(call, t) ?? defaultRenderCallArgs(call),+ renderResult: (call, result) =>+ WriteRenderer.renderResult?.(call, result, t) ??+ defaultRenderResult(call, result, t),+ }),};diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsxnew file mode 100644index 000000000..2573beb6d--- /dev/null+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx@@ -0,0 +1,106 @@+import type { ToolResultBlock } from '@agentscope-ai/agentscope/message';+import { Circle } from 'lucide-react';+import type { ReactNode } from 'react';++import type { ToolCallWithResult } from './types';+import lineCornerSvg from '@/assets/images/line-corner.svg';+import lineVerticalSvg from '@/assets/images/line-vertical.svg';++/**+ * Pick the connector image for an item at `index` of `total`:+ * corner for the last row, vertical otherwise.+ */+function getLineImage(index: number, total: number): string {+ return index === total - 1 ? lineCornerSvg : lineVerticalSvg;+}++/**+ * Single tree-line cell. Use inside flex rows where one column is the line+ * and the next is the actual content.+ */+export function TreeLine({+ index,+ total,+ className = 'w-3 h-full',+}: {+ index: number;+ total: number;+ className?: string;+}) {+ return (+ <div className="flex-shrink-0 h-full items-center">+ <img src={getLineImage(index, total)} alt="" className={className} />+ </div>+ );+}++/**+ * Single corner-only line, used when only one trailing item exists.+ */+export function CornerLine({ className = 'w-3 h-4' }: { className?: string }) {+ return (+ <div className="flex-shrink-0">+ <img src={lineCornerSvg} alt="" className={className} />+ </div>+ );+}++/**+ * Aggregated state icon over a list of tool result states. Mirrors the+ * pre-refactor priority: running/undefined → pulsing muted; all success →+ * green; any error → red; any interrupted → yellow; otherwise muted.+ */+export function ToolStateIcon({ states }: { states: (ToolResultBlock['state'] | undefined)[] }) {+ if (states.includes('running') || states.includes(undefined)) {+ return (+ <Circle className="size-2.5 text-muted-foreground fill-muted-foreground animate-pulse shrink-0" />+ );+ }+ if (states.every((state) => state === 'success')) {+ return <Circle className="size-2.5 text-green-500 fill-green-500 shrink-0" />;+ }+ if (states.some((state) => state === 'error')) {+ return <Circle className="size-2.5 text-red-500 fill-red-500 shrink-0" />;+ }+ if (states.some((state) => state === 'interrupted')) {+ return <Circle className="size-2.5 text-yellow-500 fill-yellow-500 shrink-0" />;+ }+ return <Circle className="size-2.5 text-muted-foreground fill-muted-foreground shrink-0" />;+}++/**+ * Header + indented item list, used by Read / Glob / Grep group renderers.+ * Each item shows only the per-call args (no result), connected by SVG tree+ * lines. `inline` lays items horizontally instead of stacked.+ */+export function ToolCallGroupList({+ calls,+ label,+ renderItem,+ inline,+}: {+ calls: ToolCallWithResult[];+ label: ReactNode;+ renderItem: (item: ToolCallWithResult) => ReactNode;+ inline?: boolean;+}) {+ return (+ <div className="flex flex-col w-full">+ <div className="flex flex-row gap-x-2 w-full max-w-full items-center">+ <ToolStateIcon states={calls.map((item) => item.result?.state)} />+ {label}+ </div>+ <div className={`flex ${inline ? 'flex-row' : 'flex-col'} gap-x-2 pl-6 max-w-full`}>+ {calls.map((item, index) => (+ <div+ key={item.call.id}+ className="flex flex-row gap-x-2 w-full max-w-full items-stretch"+ >+ <TreeLine index={index} total={calls.length} />+ <div className="truncate flex-1 min-w-0 text-sm">{renderItem(item)}</div>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/index.ts b/examples/web_ui/frontend/src/components/chat/tool-renderers/index.tsindex b03d3c4da..3a63a6a2d 100644--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/index.ts+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/index.ts@@ -5,21 +5,24 @@ import { BashRenderer } from './BashRenderer';import {defaultGetDisplayName,defaultRenderCallArgs,- defaultRenderResult,defaultRenderConfirmBody,+ defaultRenderGroup,+ defaultRenderResult,} from './DefaultRenderer';+import { EditRenderer } from './EditRenderer';+import { GlobRenderer } from './GlobRenderer';+import { GrepRenderer } from './GrepRenderer';import { ReadRenderer } from './ReadRenderer';-import { SearchRenderer } from './SearchRenderer';-import type { TFunction, ToolRenderer } from './types';+import type { TFunction, ToolCallWithResult, ToolRenderer } from './types';import { WriteRenderer } from './WriteRenderer';const renderers: Record<string, ToolRenderer> = {Bash: BashRenderer,Read: ReadRenderer,Write: WriteRenderer,- Edit: WriteRenderer,- Glob: SearchRenderer,- Grep: SearchRenderer,+ Edit: EditRenderer,+ Glob: GlobRenderer,+ Grep: GrepRenderer,};function getRenderer(toolName: string): ToolRenderer {@@ -49,3 +52,27 @@ export function renderConfirmBody(call: ToolCallBlock, t: TFunction): ReactNodeconst r = getRenderer(call.name);return r.renderConfirmBody?.(call, t) ?? defaultRenderConfirmBody(call);}++/**+ * Render a group of consecutive tool calls of the same name.+ *+ * - If the tool's renderer defines `renderGroup`, delegate to it.+ * - Otherwise fall back to `defaultRenderGroup`, wired with this registry's+ * resolvers so per-tool `getDisplayName` / `renderCallArgs` / `renderResult`+ * still apply.+ */+export function renderToolGroup(+ toolName: string,+ calls: ToolCallWithResult[],+ t: TFunction,+): ReactNode {+ const r = getRenderer(toolName);+ if (r.renderGroup) {+ return r.renderGroup(calls, t);+ }+ return defaultRenderGroup(calls, t, {+ getDisplayName: (call) => getDisplayName(call, t),+ renderCallArgs: (call) => renderCallArgs(call, t),+ renderResult: (call, result) => renderResult(call, result, t),+ });+}diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/types.ts b/examples/web_ui/frontend/src/components/chat/tool-renderers/types.tsindex 07e87523a..3fb785334 100644--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/types.ts+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/types.ts@@ -3,9 +3,21 @@ import type { ReactNode } from 'react';export type TFunction = (key: string, params?: Record<string, unknown>) => string;+export interface ToolCallWithResult {+ call: ToolCallBlock;+ result?: ToolResultBlock;+}+export interface ToolRenderer {getDisplayName?: (call: ToolCallBlock, t: TFunction) => string;renderCallArgs?: (call: ToolCallBlock, t: TFunction) => ReactNode;renderResult?: (call: ToolCallBlock, result: ToolResultBlock, t: TFunction) => ReactNode;renderConfirmBody?: (call: ToolCallBlock, t: TFunction) => ReactNode;+ /**+ * Render a group of consecutive tool calls of the same name.+ * Receives the visible (non-truncated) calls — `MessageBubble` truncates+ * at the first `asking` call before invoking, and renders ConfirmCard+ * separately.+ */+ renderGroup?: (calls: ToolCallWithResult[], t: TFunction) => ReactNode;}diff --git a/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsxindex fb0469127..e8301a526 100644--- a/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx@@ -1,28 +1,26 @@import { PlusCircle } from 'lucide-react';-import { useState } from 'react';+import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';+import type { ContextConfig, ReActConfig } from '@/api';+import {+ AgentFormFields,+ defaultAgentFormValues,+ type AgentFormValues,+ type AgentSection,+} from '@/components/form/AgentFormFields';+import type { SchemaFormValue } from '@/components/form/SchemaForm';import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';import {Dialog,DialogContent,+ DialogFooter,DialogHeader,DialogTitle,DialogTrigger,} from '@/components/ui/dialog';-import {- Field,- FieldDescription,- FieldGroup,- FieldLabel,- FieldLegend,- FieldSeparator,- FieldSet,-} from '@/components/ui/field';-import { Input } from '@/components/ui/input';-import { Textarea } from '@/components/ui/textarea';import { useAgents } from '@/hooks/useAgents';+import { useAgentSchema } from '@/hooks/useAgentSchema';interface Props {onCreated?: () => void;@@ -32,34 +30,36 @@ interface Props {export function AgentDialog({ onCreated, triggerId }: Props) {const { create } = useAgents();const { t } = useTranslation();+ const { schema } = useAgentSchema();const [open, setOpen] = useState(false);const [submitting, setSubmitting] = useState(false);+ const [values, setValues] = useState<AgentFormValues | null>(null);++ useEffect(() => {+ if (open && schema && !values) {+ setValues(defaultAgentFormValues(schema));+ }+ if (!open) setValues(null);+ }, [open, schema, values]);- const [name, setName] = useState('');- const [systemPrompt, setSystemPrompt] = useState("You're a helpful assistant.");- const [triggerRatio, setTriggerRatio] = useState('');- const [reserveRatio, setReserveRatio] = useState('');- const [toolResultLimit, setToolResultLimit] = useState('');- const [compressionPrompt, setCompressionPrompt] = useState('');- const [summaryTemplate, setSummaryTemplate] = useState('');- const [maxIters, setMaxIters] = useState('');- const [stopOnReject, setStopOnReject] = useState(false);+ const handleChange = (section: AgentSection, key: string, value: SchemaFormValue) => {+ setValues((prev) =>+ prev ? { ...prev, [section]: { ...prev[section], [key]: value } } : prev,+ );+ };const handleSubmit = async () => {- const context_config = {- ...(triggerRatio !== '' && { trigger_ratio: parseFloat(triggerRatio) }),- ...(reserveRatio !== '' && { reserve_ratio: parseFloat(reserveRatio) }),- ...(toolResultLimit !== '' && { tool_result_limit: parseInt(toolResultLimit) }),- ...(compressionPrompt !== '' && { compression_prompt: compressionPrompt }),- ...(summaryTemplate !== '' && { summary_template: summaryTemplate }),- };- const react_config = {- ...(maxIters !== '' && { max_iters: parseInt(maxIters) }),- stop_on_reject: stopOnReject,- };+ if (!values) return;+ const name = (values.identity.name as string | undefined)?.trim();+ if (!name) return;setSubmitting(true);try {- await create({ name, system_prompt: systemPrompt, context_config, react_config });+ await create({+ name,+ system_prompt: values.identity.system_prompt as string | undefined,+ context_config: values.context_config as unknown as ContextConfig,+ react_config: values.react_config as unknown as ReActConfig,+ });setOpen(false);onCreated?.();} finally {@@ -67,6 +67,8 @@ export function AgentDialog({ onCreated, triggerId }: Props) {}};+ const nameValid = !!(values?.identity.name as string | undefined)?.trim();+return (<Dialog open={open} onOpenChange={setOpen}><DialogTrigger asChild>@@ -75,176 +77,30 @@ export function AgentDialog({ onCreated, triggerId }: Props) {<span>{t('dialog-agent-create.trigger')}</span></Button></DialogTrigger>- <DialogContent className="max-w-lg max-h-[80vh] overflow-y-auto">+ <DialogContent className="w-[500px]! max-w-[500px]!"><DialogHeader><DialogTitle>{t('dialog-agent-create.title')}</DialogTitle></DialogHeader>- <FieldGroup>- <FieldSet>- <FieldLegend>{t('dialog-agent-create.identity.legend')}</FieldLegend>- <FieldDescription>- {t('dialog-agent-create.identity.description')}- </FieldDescription>- <FieldGroup>- <Field>- <FieldLabel htmlFor="agent-name">- {t('dialog-agent-create.identity.name.label')}- </FieldLabel>- <Input- id="agent-name"- placeholder={t('dialog-agent-create.identity.name.placeholder')}- value={name}- onChange={(e) => setName(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="agent-prompt">- {t('dialog-agent-create.identity.systemPrompt.label')}- </FieldLabel>- <Textarea- id="agent-prompt"- rows={4}- placeholder={t(- 'dialog-agent-create.identity.systemPrompt.placeholder',- )}- value={systemPrompt}- onChange={(e) => setSystemPrompt(e.target.value)}- />- </Field>- </FieldGroup>- </FieldSet>- <FieldSeparator />- <FieldSet>- <FieldLegend>{t('dialog-agent-create.contextConfig.legend')}</FieldLegend>- <FieldDescription>- {t('dialog-agent-create.contextConfig.description')}- </FieldDescription>- <FieldGroup>- <Field>- <FieldLabel htmlFor="trigger-ratio">- {t('dialog-agent-create.contextConfig.triggerRatio.label')}- </FieldLabel>- <Input- id="trigger-ratio"- type="number"- min={0.01}- max={0.89}- step={0.01}- placeholder={t(- 'dialog-agent-create.contextConfig.triggerRatio.placeholder',- )}- value={triggerRatio}- onChange={(e) => setTriggerRatio(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="reserve-ratio">- {t('dialog-agent-create.contextConfig.reserveRatio.label')}- </FieldLabel>- <Input- id="reserve-ratio"- type="number"- min={0.01}- max={0.89}- step={0.01}- placeholder={t(- 'dialog-agent-create.contextConfig.reserveRatio.placeholder',- )}- value={reserveRatio}- onChange={(e) => setReserveRatio(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="tool-result-limit">- {t('dialog-agent-create.contextConfig.toolResultLimit.label')}- </FieldLabel>- <Input- id="tool-result-limit"- type="number"- min={100}- step={100}- placeholder={t(- 'dialog-agent-create.contextConfig.toolResultLimit.placeholder',- )}- value={toolResultLimit}- onChange={(e) => setToolResultLimit(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="compression-prompt">- {t('dialog-agent-create.contextConfig.compressionPrompt.label')}- </FieldLabel>- <Textarea- id="compression-prompt"- rows={2}- placeholder={t(- 'dialog-agent-create.contextConfig.compressionPrompt.placeholder',- )}- value={compressionPrompt}- onChange={(e) => setCompressionPrompt(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="summary-template">- {t('dialog-agent-create.contextConfig.summaryTemplate.label')}- </FieldLabel>- <Textarea- id="summary-template"- rows={2}- placeholder={t(- 'dialog-agent-create.contextConfig.summaryTemplate.placeholder',- )}- value={summaryTemplate}- onChange={(e) => setSummaryTemplate(e.target.value)}- />- </Field>- </FieldGroup>- </FieldSet>- <FieldSeparator />- <FieldSet>- <FieldLegend>{t('dialog-agent-create.reactConfig.legend')}</FieldLegend>- <FieldDescription>- {t('dialog-agent-create.reactConfig.description')}- </FieldDescription>- <FieldGroup>- <Field>- <FieldLabel htmlFor="max-iters">- {t('dialog-agent-create.reactConfig.maxIters.label')}- </FieldLabel>- <Input- id="max-iters"- type="number"- min={1}- step={1}- placeholder={t(- 'dialog-agent-create.reactConfig.maxIters.placeholder',- )}- value={maxIters}- onChange={(e) => setMaxIters(e.target.value)}- />- </Field>- <Field orientation="horizontal">- <Checkbox- id="stop-on-reject"- checked={stopOnReject}- onCheckedChange={(v) => setStopOnReject(v === true)}- />- <FieldLabel htmlFor="stop-on-reject" className="font-normal">- {t('dialog-agent-create.reactConfig.stopOnReject.label')}- </FieldLabel>- </Field>- </FieldGroup>- </FieldSet>- <Field orientation="horizontal">- <Button onClick={handleSubmit} disabled={!name.trim() || submitting}>- <PlusCircle />- {submitting ? t('common.creating') : t('common.create')}- </Button>- <Button variant="outline" onClick={() => setOpen(false)}>- {t('common.cancel')}- </Button>- </Field>- </FieldGroup>+ <div className="no-scrollbar -mx-4 max-h-[75vh] overflow-y-auto px-4">+ {schema && values ? (+ <AgentFormFields schema={schema} values={values} onChange={handleChange} />+ ) : (+ <p className="text-muted-foreground text-sm">{t('common.loading')}</p>+ )}+ </div>+ <DialogFooter>+ <Button size="sm" variant="outline" onClick={() => setOpen(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ size="sm"+ onClick={handleSubmit}+ disabled={!nameValid || submitting || !schema || !values}+ >+ <PlusCircle />+ {submitting ? t('common.creating') : t('common.create')}+ </Button>+ </DialogFooter></DialogContent></Dialog>);diff --git a/examples/web_ui/frontend/src/components/dialog/CreateCredentialDialog.tsx b/examples/web_ui/frontend/src/components/dialog/CreateCredentialDialog.tsxindex 7bcd0b5d1..3a787acd5 100644--- a/examples/web_ui/frontend/src/components/dialog/CreateCredentialDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/CreateCredentialDialog.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react';import { credentialApi } from '@/api';import type { CredentialSchema } from '@/api';-import { SchemaForm } from '@/components/form/SchemaForm';+import { SchemaForm, type SchemaFormValue } from '@/components/form/SchemaForm';import { Button } from '@/components/ui/button';import {Dialog,@@ -35,7 +35,7 @@ export function CreateCredentialDialog({ open, onOpenChange, onCreated, defaultTconst [schemas, setSchemas] = useState<CredentialSchema[]>([]);const [loadingSchemas, setLoadingSchemas] = useState(false);const [selectedType, setSelectedType] = useState('');- const [values, setValues] = useState<Record<string, string | boolean>>({});+ const [values, setValues] = useState<Record<string, SchemaFormValue>>({});const [submitting, setSubmitting] = useState(false);useEffect(() => {diff --git a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsxindex 1e5de73fc..48b347908 100644--- a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx@@ -1,22 +1,24 @@-import { useState, useEffect } from 'react';+import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import type { AgentRecord } from '@/api';+import type { AgentRecord, ContextConfig, ReActConfig } from '@/api';+import {+ AgentFormFields,+ defaultAgentFormValues,+ type AgentFormValues,+ type AgentSection,+} from '@/components/form/AgentFormFields';+import type { SchemaFormValue } from '@/components/form/SchemaForm';import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';-import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';import {- Field,- FieldDescription,- FieldGroup,- FieldLabel,- FieldLegend,- FieldSeparator,- FieldSet,-} from '@/components/ui/field';-import { Input } from '@/components/ui/input';-import { Textarea } from '@/components/ui/textarea';+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';import { useAgents } from '@/hooks/useAgents';+import { useAgentSchema } from '@/hooks/useAgentSchema';interface Props {open: boolean;@@ -28,51 +30,47 @@ interface Props {export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props) {const { update } = useAgents();const { t } = useTranslation();+ const { schema } = useAgentSchema();const [submitting, setSubmitting] = useState(false);-- const [name, setName] = useState('');- const [systemPrompt, setSystemPrompt] = useState('');- const [triggerRatio, setTriggerRatio] = useState('');- const [reserveRatio, setReserveRatio] = useState('');- const [toolResultLimit, setToolResultLimit] = useState('');- const [compressionPrompt, setCompressionPrompt] = useState('');- const [summaryTemplate, setSummaryTemplate] = useState('');- const [maxIters, setMaxIters] = useState('');- const [stopOnReject, setStopOnReject] = useState(false);+ const [values, setValues] = useState<AgentFormValues | null>(null);useEffect(() => {- if (!open) return;+ if (!open || !schema) {+ if (!open) setValues(null);+ return;+ }+ // Start from schema defaults, then overlay the existing agent's data so+ // any unset fields fall back to defaults rather than empty.+ const base = defaultAgentFormValues(schema);const d = agent.data;- setName(d.name);- setSystemPrompt(d.system_prompt);- setTriggerRatio(d.context_config?.trigger_ratio?.toString() ?? '');- setReserveRatio(d.context_config?.reserve_ratio?.toString() ?? '');- setToolResultLimit(d.context_config?.tool_result_limit?.toString() ?? '');- setCompressionPrompt(d.context_config?.compression_prompt ?? '');- setSummaryTemplate(d.context_config?.summary_template ?? '');- setMaxIters(d.react_config?.max_iters?.toString() ?? '');- setStopOnReject(d.react_config?.stop_on_reject ?? false);- }, [open, agent]);+ setValues({+ identity: {+ ...base.identity,+ name: d.name,+ system_prompt: d.system_prompt,+ },+ context_config: { ...base.context_config, ...(d.context_config ?? {}) },+ react_config: { ...base.react_config, ...(d.react_config ?? {}) },+ });+ }, [open, schema, agent]);++ const handleChange = (section: AgentSection, key: string, value: SchemaFormValue) => {+ setValues((prev) =>+ prev ? { ...prev, [section]: { ...prev[section], [key]: value } } : prev,+ );+ };const handleSubmit = async () => {- const context_config = {- ...(triggerRatio !== '' && { trigger_ratio: parseFloat(triggerRatio) }),- ...(reserveRatio !== '' && { reserve_ratio: parseFloat(reserveRatio) }),- ...(toolResultLimit !== '' && { tool_result_limit: parseInt(toolResultLimit) }),- ...(compressionPrompt !== '' && { compression_prompt: compressionPrompt }),- ...(summaryTemplate !== '' && { summary_template: summaryTemplate }),- };- const react_config = {- ...(maxIters !== '' && { max_iters: parseInt(maxIters) }),- stop_on_reject: stopOnReject,- };+ if (!values) return;+ const name = (values.identity.name as string | undefined)?.trim();+ if (!name) return;setSubmitting(true);try {await update(agent.id, {name,- system_prompt: systemPrompt,- context_config,- react_config,+ system_prompt: values.identity.system_prompt as string | undefined,+ context_config: values.context_config as unknown as ContextConfig,+ react_config: values.react_config as unknown as ReActConfig,});onOpenChange(false);onUpdated?.();@@ -81,177 +79,33 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props)}};+ const nameValid = !!(values?.identity.name as string | undefined)?.trim();+return (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="max-w-lg max-h-[80vh] overflow-y-auto">+ <DialogContent className="w-[720px] max-w-[720px]"><DialogHeader><DialogTitle>{t('dialog-agent-edit.title')}</DialogTitle></DialogHeader>- <FieldGroup>- <FieldSet>- <FieldLegend>{t('dialog-agent-create.identity.legend')}</FieldLegend>- <FieldDescription>- {t('dialog-agent-create.identity.description')}- </FieldDescription>- <FieldGroup>- <Field>- <FieldLabel htmlFor="edit-name">- {t('dialog-agent-create.identity.name.label')}- </FieldLabel>- <Input- id="edit-name"- placeholder={t('dialog-agent-create.identity.name.placeholder')}- value={name}- onChange={(e) => setName(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="edit-prompt">- {t('dialog-agent-create.identity.systemPrompt.label')}- </FieldLabel>- <Textarea- id="edit-prompt"- rows={4}- placeholder={t(- 'dialog-agent-create.identity.systemPrompt.placeholder',- )}- value={systemPrompt}- onChange={(e) => setSystemPrompt(e.target.value)}- />- </Field>- </FieldGroup>- </FieldSet>- <FieldSeparator />- <FieldSet>- <FieldLegend>{t('dialog-agent-create.contextConfig.legend')}</FieldLegend>- <FieldDescription>- {t('dialog-agent-create.contextConfig.description')}- </FieldDescription>- <FieldGroup>- <Field>- <FieldLabel htmlFor="edit-trigger-ratio">- {t('dialog-agent-create.contextConfig.triggerRatio.label')}- </FieldLabel>- <Input- id="edit-trigger-ratio"- type="number"- min={0.01}- max={0.89}- step={0.01}- placeholder={t(- 'dialog-agent-create.contextConfig.triggerRatio.placeholder',- )}- value={triggerRatio}- onChange={(e) => setTriggerRatio(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="edit-reserve-ratio">- {t('dialog-agent-create.contextConfig.reserveRatio.label')}- </FieldLabel>- <Input- id="edit-reserve-ratio"- type="number"- min={0.01}- max={0.89}- step={0.01}- placeholder={t(- 'dialog-agent-create.contextConfig.reserveRatio.placeholder',- )}- value={reserveRatio}- onChange={(e) => setReserveRatio(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="edit-tool-result-limit">- {t('dialog-agent-create.contextConfig.toolResultLimit.label')}- </FieldLabel>- <Input- id="edit-tool-result-limit"- type="number"- min={100}- step={100}- placeholder={t(- 'dialog-agent-create.contextConfig.toolResultLimit.placeholder',- )}- value={toolResultLimit}- onChange={(e) => setToolResultLimit(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="edit-compression-prompt">- {t('dialog-agent-create.contextConfig.compressionPrompt.label')}- </FieldLabel>- <Textarea- id="edit-compression-prompt"- rows={2}- placeholder={t(- 'dialog-agent-create.contextConfig.compressionPrompt.placeholder',- )}- value={compressionPrompt}- onChange={(e) => setCompressionPrompt(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="edit-summary-template">- {t('dialog-agent-create.contextConfig.summaryTemplate.label')}- </FieldLabel>- <Textarea- id="edit-summary-template"- rows={2}- placeholder={t(- 'dialog-agent-create.contextConfig.summaryTemplate.placeholder',- )}- value={summaryTemplate}- onChange={(e) => setSummaryTemplate(e.target.value)}- />- </Field>- </FieldGroup>- </FieldSet>- <FieldSeparator />- <FieldSet>- <FieldLegend>{t('dialog-agent-create.reactConfig.legend')}</FieldLegend>- <FieldDescription>- {t('dialog-agent-create.reactConfig.description')}- </FieldDescription>- <FieldGroup>- <Field>- <FieldLabel htmlFor="edit-max-iters">- {t('dialog-agent-create.reactConfig.maxIters.label')}- </FieldLabel>- <Input- id="edit-max-iters"- type="number"- min={1}- step={1}- placeholder={t(- 'dialog-agent-create.reactConfig.maxIters.placeholder',- )}- value={maxIters}- onChange={(e) => setMaxIters(e.target.value)}- />- </Field>- <Field orientation="horizontal">- <Checkbox- id="edit-stop-on-reject"- checked={stopOnReject}- onCheckedChange={(v) => setStopOnReject(v === true)}- />- <FieldLabel htmlFor="edit-stop-on-reject" className="font-normal">- {t('dialog-agent-create.reactConfig.stopOnReject.label')}- </FieldLabel>- </Field>- </FieldGroup>- </FieldSet>- <Field orientation="horizontal">- <Button onClick={handleSubmit} disabled={!name.trim() || submitting}>- {submitting ? t('common.saving') : t('common.save')}- </Button>- <Button variant="outline" onClick={() => onOpenChange(false)}>- {t('common.cancel')}- </Button>- </Field>- </FieldGroup>+ <div className="no-scrollbar -mx-4 max-h-[75vh] overflow-y-auto px-4">+ {schema && values ? (+ <AgentFormFields schema={schema} values={values} onChange={handleChange} />+ ) : (+ <p className="text-muted-foreground text-sm">{t('common.loading')}</p>+ )}+ </div>+ <DialogFooter>+ <Button size="sm" variant="outline" onClick={() => onOpenChange(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ size="sm"+ onClick={handleSubmit}+ disabled={!nameValid || submitting || !schema || !values}+ >+ {submitting ? t('common.saving') : t('common.save')}+ </Button>+ </DialogFooter></DialogContent></Dialog>);diff --git a/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsxindex 7828508e5..9e6d4791b 100644--- a/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react';import { credentialApi } from '@/api';import type { CredentialRecord, CredentialSchema } from '@/api';-import { SchemaForm } from '@/components/form/SchemaForm';+import { SchemaForm, type SchemaFormValue } from '@/components/form/SchemaForm';import { Button } from '@/components/ui/button';import {Dialog,@@ -26,7 +26,7 @@ export function EditCredentialDialog({ open, onOpenChange, credential, onUpdatedconst { t } = useTranslation();const [schema, setSchema] = useState<CredentialSchema | null>(null);const [loadingSchema, setLoadingSchema] = useState(false);- const [values, setValues] = useState<Record<string, string | boolean>>({});+ const [values, setValues] = useState<Record<string, SchemaFormValue>>({});const [submitting, setSubmitting] = useState(false);const type = credential.data.type as string | undefined;@@ -43,13 +43,13 @@ export function EditCredentialDialog({ open, onOpenChange, credential, onUpdatedsetSchema(matched ?? null);// Pre-fill values from existing credential data (excluding writeOnly fields)if (matched) {- const prefill: Record<string, string | boolean> = {};+ const prefill: Record<string, SchemaFormValue> = {};for (const [key, prop] of Object.entries(matched.properties)) {if (key === 'id' || key === 'type' || prop.const !== undefined) continue;if (prop.writeOnly) continue; // don't pre-fill secrets like api_keyconst existing = credential.data[key];if (existing !== undefined) {- prefill[key] = existing as string | boolean;+ prefill[key] = existing as SchemaFormValue;}}setValues(prefill);diff --git a/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx b/examples/web_ui/frontend/src/components/form/AgentFormFields.tsxnew file mode 100644index 000000000..a3769f349--- /dev/null+++ b/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx@@ -0,0 +1,93 @@+import { useTranslation } from 'react-i18next';++import type { AgentSchemaResponse } from '@/api';+import { SchemaForm, type SchemaFormValue } from '@/components/form/SchemaForm';+import {+ FieldDescription,+ FieldGroup,+ FieldLegend,+ FieldSeparator,+ FieldSet,+} from '@/components/ui/field';++export type AgentSection = 'identity' | 'context_config' | 'react_config';++export type AgentFormValues = {+ [K in AgentSection]: Record<string, SchemaFormValue>;+};++interface Props {+ schema: AgentSchemaResponse;+ values: AgentFormValues;+ onChange: (section: AgentSection, key: string, value: SchemaFormValue) => void;+}++const SECTIONS: { key: AgentSection; i18n: string }[] = [+ { key: 'identity', i18n: 'identity' },+ { key: 'context_config', i18n: 'context-config' },+ { key: 'react_config', i18n: 'react-config' },+];++const toKebab = (s: string) => s.replace(/_/g, '-');++export function AgentFormFields({ schema, values, onChange }: Props) {+ const { t } = useTranslation();++ return (+ <FieldGroup>+ {SECTIONS.map(({ key: sectionKey, i18n: sectionI18n }, idx) => {+ const sectionSchema = schema[sectionKey];+ const legend = t(`agent-form.${sectionI18n}.legend`, {+ defaultValue: sectionSchema.title ?? sectionKey,+ });+ const description = t(`agent-form.${sectionI18n}.description`, {+ defaultValue: '',+ });+ return (+ <div key={sectionKey}>+ {idx > 0 && <FieldSeparator className="my-0" />}+ <FieldSet>+ <FieldLegend>{legend}</FieldLegend>+ {description && <FieldDescription>{description}</FieldDescription>}+ <SchemaForm+ schema={sectionSchema}+ values={values[sectionKey]}+ onChange={(k, v) => onChange(sectionKey, k, v)}+ idPrefix={`agent-form-${sectionI18n}`}+ labelFor={(k, prop) =>+ t(`agent-form.${sectionI18n}.${toKebab(k)}.label`, {+ defaultValue: prop.title ?? k.replace(/_/g, ' '),+ })+ }+ placeholderFor={(k, prop) =>+ t(`agent-form.${sectionI18n}.${toKebab(k)}.placeholder`, {+ defaultValue: prop.description ?? '',+ }) || undefined+ }+ />+ </FieldSet>+ </div>+ );+ })}+ </FieldGroup>+ );+}++/** Build a fresh `AgentFormValues` populated from each section schema's defaults. */+export function defaultAgentFormValues(schema: AgentSchemaResponse): AgentFormValues {+ const fromDefaults = (+ section: AgentSchemaResponse[AgentSection],+ ): Record<string, SchemaFormValue> => {+ const out: Record<string, SchemaFormValue> = {};+ for (const [k, prop] of Object.entries(section.properties ?? {})) {+ if (prop.const !== undefined) continue;+ if (prop.default !== undefined) out[k] = prop.default as SchemaFormValue;+ }+ return out;+ };+ return {+ identity: fromDefaults(schema.identity),+ context_config: fromDefaults(schema.context_config),+ react_config: fromDefaults(schema.react_config),+ };+}diff --git a/examples/web_ui/frontend/src/components/form/SchemaForm.tsx b/examples/web_ui/frontend/src/components/form/SchemaForm.tsxindex f40a3978d..c6b2699d3 100644--- a/examples/web_ui/frontend/src/components/form/SchemaForm.tsx+++ b/examples/web_ui/frontend/src/components/form/SchemaForm.tsx@@ -1,65 +1,171 @@-import type { CredentialSchema } from '@/api';+import type { JSONSchema, JSONSchemaProperty } from '@/api';import { Checkbox } from '@/components/ui/checkbox';-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field.tsx';+import { Field, FieldDescription, FieldGroup, FieldLabel } from '@/components/ui/field.tsx';import { Input } from '@/components/ui/input';+import { Textarea } from '@/components/ui/textarea';-const SKIP_FIELDS = new Set(['id', 'type']);+const DEFAULT_SKIP_FIELDS = new Set(['id', 'type']);++export type SchemaFormValue = string | number | boolean | null | undefined;interface Props {- schema: CredentialSchema;- values: Record<string, string | boolean>;- onChange: (key: string, value: string | boolean) => void;+ schema: JSONSchema;+ values: Record<string, SchemaFormValue>;+ onChange: (key: string, value: SchemaFormValue) => void;+ /** Field names to omit from rendering. Defaults to `id` and `type`. */+ skipFields?: ReadonlySet<string>;+ /** Optional override for a field label. Falls back to `prop.title`. */+ labelFor?: (key: string, prop: JSONSchemaProperty) => string | undefined;+ /** Optional override for a field's placeholder/description. */+ placeholderFor?: (key: string, prop: JSONSchemaProperty) => string | undefined;+ /** Optional override for the helper text shown under a field. */+ descriptionFor?: (key: string, prop: JSONSchemaProperty) => string | undefined;+ /** Prefix for generated DOM IDs (so multiple SchemaForms on one page don't collide). */+ idPrefix?: string;+}++function effectiveType(prop: JSONSchemaProperty): string {+ return prop.type ?? prop.anyOf?.find((t) => t.type !== 'null')?.type ?? 'string';+}++function inferStep(type: string): number | string | undefined {+ if (type === 'integer') return 1;+ if (type === 'number') return 'any';+ return undefined;}-export function SchemaForm({ schema, values, onChange }: Props) {- const entries = Object.entries(schema.properties).filter(- ([key, prop]) => !SKIP_FIELDS.has(key) && prop.const === undefined,+/** Extract initial values from a JSON Schema's `default` fields. */+export function defaultValuesFromSchema(+ schema: JSONSchema,+ skipFields: ReadonlySet<string> = DEFAULT_SKIP_FIELDS,+): Record<string, SchemaFormValue> {+ const out: Record<string, SchemaFormValue> = {};+ for (const [key, prop] of Object.entries(schema.properties ?? {})) {+ if (skipFields.has(key) || prop.const !== undefined) continue;+ if (prop.default !== undefined) {+ out[key] = prop.default as SchemaFormValue;+ }+ }+ return out;+}++export function SchemaForm({+ schema,+ values,+ onChange,+ skipFields = DEFAULT_SKIP_FIELDS,+ labelFor,+ placeholderFor,+ descriptionFor,+ idPrefix = 'schema-form',+}: Props) {+ const entries = Object.entries(schema.properties ?? {}).filter(+ ([key, prop]) => !skipFields.has(key) && prop.const === undefined,);return (<FieldGroup>{entries.map(([key, prop]) => {+ const fieldId = `${idPrefix}-${key}`;const isRequired = schema.required?.includes(key) ?? false;+ const type = effectiveType(prop);+ const isBoolean = type === 'boolean';const isPassword = prop.format === 'password';- const effectiveType =- prop.type ?? prop.anyOf?.find((t) => t.type !== 'null')?.type ?? 'string';- const isBoolean = effectiveType === 'boolean';- const label = prop.title ?? key.replace(/_/g, ' ');+ const isTextarea = prop.format === 'textarea';+ const isNumber = type === 'number' || type === 'integer';++ const label = labelFor?.(key, prop) ?? prop.title ?? key.replace(/_/g, ' ');+ const placeholder = placeholderFor?.(key, prop) ?? prop.description;+ const description = descriptionFor?.(key, prop);+ const current = values[key];if (isBoolean) {+ return (+ <Field key={key} orientation="horizontal">+ <Checkbox+ id={fieldId}+ checked={!!current}+ onCheckedChange={(checked) => onChange(key, !!checked)}+ />+ <FieldLabel htmlFor={fieldId} className="font-normal">+ {label}+ </FieldLabel>+ {description && <FieldDescription>{description}</FieldDescription>}+ </Field>+ );+ }++ if (isTextarea) {+ return (+ <Field key={key}>+ <FieldLabel htmlFor={fieldId}>+ {label}+ {isRequired && <span className="text-destructive ml-0.5">*</span>}+ </FieldLabel>+ <Textarea+ id={fieldId}+ rows={3}+ value={(current as string | undefined) ?? ''}+ onChange={(e) => onChange(key, e.target.value)}+ placeholder={placeholder}+ />+ {description && <FieldDescription>{description}</FieldDescription>}+ </Field>+ );+ }++ if (isNumber) {+ const min = prop.minimum ?? prop.exclusiveMinimum;+ const max = prop.maximum ?? prop.exclusiveMaximum;return (<Field key={key}>- <div className="flex items-center gap-x-2">- <Checkbox- id={key}- checked={!!values[key]}- onCheckedChange={(checked) => onChange(key, !!checked)}- />- <FieldLabel htmlFor={key}>{label}</FieldLabel>- </div>+ <FieldLabel htmlFor={fieldId}>+ {label}+ {isRequired && <span className="text-destructive ml-0.5">*</span>}+ </FieldLabel>+ <Input+ id={fieldId}+ type="number"+ min={min}+ max={max}+ step={inferStep(type)}+ value={+ current === undefined || current === null ? '' : String(current)+ }+ onChange={(e) => {+ const raw = e.target.value;+ // Empty input → undefined so JSON.stringify drops the key+ // and the backend applies its own default. Sending "" would+ // fail Pydantic float/int coercion.+ if (raw === '') {+ onChange(key, undefined);+ return;+ }+ const parsed =+ type === 'integer' ? parseInt(raw, 10) : parseFloat(raw);+ onChange(key, Number.isNaN(parsed) ? raw : parsed);+ }}+ placeholder={placeholder}+ />+ {description && <FieldDescription>{description}</FieldDescription>}</Field>);}return (<Field key={key}>- <FieldLabel htmlFor={key}>+ <FieldLabel htmlFor={fieldId}>{label}{isRequired && <span className="text-destructive ml-0.5">*</span>}</FieldLabel><Input- id={key}- type={- isPassword- ? 'password'- : effectiveType === 'number' || effectiveType === 'integer'- ? 'number'- : 'text'- }- value={(values[key] as string) ?? ''}+ id={fieldId}+ type={isPassword ? 'password' : 'text'}+ value={(current as string | undefined) ?? ''}onChange={(e) => onChange(key, e.target.value)}- placeholder={prop.description}+ placeholder={placeholder}/>+ {description && <FieldDescription>{description}</FieldDescription>}</Field>);})}diff --git a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsxindex 4700972da..a72f55629 100644--- a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx+++ b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx@@ -3,17 +3,21 @@ import { useCallback, useEffect, useState } from 'react';import type { ChatModelConfig, ModelCard } from '@/api';import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu.tsx';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';-import {- Popover,- PopoverContent,- PopoverDescription,- PopoverHeader,- PopoverTitle,- PopoverTrigger,-} from '@/components/ui/popover';import { Switch } from '@/components/ui/switch';+import { useAvailableModels } from '@/hooks/useAvailableModels';import { useTranslation } from '@/i18n/useI18n';interface ParameterProperty {@@ -37,14 +41,37 @@ interface ParameterSchema {}interface Props {+ /** Currently selected primary model — used to read the parameter schema. */selectedModel: ChatModelConfig | null;+ /** Model card describing the primary model's parameter schema. */modelCard: ModelCard | null;+ /** Called when the user edits the primary model's parameters. */onChange: (parameters: Record<string, unknown>) => void;+ /** Currently selected fallback model. `null` means no fallback configured. */+ selectedFallbackModel: ChatModelConfig | null;+ /** Called when the user picks a fallback model or clears the selection. */+ onFallbackChange: (config: ChatModelConfig | null) => void;}-export function ModelParametersPopover({ selectedModel, modelCard, onChange }: Props) {+/**+ * A unified settings dropdown for the active chat model. Exposes two+ * sub-menus:+ * - "Fallback model": pick a backup model invoked when the primary fails.+ * - "Parameters": edit the primary model's inference parameters inline.+ *+ * The trigger is disabled until a primary model is selected, since both+ * sub-menus are meaningless without one.+ */+export function ModelParametersPopover({+ selectedModel,+ modelCard,+ onChange,+ selectedFallbackModel,+ onFallbackChange,+}: Props) {const [values, setValues] = useState<Record<string, unknown>>({});const { t } = useTranslation();+ const { groups } = useAvailableModels();const schema = modelCard?.parameter_schema as ParameterSchema | undefined;const properties = schema?.properties ?? {};@@ -67,136 +94,254 @@ export function ModelParametersPopover({ selectedModel, modelCard, onChange }: P[values, onChange],);+ const handleSelectFallback = (type: string, credentialId: string, model: string) => {+ onFallbackChange({+ type,+ credential_id: credentialId,+ model,+ parameters: {},+ });+ };+const disabled = !selectedModel;+ const hasFallbackOptions = Object.keys(groups).length > 0;return (- <Popover>- <PopoverTrigger asChild>+ <DropdownMenu>+ <DropdownMenuTrigger asChild><Button variant="ghost" size="icon-sm" disabled={disabled}>- <SlidersHorizontal className="size-4" />+ <SlidersHorizontal /></Button>- </PopoverTrigger>- <PopoverContent align="start" className="w-80 max-h-96 overflow-y-auto">- <PopoverHeader>- <PopoverTitle>{t('model-parameters.title')}</PopoverTitle>- <PopoverDescription>{t('model-parameters.description')}</PopoverDescription>- </PopoverHeader>- {entries.length === 0 ? (- <p className="text-muted-foreground text-xs">{t('model-parameters.empty')}</p>- ) : (- <div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3">- {entries.map(([key, prop]) => {- const effectiveType =- prop.type ??- prop.anyOf?.find((t) => t.type !== 'null')?.type ??- 'string';- const isBoolean = effectiveType === 'boolean';- const isNumber =- effectiveType === 'number' || effectiveType === 'integer';- const label = prop.title ?? key;- const isRequired = required.includes(key);+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="min-w-40">+ {/* ----- Fallback model selection ----- */}+ {/* The sub-trigger reflects the current fallback selection so the+ user can see the active model without drilling in. The label+ is truncated with an ellipsis to keep the trigger on one line+ when the model name is long. */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="truncate">+ {selectedFallbackModel+ ? t('model-parameters.fallbackLabelWithModel', {+ model: selectedFallbackModel.model,+ })+ : t('model-parameters.fallbackLabel')}+ </span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 overflow-y-auto">+ {!hasFallbackOptions ? (+ <div className="px-2 py-3 text-center text-sm text-muted-foreground">+ <p>{t('llm-select.empty.title')}</p>+ </div>+ ) : (+ Object.entries(groups).map(([type, items], idx) => (+ <div key={type}>+ {idx > 0 && <DropdownMenuSeparator />}+ <DropdownMenuLabel>+ {type.replace(/_credential$/, '')}+ </DropdownMenuLabel>+ {items.flatMap(({ credential, models }) =>+ models.map((m) => {+ const isSelected =+ selectedFallbackModel?.credential_id ===+ credential.id &&+ selectedFallbackModel?.model === m.name;+ // Checkbox-style indicator: a check appears next+ // to the active fallback. Toggling off the active+ // item clears the selection (mirrors the explicit+ // "No fallback" entry below).+ return (+ <DropdownMenuCheckboxItem+ key={`${credential.id}-${m.name}`}+ checked={isSelected}+ onCheckedChange={(checked) => {+ if (checked) {+ handleSelectFallback(+ type,+ credential.id,+ m.name,+ );+ } else {+ onFallbackChange(null);+ }+ }}+ >+ {m.label}+ </DropdownMenuCheckboxItem>+ );+ }),+ )}+ </div>+ ))+ )}+ <DropdownMenuSeparator />+ {/* "No fallback" is checked exactly when no fallback is set,+ making the list behave like a single-select group. Clicking+ it while already checked is a no-op. */}+ <DropdownMenuCheckboxItem+ checked={!selectedFallbackModel}+ onCheckedChange={(checked) => {+ if (checked) onFallbackChange(null);+ }}+ >+ {t('llm-select.noFallback')}+ </DropdownMenuCheckboxItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>- if (isBoolean) {- return (- <>- <Label- key={`${key}-label`}- htmlFor={`param-${key}`}- className="whitespace-nowrap"- >- {label}- </Label>- <Switch- key={`${key}-input`}- id={`param-${key}`}- checked={- values[key] !== undefined- ? !!values[key]- : !!prop.default- }- onCheckedChange={(checked) =>- handleChange(key, !!checked)- }- />- </>- );- }+ {/* ----- Primary model parameters ----- */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ {t('model-parameters.parametersLabel')}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-80 max-h-96 overflow-y-auto p-3">+ <div className="mb-3">+ <p className="text-sm font-medium">{t('model-parameters.title')}</p>+ <p className="text-muted-foreground text-xs">+ {t('model-parameters.description')}+ </p>+ </div>+ {entries.length === 0 ? (+ <p className="text-muted-foreground text-xs">+ {t('model-parameters.empty')}+ </p>+ ) : (+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3">+ {entries.map(([key, prop]) => {+ const effectiveType =+ prop.type ??+ prop.anyOf?.find((t) => t.type !== 'null')?.type ??+ 'string';+ const isBoolean = effectiveType === 'boolean';+ const isNumber =+ effectiveType === 'number' || effectiveType === 'integer';+ const label = prop.title ?? key;+ const isRequired = required.includes(key);++ if (isBoolean) {+ return (+ <div+ key={key}+ className="contents"+ // Keep clicks/keys inside the form from+ // closing the dropdown menu.+ onPointerDown={(e) => e.stopPropagation()}+ onKeyDown={(e) => e.stopPropagation()}+ >+ <Label+ htmlFor={`param-${key}`}+ className="whitespace-nowrap"+ >+ {label}+ </Label>+ <Switch+ id={`param-${key}`}+ checked={+ values[key] !== undefined+ ? !!values[key]+ : !!prop.default+ }+ onCheckedChange={(checked) =>+ handleChange(key, !!checked)+ }+ />+ </div>+ );+ }- return (- <>- <Label- key={`${key}-label`}- htmlFor={`param-${key}`}- className="whitespace-nowrap"- >- {label}- {isRequired && (- <span className="text-destructive ml-0.5">*</span>- )}- </Label>- <Input- key={`${key}-input`}- id={`param-${key}`}- type={isNumber ? 'number' : 'text'}- value={values[key] !== undefined ? String(values[key]) : ''}- placeholder={- prop.default !== undefined- ? String(prop.default)- : undefined- }- min={prop.minimum}- max={prop.maximum}- step={- isNumber && effectiveType === 'number'- ? 'any'- : undefined- }- onChange={(e) => {- const raw = e.target.value;- if (isNumber) {- handleChange(- key,- raw === '' ? undefined : Number(raw),- );- } else {- handleChange(key, raw);- }- }}- onBlur={(e) => {- if (!isNumber || e.target.value === '') return;- let num = Number(e.target.value);- if (prop.minimum !== undefined && num < prop.minimum)- num = prop.minimum;- if (prop.maximum !== undefined && num > prop.maximum)- num = prop.maximum;- if (- prop.exclusiveMinimum !== undefined &&- num <= prop.exclusiveMinimum- )- num =- prop.exclusiveMinimum +- (effectiveType === 'integer'- ? 1- : Number.EPSILON);- if (- prop.exclusiveMaximum !== undefined &&- num >= prop.exclusiveMaximum- )- num =- prop.exclusiveMaximum -- (effectiveType === 'integer'- ? 1- : Number.EPSILON);- if (num !== Number(e.target.value))- handleChange(key, num);- }}- />- </>- );- })}- </div>- )}- </PopoverContent>- </Popover>+ return (+ <div+ key={key}+ className="contents"+ onPointerDown={(e) => e.stopPropagation()}+ onKeyDown={(e) => e.stopPropagation()}+ >+ <Label+ htmlFor={`param-${key}`}+ className="whitespace-nowrap"+ >+ {label}+ {isRequired && (+ <span className="text-destructive ml-0.5">+ *+ </span>+ )}+ </Label>+ <Input+ id={`param-${key}`}+ type={isNumber ? 'number' : 'text'}+ value={+ values[key] !== undefined+ ? String(values[key])+ : ''+ }+ placeholder={+ prop.default !== undefined+ ? String(prop.default)+ : undefined+ }+ min={prop.minimum}+ max={prop.maximum}+ step={+ isNumber && effectiveType === 'number'+ ? 'any'+ : undefined+ }+ onChange={(e) => {+ const raw = e.target.value;+ if (isNumber) {+ handleChange(+ key,+ raw === '' ? undefined : Number(raw),+ );+ } else {+ handleChange(key, raw);+ }+ }}+ onBlur={(e) => {+ if (!isNumber || e.target.value === '') return;+ let num = Number(e.target.value);+ if (+ prop.minimum !== undefined &&+ num < prop.minimum+ )+ num = prop.minimum;+ if (+ prop.maximum !== undefined &&+ num > prop.maximum+ )+ num = prop.maximum;+ if (+ prop.exclusiveMinimum !== undefined &&+ num <= prop.exclusiveMinimum+ )+ num =+ prop.exclusiveMinimum ++ (effectiveType === 'integer'+ ? 1+ : Number.EPSILON);+ if (+ prop.exclusiveMaximum !== undefined &&+ num >= prop.exclusiveMaximum+ )+ num =+ prop.exclusiveMaximum -+ (effectiveType === 'integer'+ ? 1+ : Number.EPSILON);+ if (num !== Number(e.target.value))+ handleChange(key, num);+ }}+ />+ </div>+ );+ })}+ </div>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuContent>+ </DropdownMenu>);}diff --git a/examples/web_ui/frontend/src/components/select/LlmSelect.tsx b/examples/web_ui/frontend/src/components/select/LlmSelect.tsxindex 4ecff6bd3..05a221290 100644--- a/examples/web_ui/frontend/src/components/select/LlmSelect.tsx+++ b/examples/web_ui/frontend/src/components/select/LlmSelect.tsx@@ -1,4 +1,4 @@-import { ChevronDown, PlusCircle } from 'lucide-react';+import { ChevronDown, PlusCircle, Ban } from 'lucide-react';import { useEffect } from 'react';import type { ChatModelConfig } from '@/api';@@ -20,12 +20,33 @@ import { useTranslation } from '@/i18n/useI18n.ts';interface Props {value?: ChatModelConfig | null;- onChange?: (value: ChatModelConfig) => void;+ /**+ * Called when the user selects a model, or — when `allowClear` is true —+ * clears the selection (in which case `null` is emitted).+ */+ onChange?: (value: ChatModelConfig | null) => void;onAddCredential?: () => void;refetchTrigger?: number;+ /** Override the trigger label shown when no model is selected. */+ placeholder?: string;+ /**+ * When true, append a "clear selection" item to the dropdown that emits+ * `null` via `onChange`. Used by the fallback selector.+ */+ allowClear?: boolean;+ /** Override the label of the "clear selection" item. */+ clearLabel?: string;}-export function LlmSelect({ value, onChange, onAddCredential, refetchTrigger }: Props) {+export function LlmSelect({+ value,+ onChange,+ onAddCredential,+ refetchTrigger,+ placeholder,+ allowClear = false,+ clearLabel,+}: Props) {const { groups, loading, refetch } = useAvailableModels();const { t } = useTranslation();const hasOptions = Object.keys(groups).length > 0;@@ -42,7 +63,7 @@ export function LlmSelect({ value, onChange, onAddCredential, refetchTrigger }:? value.model: loading? t('llm-select.loading')- : t('llm-select.placeholder');+ : (placeholder ?? t('llm-select.placeholder'));return (<DropdownMenu>@@ -115,6 +136,12 @@ export function LlmSelect({ value, onChange, onAddCredential, refetchTrigger }:}))}<DropdownMenuSeparator />+ {allowClear && (+ <DropdownMenuItem onSelect={() => onChange?.(null)} disabled={!value}>+ <Ban className="size-4" />+ <span>{clearLabel ?? t('llm-select.clear')}</span>+ </DropdownMenuItem>+ )}<DropdownMenuItem onSelect={onAddCredential}><PlusCircle className="size-4" /><span>{t('llm-select.addCredential')}</span>diff --git a/examples/web_ui/frontend/src/components/ui/collapsible.tsx b/examples/web_ui/frontend/src/components/ui/collapsible.tsxnew file mode 100644index 000000000..4db5fc6a9--- /dev/null+++ b/examples/web_ui/frontend/src/components/ui/collapsible.tsx@@ -0,0 +1,19 @@+import { Collapsible as CollapsiblePrimitive } from 'radix-ui';++function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {+ return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;+}++function CollapsibleTrigger({+ ...props+}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {+ return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />;+}++function CollapsibleContent({+ ...props+}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {+ return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />;+}++export { Collapsible, CollapsibleTrigger, CollapsibleContent };diff --git a/examples/web_ui/frontend/src/hooks/useAgentSchema.ts b/examples/web_ui/frontend/src/hooks/useAgentSchema.tsnew file mode 100644index 000000000..9e25ca0f2--- /dev/null+++ b/examples/web_ui/frontend/src/hooks/useAgentSchema.ts@@ -0,0 +1,38 @@+import { useEffect, useState } from 'react';++import { agentApi } from '@/api';+import type { AgentSchemaResponse } from '@/api';++/**+ * Module-level cache. The agent schema is derived from Pydantic models+ * on the backend and never changes at runtime, so a single in-flight fetch+ * is enough for the whole session.+ */+let cached: AgentSchemaResponse | null = null;+let inflight: Promise<AgentSchemaResponse> | null = null;++async function loadSchema(): Promise<AgentSchemaResponse> {+ if (cached) return cached;+ if (!inflight) {+ inflight = agentApi.getSchema().then((res) => {+ cached = res;+ return res;+ });+ }+ return inflight;+}++/** Fetch (and cache) the JSON Schema fragments for the agent form. */+export function useAgentSchema() {+ const [schema, setSchema] = useState<AgentSchemaResponse | null>(cached);+ const [error, setError] = useState<Error | null>(null);++ useEffect(() => {+ if (cached) return;+ loadSchema()+ .then(setSchema)+ .catch((e: Error) => setError(e));+ }, []);++ return { schema, loading: schema === null && error === null, error };+}diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex 448de2411..ff9736fb4 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -40,7 +40,10 @@"moreLines": "... {{count}} more lines","read": {"name": "Read",- "fileCount": "{{count}} file(s)"+ "fileCount_one": "{{count}} file",+ "fileCount_other": "{{count}} files",+ "lineCount_one": "Read {{formatted}} line",+ "lineCount_other": "Read {{formatted}} lines"},"glob": {"name": "Glob"@@ -61,7 +64,8 @@"yesWithRule": "Yes, and allow {{toolName}} to execute {{ruleContent}} for this session"},"messageBubble": {- "thinking": "Thinking"+ "thinking": "Thinking",+ "running": "Running..."},"chat": {"inputPlaceholder": "Type a message...",@@ -86,39 +90,29 @@},"dialog-agent-create": {"title": "Create agent",- "trigger": "Create agent",+ "trigger": "Create agent"+ },+ "agent-form": {"identity": {"legend": "Agent Identity","description": "Name and instructions that define this agent's behaviour.","name": { "label": "Name", "placeholder": "My agent" },- "systemPrompt": {- "label": "System prompt",- "placeholder": "You're a helpful assistant."- }+ "system-prompt": { "label": "System prompt" }},- "contextConfig": {+ "context-config": {"legend": "Context Config","description": "Controls how the context window is managed and compressed.",- "triggerRatio": { "label": "Trigger ratio", "placeholder": "e.g. 0.75 (0.01–0.89)" },- "reserveRatio": { "label": "Reserve ratio", "placeholder": "e.g. 0.25 (0.01–0.89)" },- "toolResultLimit": {- "label": "Tool result limit",- "placeholder": "Max chars per tool result"- },- "compressionPrompt": {- "label": "Compression prompt",- "placeholder": "Override the default compression instruction"- },- "summaryTemplate": {- "label": "Summary template",- "placeholder": "Override the default summary output template"- }+ "trigger-ratio": { "label": "Trigger ratio" },+ "reserve-ratio": { "label": "Reserve ratio" },+ "tool-result-limit": { "label": "Tool result limit" },+ "compression-prompt": { "label": "Compression prompt" },+ "summary-template": { "label": "Summary template" }},- "reactConfig": {+ "react-config": {"legend": "ReAct Config","description": "Controls the reasoning and action loop behaviour.",- "maxIters": { "label": "Max iterations", "placeholder": "Max ReAct loop iterations" },- "stopOnReject": { "label": "Stop on reject" }+ "max-iters": { "label": "Max iterations" },+ "stop-on-reject": { "label": "Stop on reject" }}},"dialog-agent-edit": {@@ -171,13 +165,16 @@},"llm-select": {"placeholder": "Select a model",+ "fallbackPlaceholder": "Fallback model","loading": "Loading…","empty": {"title": "No models available","description": "Add a credential to get started.","addButton": "Add credential"},- "addCredential": "Add Credential"+ "addCredential": "Add Credential",+ "clear": "Clear selection",+ "noFallback": "No fallback"},"permission-mode": {"placeholder": "Select permission mode",@@ -258,7 +255,10 @@"model-parameters": {"title": "Model Parameters","description": "Adjust inference parameters for the selected model.",- "empty": "No configurable parameters."+ "empty": "No configurable parameters.",+ "fallbackLabel": "Fallback model",+ "fallbackLabelWithModel": "Fallback model ({{model}})",+ "parametersLabel": "Parameters"},"setup": {"title": "Connect to Service",diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex f926c642f..262fac779 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -40,7 +40,10 @@"moreLines": "... 还有 {{count}} 行","read": {"name": "读取",- "fileCount": "{{count}} 个文件"+ "fileCount_one": "{{count}} 个文件",+ "fileCount_other": "{{count}} 个文件",+ "lineCount_one": "读取 {{formatted}} 行",+ "lineCount_other": "读取 {{formatted}} 行"},"glob": {"name": "Glob"@@ -61,7 +64,8 @@"yesWithRule": "是,且该次对话中都允许 {{toolName}} 执行 {{ruleContent}}"},"messageBubble": {- "thinking": "思考中"+ "thinking": "思考中",+ "running": "运行中..."},"chat": {"inputPlaceholder": "输入消息...",@@ -86,30 +90,29 @@},"dialog-agent-create": {"title": "创建 Agent",- "trigger": "创建 Agent",+ "trigger": "创建 Agent"+ },+ "agent-form": {"identity": {"legend": "Agent 身份","description": "定义此 Agent 行为的名称和指令。","name": { "label": "名称", "placeholder": "我的 Agent" },- "systemPrompt": { "label": "系统提示词", "placeholder": "你是一个有帮助的助手。" }+ "system-prompt": { "label": "系统提示词" }},- "contextConfig": {+ "context-config": {"legend": "上下文配置","description": "控制上下文窗口的管理和压缩方式。",- "triggerRatio": { "label": "触发比例", "placeholder": "例如 0.75(0.01–0.89)" },- "reserveRatio": { "label": "保留比例", "placeholder": "例如 0.25(0.01–0.89)" },- "toolResultLimit": {- "label": "工具结果限制",- "placeholder": "每个工具结果的最大字符数"- },- "compressionPrompt": { "label": "压缩提示词", "placeholder": "覆盖默认压缩指令" },- "summaryTemplate": { "label": "摘要模板", "placeholder": "覆盖默认摘要输出模板" }+ "trigger-ratio": { "label": "触发比例" },+ "reserve-ratio": { "label": "保留比例" },+ "tool-result-limit": { "label": "工具结果限制" },+ "compression-prompt": { "label": "压缩提示词" },+ "summary-template": { "label": "摘要模板" }},- "reactConfig": {+ "react-config": {"legend": "ReAct 配置","description": "控制推理和行动循环的行为。",- "maxIters": { "label": "最大迭代次数", "placeholder": "ReAct 循环最大迭代次数" },- "stopOnReject": { "label": "拒绝时停止" }+ "max-iters": { "label": "最大迭代次数" },+ "stop-on-reject": { "label": "拒绝时停止" }}},"dialog-agent-edit": {@@ -162,13 +165,16 @@},"llm-select": {"placeholder": "选择模型",+ "fallbackPlaceholder": "兜底模型","loading": "加载中…","empty": {"title": "暂无可用模型","description": "请先添加凭证。","addButton": "添加凭证"},- "addCredential": "添加凭证"+ "addCredential": "添加凭证",+ "clear": "清除选择",+ "noFallback": "无兜底模型"},"permission-mode": {"placeholder": "选择权限模式",@@ -249,7 +255,10 @@"model-parameters": {"title": "模型参数","description": "调整所选模型的推理参数。",- "empty": "暂无可配置参数。"+ "empty": "暂无可配置参数。",+ "fallbackLabel": "兜底模型",+ "fallbackLabelWithModel": "兜底模型({{model}})",+ "parametersLabel": "参数"},"setup": {"title": "连接到服务器",diff --git a/examples/web_ui/frontend/src/index.css b/examples/web_ui/frontend/src/index.cssindex 1f350b61a..76003e9ad 100644--- a/examples/web_ui/frontend/src/index.css+++ b/examples/web_ui/frontend/src/index.css@@ -3,6 +3,8 @@@import 'shadcn/tailwind.css';@import '@fontsource-variable/geist';+@plugin '@tailwindcss/typography';+html,body,#root {diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsxindex 963a40687..c386394b3 100644--- a/examples/web_ui/frontend/src/pages/chat/index.tsx+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx@@ -90,6 +90,12 @@ const ChatPageInner = () => {const [sidebarOpen, setSidebarOpen] = useState(true);const [selectedModel, setSelectedModel] = useState<ChatModelConfig | null>(null);+ // Fallback model used when the primary model fails. `null` means none.+ // Unlike the primary model, we never auto-select a fallback — the user+ // must opt in explicitly.+ const [selectedFallbackModel, setSelectedFallbackModel] = useState<ChatModelConfig | null>(+ null,+ );const [selectedPermissionMode, setSelectedPermissionMode] = useState<string>('default');const [editOpen, setEditOpen] = useState(false);const [deleteOpen, setDeleteOpen] = useState(false);@@ -198,6 +204,9 @@ const ChatPageInner = () => {setSelectedModel(null);}}++ // Fallback is purely opt-in: mirror what's persisted, never auto-select.+ setSelectedFallbackModel(session?.config.fallback_chat_model_config ?? null);}, [selectedSessionId, sessions, groups]);// Sync selectedPermissionMode when switching sessions.@@ -208,7 +217,11 @@ const ChatPageInner = () => {setSelectedPermissionMode(mode ?? 'default');}, [selectedSessionId]);- const handleLlmChange = async (config: ChatModelConfig) => {+ // Primary selector does not enable `allowClear`, so `config` is always+ // non-null in practice; the union below just satisfies the shared+ // `LlmSelect` callback signature.+ const handleLlmChange = async (config: ChatModelConfig | null) => {+ if (!config) return;setSelectedModel(config);if (selectedSessionId && selectedAgentId) {await updateSession(selectedSessionId, { chat_model_config: config });@@ -224,11 +237,23 @@ const ChatPageInner = () => {}};+ // Fallback selector emits `null` when the user clears the selection.+ // Persist the change to the active session if one exists.+ const handleFallbackChange = async (config: ChatModelConfig | null) => {+ setSelectedFallbackModel(config);+ if (selectedSessionId && selectedAgentId) {+ await updateSession(selectedSessionId, {+ fallback_chat_model_config: config,+ });+ }+ };+const handleCreateSession = async () => {if (!selectedAgentId) return;const res = await createSession({agent_id: selectedAgentId,...(selectedModel ? { chat_model_config: selectedModel } : {}),+ ...(selectedFallbackModel ? { fallback_chat_model_config: selectedFallbackModel } : {}),});setSelectedSessionId(res.session_id);};@@ -432,10 +457,17 @@ const ChatPageInner = () => {onAddCredential={() => setCredentialOpen(true)}refetchTrigger={credentialRefetchTrigger}/>+ {/*+ * Combined settings dropdown: fallback model + parameter+ * editing for the primary model. Disabled until a primary+ * model is selected.+ */}<ModelParametersPopoverselectedModel={selectedModel}modelCard={selectedModelCard}onChange={handleParametersChange}+ selectedFallbackModel={selectedFallbackModel}+ onFallbackChange={handleFallbackChange}/></div><div id="tour-permission-mode" className="flex flex-row gap-x-2">diff --git a/examples/web_ui/frontend/src/utils/common.ts b/examples/web_ui/frontend/src/utils/common.tsindex 965647b88..aab8b8bf8 100644--- a/examples/web_ui/frontend/src/utils/common.ts+++ b/examples/web_ui/frontend/src/utils/common.ts@@ -71,47 +71,26 @@ export const formatDuration = (seconds: number): number => {};/**- * Format a duration in seconds into a human-readable string with appropriate units (seconds, minutes, hours).+ * Format a duration in seconds into a human-readable, compact string.+ *+ * - Integer-only output (e.g. `45s`, `2min30s`, `3h`); no decimals.+ * - Adjacent unit segments are concatenated without spaces.+ * - Once the leading unit is hours, only whole hours are shown — minute and+ * second precision is not useful at that scale and would only widen the+ * badge when, e.g., a tool call sits awaiting user confirmation for hours.** @param seconds - The duration in seconds to format- * @param decimals - The number of decimal places to show (default: 1)- * @returns Formatted string with appropriate time unit (e.g., "45.2s", "2m 30.0s", "1h 15m 30.5s")+ * @returns Formatted string (e.g., "45s", "2min30s", "3h")*/-export const formatTime = (seconds: number, decimals: number = 1): string => {- // If duration is less than 60 seconds, display in seconds with specified decimal places- if (seconds < 60) {- return `${seconds.toFixed(decimals)}s`;- }- // If duration is between 60 seconds and 1 hour, display in minutes and seconds- else if (seconds < 3600) {- const minutes = Math.floor(seconds / 60);- const remainingSeconds = seconds % 60;- // If there are no remaining seconds, only show minutes- if (remainingSeconds === 0) {- return `${minutes}min`;- }- // Otherwise, show both minutes and seconds with specified decimal places- return `${minutes}min ${remainingSeconds.toFixed(decimals)}s`;+export const formatTime = (seconds: number): string => {+ const total = Math.floor(seconds);+ if (total < 60) {+ return `${total}s`;}- // If duration is 1 hour or more, display in hours, minutes, and seconds- else {- const hours = Math.floor(seconds / 3600);- const minutes = Math.floor((seconds % 3600) / 60);- const remainingSeconds = seconds % 60;-- // Only show hours if minutes and seconds are both zero- if (minutes === 0 && remainingSeconds === 0) {- return `${hours}h`;- }- // Show hours and minutes if seconds is zero- else if (remainingSeconds === 0) {- return `${hours}h ${minutes}min`;- }- // Show hours and seconds if minutes is zero- else if (minutes === 0) {- return `${hours}h ${remainingSeconds.toFixed(decimals)}s`;- }- // Show all components: hours, minutes, and seconds- return `${hours}h ${minutes}min ${remainingSeconds.toFixed(decimals)}s`;+ if (total < 3600) {+ const minutes = Math.floor(total / 60);+ const remaining = total % 60;+ return remaining === 0 ? `${minutes}min` : `${minutes}min${remaining}s`;}+ return `${Math.floor(total / 3600)}h`;};diff --git a/examples/web_ui/pnpm-lock.yaml b/examples/web_ui/pnpm-lock.yamlindex 46e22833a..0408d9766 100644--- a/examples/web_ui/pnpm-lock.yaml+++ b/examples/web_ui/pnpm-lock.yaml@@ -58,8 +58,8 @@ importers:frontend:dependencies:'@agentscope-ai/agentscope':- specifier: ^0.0.5- version: 0.0.5+ specifier: ^0.0.6+ version: 0.0.6'@fontsource-variable/geist':specifier: ^5.2.8version: 5.2.8@@ -129,6 +129,9 @@ importers:shadcn:specifier: ^4.7.0+ shadcn-prose:+ specifier: ^1.2.1+ version: 1.2.1sonner:specifier: ^2.0.7@@ -148,6 +151,9 @@ importers:'@eslint/js':specifier: ^10.0.1version: 10.0.1([email protected]([email protected]))+ '@tailwindcss/typography':+ specifier: ^0.5.19+ version: 0.5.19([email protected])'@types/mime-types':specifier: ^3.0.1version: 3.0.1@@ -193,8 +199,8 @@ importers:packages:- '@agentscope-ai/[email protected]':- resolution: {integrity: sha512-luEpnLrTLM7bpjgZdDFAwSMDx8S7qIA0l2OM+PdDqOUBJUzkjRvlYEI8Dm+UvnWDQjmxnd6R7PFK6cJrjFPAAg==}+ '@agentscope-ai/[email protected]':+ resolution: {integrity: sha512-qQdcXK9GT6kkxsXKhpKg8MuEFjPJHci8NKXCqoCr3Fx/r2bHK7jzhkJblzXM+kmmrzC/4OXmjCWcvUbEP0pkgQ==}'@babel/[email protected]':resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}@@ -1739,6 +1745,11 @@ packages:resolution: {integrity: sha512-F7HZGBeN9I0/AuuJS5PwcD8xayx5ri5GhjYUDBEVYUkexyA/giwbDNjRVrxSezE3T250OU2K/wp/ltWx3UOefg==}engines: {node: '>= 20'}+ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-w31dd8HOx3k9vPtcQh5QHP9GwKcgbMp87j58qi6xgiBnFFtKEAgCWnDw4qUT8aHwkCp8bKvb/KGKWWHedP0AAg==}+ peerDependencies:+ tailwindcss: '>=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1'+'@tailwindcss/[email protected]':resolution: {integrity: sha512-t6J3OrB5Fc0ExuhohouH0fWUGMYL6PTLhW+E7zIk/pdbnJARZDCwjBznFnkh5ynRnIRSI4YjtTH0t6USjJISrw==}peerDependencies:@@ -3614,8 +3625,8 @@ packages:resolution: {integrity: sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw==}engines: {node: '>=20'}- resolution: {integrity: sha512-AoMplt2UalrpgUDMh3L09QWjNRlgJPipclQvA6sYAaeF6nHNBMgmikAZGmcYLn8on4d9sQY9Q8bOLfrBS7Lc8g==}+ resolution: {integrity: sha512-O61LIsimY3acVabwvomwFhwrnN36yvHY2quIfy9keEcFytGgWeV35yLHQ6NVMLSBxRpHmcg2yuhCnlu2HT4pLQ==}hasBin: truepeerDependencies:ws: ^8.18.0@@ -3707,6 +3718,10 @@ packages:resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}engines: {node: '>=16.20.0'}+ resolution: {integrity: sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==}+ engines: {node: '>=4'}+resolution: {integrity: sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==}engines: {node: '>=4'}@@ -3993,6 +4008,10 @@ packages:resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}+ resolution: {integrity: sha512-WKYSb3lZ4/iC7YPrZP8HeO1ywQJE94iuBrTaUmPm0C3tPrM+ymWVmKyuzabCTtAkqWQAPOO7SOB40UcDuzsxyw==}+ deprecated: 'You can now install this as a shadcn component with: npx kibo-ui add typography'+resolution: {integrity: sha512-70fwnesNrY1GgeD7Kdzn+3SsYeyfibm8immsA5L68+OusoPTvYF01oWExl8/latKpMpvVXcbgdbbE6VFBJQ38w==}hasBin: true@@ -4567,7 +4586,7 @@ packages:snapshots:- '@agentscope-ai/[email protected]':+ '@agentscope-ai/[email protected]':dependencies:'@cfworker/json-schema': 4.1.1'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])@@ -4575,7 +4594,7 @@ snapshots:jsonrepair: 3.14.0mime-types: 3.0.2ollama: 0.6.3- openai: 6.38.0([email protected])+ openai: 6.39.0([email protected])string-format: 2.0.0uuid: 13.0.2zod: 4.4.3@@ -6113,6 +6132,11 @@ snapshots:'@tailwindcss/oxide-win32-arm64-msvc': 4.3.0'@tailwindcss/oxide-win32-x64-msvc': 4.3.0+ '@tailwindcss/[email protected]([email protected])':+ dependencies:+ postcss-selector-parser: 6.0.10+ tailwindcss: 4.3.0+'@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:'@tailwindcss/node': 4.3.0@@ -8131,7 +8155,7 @@ snapshots:powershell-utils: 0.1.0wsl-utils: 0.3.1optionalDependencies:zod: 4.4.3@@ -8215,6 +8239,11 @@ snapshots:+ dependencies:+ cssesc: 3.0.0+ util-deprecate: 1.0.2+dependencies:cssesc: 3.0.0@@ -8611,6 +8640,8 @@ snapshots:+ [email protected]: {}+dependencies:'@babel/core': 7.29.0diff --git a/pyproject.toml b/pyproject.tomlindex 88ddd7f83..be1137758 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -89,8 +89,6 @@ dev = ["pre-commit","pytest","pytest-forked",- "sphinx-gallery",- "furo","myst_parser","matplotlib","fakeredis",diff --git a/src/agentscope/agent/__init__.py b/src/agentscope/agent/__init__.pyindex a1628c8bd..39a93b8b5 100644--- a/src/agentscope/agent/__init__.py+++ b/src/agentscope/agent/__init__.py@@ -1,6 +1,6 @@# -*- coding: utf-8 -*-"""Initialize the agent module."""from ._agent import Agent-from ._config import ContextConfig, ReActConfig+from ._config import ContextConfig, ModelConfig, ReActConfig-__all__ = ["Agent", "ContextConfig", "ReActConfig"]+__all__ = ["Agent", "ContextConfig", "ModelConfig", "ReActConfig"]diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex 12dfa228e..a6202509f 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -1958,8 +1958,17 @@ class Agent:models.append(self.model_config.fallback_model)last_exception = None- for model in models:- for _ in range(self.model_config.max_retries):+ # ``max_retries`` is the number of retries on top of the initial+ # call (mirrors ``ChatModelBase.max_retries``), so total attempts+ # per model is ``max_retries + 1``.+ for index, model in enumerate(models):+ if index > 0:+ logger.info(+ "Fallback to model '%s'",+ model.model,+ )++ for attempt in range(self.model_config.max_retries + 1):try:# Apply middleware to wrap the actual model() callif not self._model_call_middlewares:@@ -2013,15 +2022,28 @@ class Agent:return await execute_chain()except Exception as e:- logger.warning(- "Model %s call failed for agent %s. "- "Retrying (%d/%d)...",- model.model,- self.name,- _ + 1,- self.model_config.max_retries,- )last_exception = e+ # Only log a "Retrying" message when there's actually a+ # next attempt left for this model. When ``max_retries=0``+ # or the last retry has been used, the outer loop either+ # falls over to the fallback or raises.+ if attempt < self.model_config.max_retries:+ logger.warning(+ "Model %s call failed for agent %s. "+ "Retrying (%d/%d)...",+ model.model,+ self.name,+ attempt + 1,+ self.model_config.max_retries,+ )+ else:+ logger.warning(+ "Model %s exhausted all %d attempt(s) "+ "for agent %s.",+ model.model,+ self.model_config.max_retries + 1,+ self.name,+ )if last_exception:raise last_exception from Nonediff --git a/src/agentscope/agent/_config.py b/src/agentscope/agent/_config.pyindex d50046594..dc85eb3bd 100644--- a/src/agentscope/agent/_config.py+++ b/src/agentscope/agent/_config.py@@ -68,32 +68,41 @@ class ContextConfig(BaseModel):"""The ratio of the tokens to reserve in context compression, which shouldbe smaller than the trigger ratio."""- compression_prompt: str = (- "<system-hint>You have been working on the task described above "- "but have not yet completed it. "- "Now write a continuation summary that will allow you to resume "- "work efficiently in a future context window where the "- "conversation history will be replaced with this summary. "- "Your summary should be structured, concise, and actionable."- "</system-hint>"+ compression_prompt: str = Field(+ default=(+ "<system-hint>You have been working on the task described above "+ "but have not yet completed it. "+ "Now write a continuation summary that will allow you to resume "+ "work efficiently in a future context window where the "+ "conversation history will be replaced with this summary. "+ "Your summary should be structured, concise, and actionable."+ "</system-hint>"+ ),+ # ``format: textarea`` is a hint for schema-driven UI renderers+ # to use a multi-line input. Plain JSON Schema doesn't natively+ # express this, so we piggy-back on ``json_schema_extra``.+ json_schema_extra={"format": "textarea"},)"""The prompt used to guide the compression model to generate thecompressed summary, which will be wrapped into a user message andattach to the end of the current memory."""- summary_template: str = (- "<system-info>Here is a summary of your previous work\n"- "# Task Overview\n"- "{task_overview}\n\n"- "# Current State\n"- "{current_state}\n\n"- "# Important Discoveries\n"- "{important_discoveries}\n\n"- "# Next Steps\n"- "{next_steps}\n\n"- "# Context to Preserve\n"- "{context_to_preserve}"- "</system-info>"+ summary_template: str = Field(+ default=(+ "<system-info>Here is a summary of your previous work\n"+ "# Task Overview\n"+ "{task_overview}\n\n"+ "# Current State\n"+ "{current_state}\n\n"+ "# Important Discoveries\n"+ "{important_discoveries}\n\n"+ "# Next Steps\n"+ "{next_steps}\n\n"+ "# Context to Preserve\n"+ "{context_to_preserve}"+ "</system-info>"+ ),+ json_schema_extra={"format": "textarea"},)"""The string template to present the compressed summary to the agent,which will be formatted with the fields from the@@ -146,12 +155,19 @@ class ModelConfig(BaseModel):model_config = {"arbitrary_types_allowed": True}max_retries: int = Field(- default=3,- gt=0,- description="Maximum number of retries when the model call fails.",+ default=0,+ ge=0,+ description=(+ "Number of retries on top of the initial call before falling "+ "over to the fallback model. ``0`` means call the model exactly "+ "once and immediately move to the fallback on failure. Same "+ "semantics as ``ChatModelBase.max_retries``. Defaults to 0 to "+ "avoid compounding with the model's own inner retry loop."+ ),)- """The maximum number of retries when the model call fails. Must be- greater than 0."""+ """Number of retries on top of the initial call before falling over to+ the fallback model. ``0`` means a single attempt with no retries.+ Mirrors the semantics of ``ChatModelBase.max_retries``."""fallback_model: ChatModelBase | None = Field(default=None,diff --git a/src/agentscope/app/__init__.py b/src/agentscope/app/__init__.pyindex 833fbb31e..262f2e226 100644--- a/src/agentscope/app/__init__.py+++ b/src/agentscope/app/__init__.py@@ -20,6 +20,8 @@ from .storage import (from ._manager import (WorkspaceManagerBase,LocalWorkspaceManager,+ DockerWorkspaceManager,+ E2BWorkspaceManager,BackgroundTaskManager,SchedulerManager,SessionManager,@@ -39,6 +41,8 @@ __all__ = ["WorkspaceManagerBase","BackgroundTaskManager","LocalWorkspaceManager",+ "DockerWorkspaceManager",+ "E2BWorkspaceManager","BackgroundTaskManager","SchedulerManager","SessionManager",diff --git a/src/agentscope/app/_manager/_docker_workspace_manager.py b/src/agentscope/app/_manager/_docker_workspace_manager.pyindex 385de057c..4a34ade4c 100644--- a/src/agentscope/app/_manager/_docker_workspace_manager.py+++ b/src/agentscope/app/_manager/_docker_workspace_manager.py@@ -60,7 +60,7 @@ class DockerWorkspaceManager(WorkspaceManagerBase):basedir: str,*,base_image: str = DEFAULT_BASE_IMAGE,- node_version: str | None = None,+ node_version: str = "20",extra_pip: list[str] | None = None,gateway_port: int = DEFAULT_GATEWAY_PORT,env: dict[str, str] | None = None,@@ -79,9 +79,9 @@ class DockerWorkspaceManager(WorkspaceManagerBase):container.base_image (`str`, defaults to `DEFAULT_BASE_IMAGE`):Base Docker image; must provide ``python3``.- node_version (`str | None`, optional):+ node_version (`str`, defaults to `"20"`):Major Node.js version (e.g. ``"20"``) to bake into- the image, or ``None`` to skip Node.+ the image.extra_pip (`list[str] | None`, optional):Extra Python packages to install into the gatewayvenv at image-build time.diff --git a/src/agentscope/app/_middleware/_tool_offload_middleware.py b/src/agentscope/app/_middleware/_tool_offload_middleware.pyindex 8d968e3e6..a37c412ee 100644--- a/src/agentscope/app/_middleware/_tool_offload_middleware.py+++ b/src/agentscope/app/_middleware/_tool_offload_middleware.py@@ -218,13 +218,6 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-methodif tool is not None and (tool.is_state_injected or tool.is_external_tool):- logger.info(- "Tool '%s' is state-injected or external, executing "- "synchronously: session_id=%s, agent_id=%s",- tool_call.name,- agent.state.session_id,- agent.name,- )async for item in next_handler(**input_kwargs):yield itemreturndiff --git a/src/agentscope/app/_router/_agent.py b/src/agentscope/app/_router/_agent.pyindex 3c3f70cca..b6cac72a5 100644--- a/src/agentscope/app/_router/_agent.py+++ b/src/agentscope/app/_router/_agent.py@@ -4,8 +4,10 @@ from datetime import datetimefrom fastapi import APIRouter, Depends, HTTPException, status+from ...agent import ContextConfig, ReActConfigfrom .._deps import get_current_user_id, get_storagefrom .._schema import (+ AgentSchemaResponse,ListAgentsResponse,CreateAgentRequest,CreateAgentResponse,@@ -20,6 +22,55 @@ agent_router = APIRouter()+@agent_router.get(+ "/schema",+ response_model=AgentSchemaResponse,+ summary="Get JSON Schema fragments for the agent form",+)+async def get_agent_schema() -> AgentSchemaResponse:+ """Return the JSON Schema fragments used by the frontend to render+ the agent create / edit forms.++ The frontend uses three sections — identity, context config, and+ react config — so we return them as separate self-contained schemas+ rather than a single ``AgentData`` schema with ``$ref``s.++ Returns:+ `AgentSchemaResponse`:+ Schemas for the three form sections.+ """+ # Slice ``AgentData``'s schema down to the identity-relevant fields.+ # Going through ``AgentData.model_json_schema()`` (rather than building+ # a dict by hand) keeps Pydantic as the single source of truth for+ # defaults, titles, descriptions, and the ``format: textarea`` hint.+ agent_schema = AgentData.model_json_schema()+ identity_keys = ("name", "system_prompt")+ identity = {+ "type": "object",+ "title": "Identity",+ "properties": {+ k: v+ for k, v in agent_schema.get("properties", {}).items()+ if k in identity_keys+ },+ "required": [+ r for r in agent_schema.get("required", []) if r in identity_keys+ ],+ }++ context_schema = ContextConfig.model_json_schema()+ # ``summary_schema`` holds a Pydantic JSON Schema describing how the+ # compression model should structure its output. The end-user is not+ # expected to edit it from the form, so we hide it.+ context_schema.get("properties", {}).pop("summary_schema", None)++ return AgentSchemaResponse(+ identity=identity,+ context_config=context_schema,+ react_config=ReActConfig.model_json_schema(),+ )++@agent_router.get("/",response_model=ListAgentsResponse,diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex c7722a083..344c00e55 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -13,7 +13,12 @@ from .._schema import (ListSessionsResponse,UpdateSessionRequest,)-from ..storage import StorageBase, SessionConfig, SessionRecord+from ..storage import (+ ChatModelConfig,+ SessionConfig,+ SessionRecord,+ StorageBase,+)session_router = APIRouter(prefix="/sessions",@@ -22,6 +27,34 @@ session_router = APIRouter()+async def _ensure_credential_exists(+ storage: StorageBase,+ user_id: str,+ config: ChatModelConfig | None,+) -> None:+ """Validate that the credential referenced by ``config`` belongs to the+ given user. No-op when ``config`` is ``None``.++ Args:+ storage (`StorageBase`): Injected storage backend.+ user_id (`str`): The authenticated user ID.+ config (`ChatModelConfig | None`): Model config to validate. Pass+ ``None`` to skip the check.++ Raises:+ `HTTPException`: 404 if the credential does not exist or does not+ belong to the user.+ """+ if config is None:+ return+ credentials = await storage.list_credentials(user_id)+ if not any(c.id == config.credential_id for c in credentials):+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Credential '{config.credential_id}' not found.",+ )++@session_router.get("/",response_model=ListSessionsResponse,@@ -94,16 +127,12 @@ async def create_session(detail=f"Agent '{body.agent_id}' not found.",)- if body.chat_model_config is not None:- credentials = await storage.list_credentials(user_id)- if not any(- c.id == body.chat_model_config.credential_id for c in credentials- ):- raise HTTPException(- status_code=status.HTTP_404_NOT_FOUND,- detail=f"Credential '{body.chat_model_config.credential_id}' "- f"not found.",- )+ await _ensure_credential_exists(storage, user_id, body.chat_model_config)+ await _ensure_credential_exists(+ storage,+ user_id,+ body.fallback_chat_model_config,+ )session_record = await storage.upsert_session(user_id=user_id,@@ -111,6 +140,7 @@ async def create_session(config=SessionConfig(workspace_id=body.workspace_id or uuid.uuid4().hex,chat_model_config=body.chat_model_config,+ fallback_chat_model_config=body.fallback_chat_model_config,**({"name": body.name} if body.name is not None else {}),),)@@ -181,18 +211,12 @@ async def update_session(detail=f"Session '{session_id}' not found.",)- if body.chat_model_config is not None:- credentials = await storage.list_credentials(user_id)- if not any(- c.id == body.chat_model_config.credential_id for c in credentials- ):- raise HTTPException(- status_code=status.HTTP_404_NOT_FOUND,- detail=(- f"Credential '{body.chat_model_config.credential_id}' "- f"not found."- ),- )+ await _ensure_credential_exists(storage, user_id, body.chat_model_config)+ await _ensure_credential_exists(+ storage,+ user_id,+ body.fallback_chat_model_config,+ )updated_state = existing.stateif body.permission_mode is not None:@@ -206,17 +230,19 @@ async def update_session(},)+ # PATCH semantics: only fields explicitly present in the request body are+ # applied. ``exclude_unset=True`` lets clients distinguish "leave+ # unchanged" (omit) from "clear" (send ``null``) — required for clearing+ # ``fallback_chat_model_config``.config_updates = body.model_dump(- exclude_none=True,+ exclude_unset=True,exclude={"permission_mode"},)return await storage.upsert_session(user_id=user_id,agent_id=agent_id,- config=existing.config.model_copy(- update=dict(config_updates.items()),- ),+ config=existing.config.model_copy(update=config_updates),state=updated_state,session_id=session_id,)diff --git a/src/agentscope/app/_schema/__init__.py b/src/agentscope/app/_schema/__init__.pyindex bd0893c76..57677d53d 100644--- a/src/agentscope/app/_schema/__init__.py+++ b/src/agentscope/app/_schema/__init__.py@@ -11,6 +11,7 @@ from ._schedule import (UpdateScheduleRequest,)from ._agent import (+ AgentSchemaResponse,ListAgentsResponse,CreateAgentRequest,CreateAgentResponse,@@ -37,6 +38,7 @@ from ._session import (__all__ = [# Agent+ "AgentSchemaResponse","ListAgentsResponse","CreateAgentRequest","CreateAgentResponse",diff --git a/src/agentscope/app/_schema/_agent.py b/src/agentscope/app/_schema/_agent.pyindex cbca7c38d..a252b653d 100644--- a/src/agentscope/app/_schema/_agent.py+++ b/src/agentscope/app/_schema/_agent.py@@ -56,3 +56,27 @@ class ListAgentsResponse(BaseModel):agents: list[AgentRecord] = Field(description="Agent records.")total: int = Field(description="Total number of agents.")+++class AgentSchemaResponse(BaseModel):+ """JSON Schema fragments used by the frontend to render the agent+ create / edit forms.++ Each fragment is a self-contained JSON Schema object so the frontend+ doesn't need to follow ``$ref`` links across fragments. The frontend+ pairs each property with an i18n key derived from its path, so labels+ and descriptions remain localizable independently of the backend.+ """++ identity: dict = Field(+ description=(+ "Schema for the agent's identity fields (``name``, "+ "``system_prompt``)."+ ),+ )+ context_config: dict = Field(+ description="Schema for ``ContextConfig``.",+ )+ react_config: dict = Field(+ description="Schema for ``ReActConfig``.",+ )diff --git a/src/agentscope/app/_schema/_session.py b/src/agentscope/app/_schema/_session.pyindex 2bae8ccb8..ea9aa1a5c 100644--- a/src/agentscope/app/_schema/_session.py+++ b/src/agentscope/app/_schema/_session.py@@ -23,6 +23,11 @@ class CreateSessionRequest(BaseModel):description="Model provider and parameters. ""Can be set later via PATCH.",)+ fallback_chat_model_config: ChatModelConfig | None = Field(+ default=None,+ description="Fallback model used when the primary model fails. "+ "Can be set later via PATCH.",+ )class CreateSessionResponse(BaseModel):@@ -44,7 +49,13 @@ class UpdateSessionRequest(BaseModel):chat_model_config: ChatModelConfig | None = Field(default=None,description="New model configuration. "- "Replaces the existing one entirely.",+ "Replaces the existing one entirely. "+ "Pass null to clear; omit to leave unchanged.",+ )+ fallback_chat_model_config: ChatModelConfig | None = Field(+ default=None,+ description="New fallback model configuration. "+ "Pass null to clear; omit to leave unchanged.",)permission_mode: PermissionMode | None = Field(default=None,diff --git a/src/agentscope/app/_service/_agent.py b/src/agentscope/app/_service/_agent.pyindex 21a26c5c7..8958cd7a8 100644--- a/src/agentscope/app/_service/_agent.py+++ b/src/agentscope/app/_service/_agent.py@@ -6,7 +6,7 @@ from ._model import get_modelfrom .._manager import WorkspaceManagerBasefrom .._types import AgentMiddlewareFactory, AgentToolFactoryfrom ..storage import StorageBase-from ...agent import Agent+from ...agent import Agent, ModelConfigfrom ...middleware import MiddlewareBasefrom ...tool import Toolkit@@ -89,6 +89,18 @@ async def get_agent(model = await get_model(user_id, model_cfg, storage)+ # ====================================================================+ # Step 2.1.1. Build the optional fallback model+ # ====================================================================+ # The fallback model is invoked by the agent when the primary model+ # fails. ``None`` means no fallback is configured for this session.+ fallback_cfg = session_record.config.fallback_chat_model_config+ fallback_model = (+ await get_model(user_id, fallback_cfg, storage)+ if fallback_cfg is not None+ else None+ )+# ====================================================================# Step 2.2. Get the session data, i.e. the agent state# ====================================================================@@ -131,6 +143,7 @@ async def get_agent(skills_or_loaders=await workspace.list_skills(),mcps=await workspace.list_mcps(),),+ model_config=ModelConfig(fallback_model=fallback_model),context_config=cfg.context_config,react_config=cfg.react_config,state=agent_state,diff --git a/src/agentscope/app/storage/_model/_agent.py b/src/agentscope/app/storage/_model/_agent.pyindex 2a20c24eb..2a2b1cb5c 100644--- a/src/agentscope/app/storage/_model/_agent.py+++ b/src/agentscope/app/storage/_model/_agent.py@@ -23,8 +23,12 @@ class AgentData(BaseModel):)system_prompt: str = Field(+ default="You're a helpful assistant.",description="The system prompt for the agent.",title="System Prompt",+ # Hint for schema-driven UI renderers; see ``ContextConfig`` for+ # the same pattern on long-form prompts.+ json_schema_extra={"format": "textarea"},)context_config: ContextConfig = Field(diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.pyindex cc1d47739..6881bcd50 100644--- a/src/agentscope/app/storage/_model/_session.py+++ b/src/agentscope/app/storage/_model/_session.py@@ -47,6 +47,10 @@ class SessionConfig(BaseModel):chat_model_config: ChatModelConfig | None = None"""The chat model config. None means no model has been configured yet."""+ fallback_chat_model_config: ChatModelConfig | None = None+ """The fallback chat model config. Used as a backup when the primary+ model fails. None means no fallback configured."""+class SessionRecord(_RecordBase):"""The session record."""diff --git a/src/agentscope/model/_base.py b/src/agentscope/model/_base.pyindex 8a8bd59f8..6e87e46a0 100644--- a/src/agentscope/model/_base.py+++ b/src/agentscope/model/_base.py@@ -1,5 +1,6 @@# -*- coding: utf-8 -*-"""The base class for the chat models."""+import asyncioimport inspectimport jsonfrom abc import abstractmethod@@ -177,6 +178,8 @@ class ChatModelBase:self.model,str(e),)+ # Sleep before retry+ await asyncio.sleep(0.1)else:logger.warning("All %d attempt(s) failed for model %s.",