Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(web_ui): chat polish, session auto-naming, and a query cache (#2503)
DavdGao5ceeaa29fc1c
diff --git a/examples/web_ui/frontend/package.json b/examples/web_ui/frontend/package.jsonindex 191252c55..d766e5e85 100644--- a/examples/web_ui/frontend/package.json+++ b/examples/web_ui/frontend/package.json@@ -20,6 +20,7 @@"@streamdown/math": "^1.0.2","@streamdown/mermaid": "^1.0.2","@tailwindcss/vite": "^4.3.0",+ "@tanstack/react-query": "^5.102.8","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cron-parser": "^5.5.0",diff --git a/examples/web_ui/frontend/src/App.tsx b/examples/web_ui/frontend/src/App.tsxindex 497bc4db4..c1050096a 100644--- a/examples/web_ui/frontend/src/App.tsx+++ b/examples/web_ui/frontend/src/App.tsx@@ -1,3 +1,4 @@+import { QueryClientProvider } from '@tanstack/react-query';import { Onborda, OnbordaProvider } from 'onborda';import { useMemo, useState } from 'react';import { createBrowserRouter, Navigate, RouterProvider, useNavigate } from 'react-router-dom';@@ -11,6 +12,7 @@ import { buildChatTour } from '@/components/tour/chatTourSteps';import { TourCard } from '@/components/tour/TourCard';import { UploadProvider } from '@/context/UploadContext';import { useTranslation } from '@/i18n/useI18n';+import { queryClient } from '@/lib/query-client';import { ChannelPage } from '@/pages/channel';import { ChatPage } from '@/pages/chat';import { CredentialPage } from '@/pages/credential';@@ -73,19 +75,21 @@ function App() {}return (- <OnbordaProvider>- <Onborda- steps={tours}- cardComponent={TourCard}- shadowOpacity="0.6"- cardTransition={{ type: 'spring', duration: 0.4 }}- >- <UploadProvider>- <RouterProvider router={router} />- </UploadProvider>- <Toaster richColors position="top-right" />- </Onborda>- </OnbordaProvider>+ <QueryClientProvider client={queryClient}>+ <OnbordaProvider>+ <Onborda+ steps={tours}+ cardComponent={TourCard}+ shadowOpacity="0.6"+ cardTransition={{ type: 'spring', duration: 0.4 }}+ >+ <UploadProvider>+ <RouterProvider router={router} />+ </UploadProvider>+ <Toaster richColors position="top-right" />+ </Onborda>+ </OnbordaProvider>+ </QueryClientProvider>);}diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.tsindex b9ed157ea..83b4a5f6b 100644--- a/examples/web_ui/frontend/src/api/types.ts+++ b/examples/web_ui/frontend/src/api/types.ts@@ -115,6 +115,8 @@ export type SessionSource = 'user' | 'schedule' | 'channel';export interface SessionConfig {name: string;+ /** Who owns `name` — see the backend's `SessionNaming`. */+ naming: { auto: boolean };chat_model_config: ChatModelConfig;/** Fallback model used when the primary model fails. */fallback_chat_model_config: ChatModelConfig | null;diff --git a/examples/web_ui/frontend/src/components/chat/ASMessageBubble.tsx b/examples/web_ui/frontend/src/components/chat/ASMessageBubble.tsxindex 3c8c43621..f78044460 100644--- a/examples/web_ui/frontend/src/components/chat/ASMessageBubble.tsx+++ b/examples/web_ui/frontend/src/components/chat/ASMessageBubble.tsx@@ -11,16 +11,18 @@ import type {import {ArrowDown,ArrowUp,+ Check,CheckCircle,ChevronRight,CirclePlay,+ Copy,FileText,FileVideo2,Loader2,TriangleAlert,} from 'lucide-react';import * as mime from 'mime-types';-import { useEffect, useRef, useState } from 'react';+import { memo, useEffect, useRef, useState } from 'react';import { renderToolCall } from './tool-renderers';import { countDiffStats, DiffStats, getResultDiff } from './tool-renderers/_shared';@@ -37,6 +39,7 @@ import {} from '@/components/ui/attachment.tsx';import { Badge } from '@/components/ui/badge';import { Bubble, BubbleContent } from '@/components/ui/bubble.tsx';+import { Button } from '@/components/ui/button';import {Collapsible,CollapsibleContent,@@ -46,7 +49,7 @@ import { Message, MessageFooter, MessageContent } from '@/components/ui/message'import { useAudioBlock, useReplayController } from '@/context/AudioContext';import { useTranslation } from '@/i18n/useI18n';import { cn } from '@/lib/utils';-import { formatNumber, formatTime } from '@/utils/common';+import { copyToClipboard, formatNumber, formatTime } from '@/utils/common';import 'streamdown/styles.css';/**@@ -290,6 +293,35 @@ function AudioInlineControl({ block }: { block: DataBlock }) {);}+/**+ * Copies the message's text to the clipboard, flipping to a check mark+ * for a moment so the click has visible feedback. Hidden until the+ * message is hovered on pointer devices; always visible on touch.+ */+function CopyButton({ text }: { text: string }) {+ const { t } = useTranslation();+ const [copied, setCopied] = useState(false);++ const handleCopy = async () => {+ if (!(await copyToClipboard(text))) return;+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ };++ return (+ <Button+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground md:opacity-0 group-hover/message:opacity-100 focus-visible:opacity-100"+ tooltip={t('messageBubble.copy')}+ aria-label={t('messageBubble.copy')}+ onClick={handleCopy}+ >+ {copied ? <Check /> : <Copy />}+ </Button>+ );+}+const MCP_TOOL_PREFIX = 'mcp__';// Task-management tools are all surfaced under one "updated todos" summary.@@ -383,7 +415,7 @@ interface MessageBubbleProps {* 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 ASMessageBubble({ message }: MessageBubbleProps) {+function ASMessageBubbleComponent({ message }: MessageBubbleProps) {const isUser = message.role === 'user';const { t } = useTranslation();@@ -410,6 +442,13 @@ export function ASMessageBubble({ message }: MessageBubbleProps) {const blocks = groupToolCalls(message.content);+ // What the copy button hands over — the prose of the message, without+ // the tool calls and attachments around it.+ const plainText = message.content+ .filter((b): b is TextBlock => b.type === 'text')+ .map((b) => b.text)+ .join('\n\n');+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);@@ -449,8 +488,14 @@ export function ASMessageBubble({ message }: MessageBubbleProps) {<ASBlock block={block} key={index} />))}</AttachmentGroup>- {message.role !== 'user' && (- <MessageFooter className="font-mono">+ {message.role === 'user' ? (+ plainText && (+ <MessageFooter>+ <CopyButton text={plainText} />+ </MessageFooter>+ )+ ) : (+ <MessageFooter className="gap-1 font-mono"><Badgevariant="secondary"aria-label={isRunning ? t('messageBubble.running') : undefined}@@ -477,6 +522,7 @@ export function ASMessageBubble({ message }: MessageBubbleProps) {<AudioInlineControl key={block.id} block={block} />))}</Badge>+ {plainText && <CopyButton text={plainText} />}</MessageFooter>)}</MessageContent>@@ -484,6 +530,15 @@ export function ASMessageBubble({ message }: MessageBubbleProps) {);}+/**+ * Memoised: a streaming reply publishes a new `Msg` object on every delta+ * (see ``useMessages``) while the messages around it keep their identity,+ * so only the bubble that actually changed re-renders. A message mutated+ * in place would therefore *not* repaint — new content has to arrive as a+ * new object.+ */+export const ASMessageBubble = memo(ASMessageBubbleComponent);+/*** A thinking block with a live-ticking "thinking for Xs" header. Kept as its* own component so only thinking blocks pay for the per-second timer.@@ -623,10 +678,19 @@ export function ASBlock({ block, ...props }: ASBlockProps) {label?: string;sublabel?: string;};+ // Both halves go through the same i18n table, falling+ // back to the raw text for sources it doesn't cover.hintLabel = parsed.label- ? t(`messageBubble.hintSource.${parsed.label.toLowerCase()}`)+ ? t(`messageBubble.hintSource.${parsed.label.toLowerCase()}`, {+ defaultValue: parsed.label,+ }): block.source;- hintSublabel = parsed.sublabel ?? null;+ hintSublabel = parsed.sublabel+ ? t(+ `messageBubble.hintSource.${parsed.sublabel.toLowerCase().replace(/\s+/g, '_')}`,+ { defaultValue: parsed.sublabel },+ )+ : null;} catch {hintLabel = block.source;}diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsxindex 3aeedf083..4c0cb3859 100644--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx@@ -18,6 +18,7 @@ import { FlipCard } from '@/components/chat/FlipCard.tsx';import { TextInput } from '@/components/chat/TextInput.tsx';import { WorkingDirectoryDialog } from '@/components/dialog/WorkingDirectoryDialog';import { Alert, AlertAction, AlertDescription, AlertTitle } from '@/components/ui/alert.tsx';+import { Marker, MarkerContent } from '@/components/ui/marker';import {MessageScroller,MessageScrollerButton,@@ -34,6 +35,30 @@ import { cn } from '@/lib/utils';/** How long a load may run before it is worth showing a spinner. */const SPINNER_DELAY_MS = 150;+/**+ * A gap this long between two messages gets a marker stamping when the+ * conversation resumed — long enough that it *was* resumed, rather than+ * merely paused to read the last reply.+ */+const TIME_MARKER_GAP_MS = 10 * 60 * 1000;++/**+ * Stamp for a resumed conversation. The time alone is enough while the+ * marker and the message above it share a day; once the gap crosses+ * midnight the date has to come with it. Both come from `Intl`, so+ * "Aug 13, 13:03" and "8月13日 13:03" fall out of the active language+ * rather than out of a hand-written pattern per locale.+ */+function markerStamp(at: Date, previous: Date, language: string): string {+ const sameDay = at.toDateString() === previous.toDateString();+ return new Intl.DateTimeFormat(language, {+ ...(sameDay ? {} : { month: 'short', day: 'numeric' }),+ hour: '2-digit',+ minute: '2-digit',+ hour12: false,+ }).format(at);+}+interface ChatContentProps {msgs: Msg[];/**@@ -106,7 +131,7 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({git,onRefreshGit,}) => {- const { t } = useTranslation();+ const { t, i18n } = useTranslation();// Only a session that finished loading with nothing in it is empty.// Treating "no messages yet" as empty would flash the greeting over// every session that does have history.@@ -158,15 +183,35 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({<MessageScroller><MessageScrollerViewport><MessageScrollerContent>- {msgs.map((message) => (- <MessageScrollerItem key={message.id} messageId={message.id}>- <ASMessageBubble+ {msgs.map((message, index) => {+ const previous = msgs[index - 1];+ const at = new Date(message.created_at);+ const previousAt = previous+ ? new Date(previous.finished_at ?? previous.created_at)+ : at;+ return (+ <MessageScrollerItemkey={message.id}- message={message}- onUserConfirm={onUserConfirm}- />- </MessageScrollerItem>- ))}+ messageId={message.id}+ >+ {at.getTime() - previousAt.getTime() >+ TIME_MARKER_GAP_MS && (+ <Marker+ variant="separator"+ className="mb-6 font-mono text-xs"+ >+ <MarkerContent>+ {markerStamp(at, previousAt, i18n.language)}+ </MarkerContent>+ </Marker>+ )}+ <ASMessageBubble+ message={message}+ onUserConfirm={onUserConfirm}+ />+ </MessageScrollerItem>+ );+ })}{msgs.length > 0 &&msgs[msgs.length - 1].finished_reason ===ReplyFinishedReason.EXCEED_MAX_ITERS &&diff --git a/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx b/examples/web_ui/frontend/src/components/form/AgentFormFields.tsxindex 1099c6759..030a8e339 100644--- a/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx+++ b/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx@@ -120,6 +120,15 @@ export function AgentFormFields({ schema, values, onChange }: Props) {defaultValue: prop.description ?? '',}) || undefined}+ // Only for fields whose label cannot carry the+ // whole story on its own — hence no fallback to+ // `prop.description`, which is English-only and+ // already serves as the placeholder.+ descriptionFor={(k) =>+ t(`agent-form.${sectionI18n}.${toKebab(k)}.description`, {+ defaultValue: '',+ }) || undefined+ }/></FieldSet></div>diff --git a/examples/web_ui/frontend/src/components/form/SchemaForm.tsx b/examples/web_ui/frontend/src/components/form/SchemaForm.tsxindex b64d1ffef..c51942394 100644--- a/examples/web_ui/frontend/src/components/form/SchemaForm.tsx+++ b/examples/web_ui/frontend/src/components/form/SchemaForm.tsx@@ -141,6 +141,11 @@ export function SchemaForm({);if (isBoolean) {+ const boxLabel = (+ <FieldLabel htmlFor={fieldId} className="font-normal">+ {label}+ </FieldLabel>+ );return (<Field key={key} orientation="horizontal"><Checkbox@@ -148,10 +153,18 @@ export function SchemaForm({checked={!!current}onCheckedChange={(checked) => onChange(key, !!checked)}/>- <FieldLabel htmlFor={fieldId} className="font-normal">- {label}- </FieldLabel>- {description && <FieldDescription>{description}</FieldDescription>}+ {/* A described checkbox stacks its label and helper+ text in a column beside the box; without one the+ label stays inline, so a plain toggle keeps the+ single centred row it has always had. */}+ {descriptionNode ? (+ <FieldContent>+ {boxLabel}+ {descriptionNode}+ </FieldContent>+ ) : (+ boxLabel+ )}</Field>);}diff --git a/examples/web_ui/frontend/src/components/ui/message-scroller.tsx b/examples/web_ui/frontend/src/components/ui/message-scroller.tsxindex ff924e330..1af58a2d6 100644--- a/examples/web_ui/frontend/src/components/ui/message-scroller.tsx+++ b/examples/web_ui/frontend/src/components/ui/message-scroller.tsx@@ -40,7 +40,10 @@ function MessageScrollerViewport({<MessageScrollerPrimitive.Viewportdata-slot="message-scroller-viewport"className={cn(- 'size-full min-h-0 min-w-0 scroll-fade-b scrollbar-thin scrollbar-gutter-stable overflow-y-auto overscroll-contain contain-content data-autoscrolling:scrollbar-thumb-transparent data-autoscrolling:scrollbar-track-transparent',+ // `no-scrollbar`: the stock thin scrollbar is hidden while+ // autoscrolling and shown otherwise, so a streaming reply+ // blinks it on and off down the right edge.+ 'size-full min-h-0 min-w-0 scroll-fade-b no-scrollbar overflow-y-auto overscroll-contain contain-content',className,)}{...props}diff --git a/examples/web_ui/frontend/src/hooks/useAgentSchema.ts b/examples/web_ui/frontend/src/hooks/useAgentSchema.tsindex 4a20bb9df..62b8c8404 100644--- a/examples/web_ui/frontend/src/hooks/useAgentSchema.ts+++ b/examples/web_ui/frontend/src/hooks/useAgentSchema.ts@@ -1,38 +1,20 @@-import { useEffect, useState } from 'react';+import { useQuery } from '@tanstack/react-query';import { agentApi } from '@/api';-import type { AgentSchemaV2Response } 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.+ * The full `AgentData` JSON Schema backing the agent form.+ *+ * Derived from Pydantic models on the backend, so it cannot change while+ * the server is up: fetched once and served from cache for every create /+ * edit dialog afterwards.*/-let cached: AgentSchemaV2Response | null = null;-let inflight: Promise<AgentSchemaV2Response> | null = null;--async function loadSchema(): Promise<AgentSchemaV2Response> {- if (cached) return cached;- if (!inflight) {- inflight = agentApi.getSchema().then((res) => {- cached = res;- return res;- });- }- return inflight;-}--/** Fetch (and cache) the full `AgentData` JSON Schema for the agent form. */export function useAgentSchema() {- const [schema, setSchema] = useState<AgentSchemaV2Response | null>(cached);- const [error, setError] = useState<Error | null>(null);-- useEffect(() => {- if (cached) return;- loadSchema()- .then(setSchema)- .catch((e: Error) => setError(e));- }, []);+ const { data, isPending, error } = useQuery({+ queryKey: ['agent-schema'],+ queryFn: () => agentApi.getSchema(),+ staleTime: Infinity,+ });- return { schema, loading: schema === null && error === null, error };+ return { schema: data ?? null, loading: isPending, error: error as Error | null };}diff --git a/examples/web_ui/frontend/src/hooks/useAvailableModels.ts b/examples/web_ui/frontend/src/hooks/useAvailableModels.tsindex cae10a095..e649a63d7 100644--- a/examples/web_ui/frontend/src/hooks/useAvailableModels.ts+++ b/examples/web_ui/frontend/src/hooks/useAvailableModels.ts@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback } from 'react';+import { useQuery } from '@tanstack/react-query';import { credentialApi, modelApi } from '@/api';import type { CredentialView, ModelCard } from '@/api';@@ -12,44 +12,57 @@ export interface CredentialWithModels {* Fetches all credentials and their available models, grouped by provider type.* Provider type is read from `credential.data.type`.* Credentials without a `type` field or whose model fetch fails are silently skipped.+ *+ * One credential list plus one model list per provider — the most expensive+ * fan-out on the page, and every model picker in the app mounts it. Cached+ * under the shared default window and re-fetched on demand through+ * `refetch`, which is what the "credential just added" trigger calls.*/+async function fetchGroups(): Promise<Record<string, CredentialWithModels[]>> {+ const { credentials } = await credentialApi.list();+ const result: Record<string, CredentialWithModels[]> = {};++ await Promise.all(+ credentials.map(async (credential) => {+ const type = credential.data.type as string | undefined;+ if (!type) return;+ if (!result[type]) result[type] = [];+ try {+ const { models } = await modelApi.list(type);+ // Reverse-alphabetical, which is how the providers' naming+ // schemes rank themselves — gpt-5 before gpt-4, qwen3 before+ // qwen2 — so the strongest models sit at the top of the picker.+ result[type].push({+ credential,+ models: [...models].sort((a, b) =>+ b.name.localeCompare(a.name, undefined, { numeric: true }),+ ),+ });+ } catch {+ result[type].push({ credential, models: [] });+ }+ }),+ );++ return result;+}++/**+ * Cache key for the grouped model list. Exported so a credential change —+ * which moves what these groups contain — can invalidate it.+ */+export const AVAILABLE_MODELS_KEY = ['available-models'];+export function useAvailableModels() {- const [groups, setGroups] = useState<Record<string, CredentialWithModels[]>>({});- const [loading, setLoading] = useState(false);- const [error, setError] = useState<Error | null>(null);-- const refetch = useCallback(async () => {- setLoading(true);- setError(null);- try {- const { credentials } = await credentialApi.list();- const result: Record<string, CredentialWithModels[]> = {};-- await Promise.all(- credentials.map(async (credential) => {- const type = credential.data.type as string | undefined;- if (!type) return;- if (!result[type]) result[type] = [];- try {- const { models } = await modelApi.list(type);- result[type].push({ credential, models });- } catch {- result[type].push({ credential, models: [] });- }- }),- );-- setGroups(result);- } catch (e) {- setError(e as Error);- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- refetch();- }, [refetch]);-- return { groups, loading, error, refetch };+ const { data, isPending, error, refetch } = useQuery({+ queryKey: AVAILABLE_MODELS_KEY,+ queryFn: fetchGroups,+ });++ return {+ groups: data ?? {},+ loading: isPending,+ error: error as Error | null,+ refetch: () => void refetch(),+ };}diff --git a/examples/web_ui/frontend/src/hooks/useCredentials.ts b/examples/web_ui/frontend/src/hooks/useCredentials.tsindex 29d1511a9..c015d4768 100644--- a/examples/web_ui/frontend/src/hooks/useCredentials.ts+++ b/examples/web_ui/frontend/src/hooks/useCredentials.ts@@ -1,7 +1,9 @@+import { useQueryClient } from '@tanstack/react-query';import { useState, useEffect, useCallback } from 'react';import { credentialApi } from '../api';import type { CredentialView, CreateCredentialRequest, UpdateCredentialRequest } from '../api';+import { AVAILABLE_MODELS_KEY } from './useAvailableModels';/*** Manages API key credentials with CRUD operations.@@ -11,6 +13,7 @@ export function useCredentials() {const [credentials, setCredentials] = useState<CredentialView[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<Error | null>(null);+ const queryClient = useQueryClient();const refetch = useCallback(async () => {setLoading(true);@@ -29,33 +32,42 @@ export function useCredentials() {refetch();}, [refetch]);+ // Every model picker reads its options from the cached+ // `available-models` query, which is derived from the credentials —+ // so a credential that just changed has to drop that cache too,+ // rather than leaving the pickers to time out of it.+ const refresh = useCallback(async () => {+ await refetch();+ await queryClient.invalidateQueries({ queryKey: AVAILABLE_MODELS_KEY });+ }, [refetch, queryClient]);+/** Stores a new credential and refreshes the list. */const create = useCallback(async (body: CreateCredentialRequest) => {const res = await credentialApi.create(body);- await refetch();+ await refresh();return res;},- [refetch],+ [refresh],);/** Replaces a credential's payload and refreshes the list. */const update = useCallback(async (credentialId: string, body: UpdateCredentialRequest) => {const res = await credentialApi.update(credentialId, body);- await refetch();+ await refresh();return res;},- [refetch],+ [refresh],);/** Permanently deletes a credential and refreshes the list. */const remove = useCallback(async (credentialId: string) => {await credentialApi.delete(credentialId);- await refetch();+ await refresh();},- [refetch],+ [refresh],);return { credentials, loading, error, refetch, create, update, remove };diff --git a/examples/web_ui/frontend/src/hooks/useMCPHubs.ts b/examples/web_ui/frontend/src/hooks/useMCPHubs.tsindex 1a622453b..734f59bd1 100644--- a/examples/web_ui/frontend/src/hooks/useMCPHubs.ts+++ b/examples/web_ui/frontend/src/hooks/useMCPHubs.ts@@ -1,37 +1,27 @@-import { useCallback, useEffect, useState } from 'react';+import { useQuery } from '@tanstack/react-query';import { hubApi } from '@/api';-import type { HubInfo } from '@/api';/*** The MCP hubs registered on the server.*- * The list is fixed at deploy time (`create_app(mcp_hubs=[...])`), so it is- * fetched once and never mutated from the UI. An empty list is the normal- * state for a deployment that configured no hubs — not an error.+ * The list is fixed at deploy time (`create_app(mcp_hubs=[...])`), so it can+ * never go stale while the server is up — hence `staleTime: Infinity`, which+ * turns every visit to the MCP page after the first into a cache read. An+ * empty list is the normal state for a deployment that configured no hubs —+ * not an error.*/export function useMCPHubs() {- const [hubs, setHubs] = useState<HubInfo[]>([]);- // Starts true: the first paint happens before the effect fires, and- // a false start would flash the empty state before the spinner.- const [loading, setLoading] = useState(true);- const [error, setError] = useState<Error | null>(null);+ const { data, isPending, error, refetch } = useQuery({+ queryKey: ['mcp-hubs'],+ queryFn: () => hubApi.mcp.listHubs(),+ staleTime: Infinity,+ });- const refetch = useCallback(async () => {- setLoading(true);- setError(null);- try {- setHubs(await hubApi.mcp.listHubs());- } catch (e) {- setError(e as Error);- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- refetch();- }, [refetch]);-- return { hubs, loading, error, refetch };+ return {+ hubs: data ?? [],+ loading: isPending,+ error: error as Error | null,+ refetch: () => void refetch(),+ };}diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.tsindex 4b7eb9c1f..3d93538be 100644--- a/examples/web_ui/frontend/src/hooks/useMessages.ts+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts@@ -124,6 +124,13 @@ export function useMessages(* ``tasks_context`` and ``permission_context``.*/onStateUpdated?: (value: Record<string, unknown>) => void;+ /**+ * Called when a ``CUSTOM`` event with ``name="session_updated"``+ * arrives — the session record changed server-side, currently+ * only when auto-naming replaced its placeholder name. Refetch+ * the session list to pick the new one up.+ */+ onSessionUpdated?: () => void;},) {const [msgs, setMsgs] = useState<Msg[]>([]);@@ -178,6 +185,8 @@ export function useMessages(optionsRef.current?.onTeamUpdated?.();} else if (custom.name === 'state_updated' && custom.value) {optionsRef.current?.onStateUpdated?.(custom.value as Record<string, unknown>);+ } else if (custom.name === 'session_updated') {+ optionsRef.current?.onSessionUpdated?.();} else if (custom.name === 'subagent_require_user_confirm') {// A team member is asking for confirmation; show (or// refresh) its card on this leader view. Dedup by@@ -215,15 +224,27 @@ export function useMessages(}clearInterruptTimer();setPhase('streaming');- } else if (event.type === EventType.REPLY_END) {+ } else {if (currentReplyRef.current) {- appendEvent(currentReplyRef.current, event);+ const reply = currentReplyRef.current;+ appendEvent(reply, event);+ // ``appendEvent`` mutates in place, which would leave+ // every Msg identical across renders and force the whole+ // list to re-render on each delta. Republish just the+ // reply that changed under a fresh identity, so the+ // memoised bubbles of the other messages can skip the+ // render. Anything holding a Msg reference across events+ // must re-read it from here — ``currentReplyRef`` below,+ // everything else looks the reply up by id.+ const updated = { ...reply, content: [...reply.content] };+ msgsRef.current = msgsRef.current.map((m) => (m === reply ? updated : m));+ currentReplyRef.current = updated;+ }+ if (event.type === EventType.REPLY_END) {+ clearInterruptTimer();+ setPhase('idle');+ currentReplyRef.current = null;}- clearInterruptTimer();- setPhase('idle');- currentReplyRef.current = null;- } else if (currentReplyRef.current) {- appendEvent(currentReplyRef.current, event);}// Route streaming audio DataBlocks to the audio manager. They stilldiff --git a/examples/web_ui/frontend/src/hooks/useSessions.ts b/examples/web_ui/frontend/src/hooks/useSessions.tsindex ea5aee95d..38c253aa7 100644--- a/examples/web_ui/frontend/src/hooks/useSessions.ts+++ b/examples/web_ui/frontend/src/hooks/useSessions.ts@@ -1,33 +1,58 @@-import { useState, useEffect, useCallback, useRef } from 'react';+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useCallback } from 'react';import { sessionApi } from '../api';import type { SessionView, CreateSessionRequest, UpdateSessionRequest } from '../api';+/** Stable empty list, so `sessions` keeps its identity between renders. */+const NO_SESSIONS: SessionView[] = [];++/** Every agent's session list, so one mutation refreshes all of them. */+const SESSIONS_KEY = ['sessions'];+/*** Manages session views for a given agent.** Each entry is a `SessionView` (record + is_running + optional team- * detail) — the same shape the backend returns. The hook clears and- * re-fetches whenever agentId changes.+ * detail) — the same shape the backend returns.+ *+ * Backed by the shared query cache, keyed on `agentId`. The chat page+ * mounts this hook twice — once for the outer sidebar's list, once+ * inside the viewport — and both now read the same entry, so a rename+ * from the sidebar reaches the viewport's header without either side+ * knowing about the other. Drilling into a team member gives the+ * viewport a different `agentId`, hence its own entry, which is what+ * that view wants.** @param agentId - The agent whose sessions to load. Pass null to skip fetching.* @returns Object with the loaded `sessions` array plus `loading` /* `error` flags and `refetch` / `create` / `update` / `remove`- * helpers that all keep the local list in sync.+ * helpers that all keep the list in sync.*/export function useSessions(agentId: string | null) {- const [state, setState] = useState<{- agentId: string | null;- sessions: SessionView[];- loading: boolean;- error: Error | null;- }>({ agentId: null, sessions: [], loading: false, error: null });- const currentAgentIdRef = useRef(agentId);- const requestIdRef = useRef(0);- const ownsState = state.agentId === agentId;- const sessions = ownsState ? state.sessions : [];- const loading = agentId !== null && (!ownsState || state.loading);- const error = ownsState ? state.error : null;+ const queryClient = useQueryClient();++ const {+ data,+ isPending,+ error,+ refetch: runRefetch,+ } = useQuery({+ queryKey: [...SESSIONS_KEY, agentId],+ queryFn: () => sessionApi.list(agentId as string).then((res) => res.sessions),+ enabled: agentId !== null,+ // This list carries `is_running` and team membership, both of+ // which move underneath the page. Sharing one copy between the+ // two mounts is the point here, not skipping the read — so a+ // view that needs it still re-reads it when it mounts.+ staleTime: 0,+ });++ /** Drop every agent's list, so both mounts re-read after a write. */+ const invalidate = useCallback(+ () => queryClient.invalidateQueries({ queryKey: SESSIONS_KEY }),+ [queryClient],+ );/*** Reload the session list.@@ -40,59 +65,18 @@ export function useSessions(agentId: string | null) {* agent or the request failed.*/const refetch = useCallback(async (): Promise<SessionView[]> => {- const requestedAgentId = agentId;- if (currentAgentIdRef.current !== requestedAgentId) return [];-- const requestId = ++requestIdRef.current;- const isCurrent = () =>- requestId === requestIdRef.current && requestedAgentId === currentAgentIdRef.current;-- if (!requestedAgentId) {- setState({ agentId: null, sessions: [], loading: false, error: null });- return [];- }- setState((prev) => ({- agentId: requestedAgentId,- sessions: prev.agentId === requestedAgentId ? prev.sessions : [],- loading: true,- error: null,- }));- try {- const res = await sessionApi.list(requestedAgentId);- if (!isCurrent()) return [];- setState({- agentId: requestedAgentId,- sessions: res.sessions,- loading: false,- error: null,- });- return res.sessions;- } catch (e) {- if (isCurrent()) {- setState((prev) => ({- agentId: requestedAgentId,- sessions: prev.agentId === requestedAgentId ? prev.sessions : [],- loading: false,- error: e as Error,- }));- }- return [];- }- }, [agentId]);-- useEffect(() => {- currentAgentIdRef.current = agentId;- refetch();- }, [agentId, refetch]);+ const result = await runRefetch();+ return result.data ?? NO_SESSIONS;+ }, [runRefetch]);/** Creates a new session and refreshes the list. */const create = useCallback(async (body: CreateSessionRequest) => {const res = await sessionApi.create(body);- await refetch();+ await invalidate();return res;},- [refetch],+ [invalidate],);/** Updates a session's model config and refreshes the list. */@@ -100,10 +84,10 @@ export function useSessions(agentId: string | null) {async (sessionId: string, body: UpdateSessionRequest) => {if (!agentId) throw new Error('No agent selected');const res = await sessionApi.update(sessionId, agentId, body);- await refetch();+ await invalidate();return res;},- [agentId, refetch],+ [agentId, invalidate],);/** Deletes a session and refreshes the list. */@@ -111,10 +95,18 @@ export function useSessions(agentId: string | null) {async (sessionId: string) => {if (!agentId) throw new Error('No agent selected');await sessionApi.delete(sessionId, agentId);- await refetch();+ await invalidate();},- [agentId, refetch],+ [agentId, invalidate],);- return { sessions, loading, error, refetch, create, update, remove };+ return {+ sessions: data ?? NO_SESSIONS,+ loading: agentId !== null && isPending,+ error: error as Error | null,+ refetch,+ create,+ update,+ remove,+ };}diff --git a/examples/web_ui/frontend/src/hooks/useSkillHubs.ts b/examples/web_ui/frontend/src/hooks/useSkillHubs.tsindex 2bb6c9e09..2098aa4f3 100644--- a/examples/web_ui/frontend/src/hooks/useSkillHubs.ts+++ b/examples/web_ui/frontend/src/hooks/useSkillHubs.ts@@ -1,37 +1,25 @@-import { useCallback, useEffect, useState } from 'react';+import { useQuery } from '@tanstack/react-query';import { hubApi } from '@/api';-import type { HubInfo } from '@/api';/*** The skill hubs registered on the server.*- * The list is fixed at deploy time (`create_app(skill_hubs=[...])`), so it is- * fetched once and never mutated from the UI. An empty list is the normal- * state for a deployment that configured no hubs — not an error.+ * Fixed at deploy time (`create_app(skill_hubs=[...])`) and cached for the+ * life of the tab, exactly like {@link useMCPHubs}. An empty list is the+ * normal state for a deployment that configured no hubs — not an error.*/export function useSkillHubs() {- const [hubs, setHubs] = useState<HubInfo[]>([]);- // Starts true: the first paint happens before the effect fires, and- // a false start would flash the empty state before the spinner.- const [loading, setLoading] = useState(true);- const [error, setError] = useState<Error | null>(null);+ const { data, isPending, error, refetch } = useQuery({+ queryKey: ['skill-hubs'],+ queryFn: () => hubApi.skill.listHubs(),+ staleTime: Infinity,+ });- const refetch = useCallback(async () => {- setLoading(true);- setError(null);- try {- setHubs(await hubApi.skill.listHubs());- } catch (e) {- setError(e as Error);- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- refetch();- }, [refetch]);-- return { hubs, loading, error, refetch };+ return {+ hubs: data ?? [],+ loading: isPending,+ error: error as Error | null,+ refetch: () => void refetch(),+ };}diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex 7d574dc57..a887957df 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -119,7 +119,8 @@"team_message": "Team","schedule": "Schedule","system": "System",- "channel": "Channel"+ "channel": "Channel",+ "runtime_state": "Runtime State"},"error": {"title": "Reply failed",@@ -132,7 +133,8 @@"internal": "An unexpected internal error occurred.","setup": "The session could not be prepared — check the agent's model, tools and knowledge bases.","unknown": "The reply failed with an unknown error."- }+ },+ "copy": "Copy"},"chat": {"inputPlaceholder": "Type a message...",@@ -194,6 +196,9 @@},"summary-template": {"label": "Summary template"+ },+ "max-image-num": {+ "label": "Max images"}},"react-config": {@@ -204,6 +209,18 @@},"stop-on-reject": {"label": "Stop on reject"+ },+ "structured-output-grace-iters": {+ "label": "Structured output grace",+ "description": "Extra iterations allowed past the maximum, so a run that hits the limit can still produce the structured output it was asked for."+ },+ "interruption-message": {+ "label": "Interruption reply",+ "description": "Sent as the agent’s reply when the user interrupts a run."+ },+ "interruption-raise-cancelled-error": {+ "label": "Raise CancelledError",+ "description": "Re-raise asyncio.CancelledError once an interruption has been handled, instead of swallowing it."}},"invite-config": {diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex 8d4e4f33a..6249ac4a4 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -119,7 +119,8 @@"team_message": "团队消息","schedule": "定时任务","system": "系统消息",- "channel": "频道"+ "channel": "频道",+ "runtime_state": "运行状态"},"error": {"title": "回复失败",@@ -132,7 +133,8 @@"internal": "发生了未预期的内部错误。","setup": "会话准备失败 —— 请检查该智能体的模型、工具和知识库配置。","unknown": "回复因未知错误失败。"- }+ },+ "copy": "复制"},"chat": {"inputPlaceholder": "输入消息...",@@ -194,6 +196,9 @@},"summary-template": {"label": "摘要模板"+ },+ "max-image-num": {+ "label": "最大图片数"}},"react-config": {@@ -204,6 +209,18 @@},"stop-on-reject": {"label": "拒绝时停止"+ },+ "structured-output-grace-iters": {+ "label": "结构化输出宽限轮数",+ "description": "超过最大迭代次数后额外允许的轮数,让已经到达上限的回复仍能产出要求的结构化输出。"+ },+ "interruption-message": {+ "label": "中断回复",+ "description": "用户中断回复时,智能体给出的回复内容。"+ },+ "interruption-raise-cancelled-error": {+ "label": "抛出 CancelledError",+ "description": "处理完中断后重新抛出 asyncio.CancelledError,而不是将其吞掉。"}},"invite-config": {diff --git a/examples/web_ui/frontend/src/lib/query-client.ts b/examples/web_ui/frontend/src/lib/query-client.tsnew file mode 100644index 000000000..c3bec9501--- /dev/null+++ b/examples/web_ui/frontend/src/lib/query-client.ts@@ -0,0 +1,30 @@+import { QueryClient } from '@tanstack/react-query';++/**+ * The app-wide query cache.+ *+ * Nothing here is polled. A cached entry is only re-fetched when a+ * component that needs it mounts again after `staleTime` has passed, and+ * anything the user changes is re-fetched explicitly by the hook that+ * changed it — so this window is not a correctness mechanism, it only+ * bounds how old a passively open view may get. That is what makes a+ * minute safe: it costs one request per page visit at most, instead of+ * one per page visit unconditionally.+ *+ * Data that cannot change while the server is up — the hub lists, the+ * agent form schema — overrides this with `staleTime: Infinity` at the+ * hook. Anything that must always be fresh (session messages, workspace+ * and git status, index polling) stays off this cache entirely.+ */+export const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ staleTime: 60_000,+ // A failed fetch surfaces in the UI as an error state with a+ // retry button; retrying a handful of times behind the user's+ // back only delays that.+ retry: 1,+ refetchOnWindowFocus: false,+ },+ },+});diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsxindex 813071497..a7ed618d5 100644--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx@@ -70,12 +70,12 @@ interface ChatViewportProps {*/sessionId: string | null;/**- * Optional hook invoked when a team membership change arrives on- * this viewport's SSE stream. The outer page owns the session list- * that backs the team sidebar, so it must be told to refetch too;- * passing this callback wires that signal up.+ * Optional hook invoked when a server-side change to this session+ * or its team arrives on the SSE stream. The outer page owns the+ * session list that backs the sidebar, so it must be told to+ * refetch too; passing this callback wires that signal up.*/- onTeamUpdated?: () => void;+ onSessionsChanged?: () => void;}/** Maximum number of panels stacked in a single dock column. */@@ -168,7 +168,7 @@ function closePanelInLayout(layout: PanelKey[][], key: PanelKey): PanelKey[][] {* session is selected yet.* @returns The right-side main JSX of the chat page.*/-export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewportProps) {+export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatViewportProps) {const { t } = useTranslation();const { sessions, refetch: refetchSessions } = useSessions(agentId);const { groups } = useAvailableModels();@@ -212,8 +212,17 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport// close a panel the user already has open.setPanelLayout((layout) => openPanelInLayout(layout, 'team'));}- onTeamUpdated?.();- }, [refetchSessions, sessionId, onTeamUpdated]);+ onSessionsChanged?.();+ }, [refetchSessions, sessionId, onSessionsChanged]);++ // Auto-naming replaced the session's placeholder name. The outer+ // page shares this cached list whenever both are looking at the same+ // agent; when they are not — drilled into a team member — it needs+ // its own nudge.+ const handleSessionUpdated = useCallback(async () => {+ await refetchSessions();+ onSessionsChanged?.();+ }, [refetchSessions, onSessionsChanged]);const handleStateUpdated = useCallback((value: Record<string, unknown>) => {if (value.tasks_context) {@@ -236,6 +245,7 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport} = useMessages(agentId, sessionId, {onTeamUpdated: handleTeamUpdated,onStateUpdated: handleStateUpdated,+ onSessionUpdated: handleSessionUpdated,});const {mcps,@@ -465,14 +475,13 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport],);- // ChatViewport keeps its own `useSessions(agentId)` instance (the- // outer page has a separate one). Its built-in fetch only fires on- // `agentId` change, so when the outer page creates a new session- // under the same agent, this list doesn't auto-refresh. Without- // this refetch, `view` would stay `null` for the brand-new session- // id and every effect below would early-return on `!view`,- // leaving the model select and friends pinned to whatever the- // previously-viewed session had configured.+ // Safety net for a `view` that never arrives. A session created from+ // the outer page reaches this list on its own, since both mount the+ // same cached query — but not when the two are looking at different+ // agents (drilled into a team member), and not for a write that+ // happened outside either. Without a `view` every effect below+ // early-returns on `!view`, leaving the model select and friends+ // pinned to whatever the previously-viewed session had configured.useEffect(() => {if (!sessionId) return;if (view) return;@@ -695,10 +704,33 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport><div className="flex flex-col flex-1 min-h-0 min-w-0 overflow-x-hidden p-2"><div className="flex flex-row gap-x-2 justify-between">- <div className="flex flex-row items-center gap-x-1">+ <div className="flex min-w-0 flex-row items-center gap-x-1"><SidebarTrigger className="md:hidden" />+ {/* The open session, named opposite its own+ settings. The sidebar is the only other+ place the name appears, and it collapses+ on mobile — so on a narrow screen this is+ the only thing saying which conversation+ is on screen.++ Withheld until the session has something+ in it: an untouched one is still named+ after the timestamp it was created at,+ and a date is worse than no title at all.+ The first reply replaces that with a real+ one. */}+ {msgs.length > 0 && (+ <span+ className="truncate px-2 text-sm text-muted-foreground"+ title={view?.session.config.name}+ >+ {view?.session.config.name}+ </span>+ )}</div>- <div className="flex flex-row gap-x-1">+ {/* Never squeezed by a long session name: the+ name truncates instead. */}+ <div className="flex shrink-0 flex-row gap-x-1"><LlmSelectid="tour-llm-select"variant="ghost"diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsxindex 63ddccbdb..c5a302301 100644--- a/examples/web_ui/frontend/src/pages/chat/index.tsx+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx@@ -83,6 +83,10 @@ const SOURCE_ICON: Record<SessionSource, LucideIcon> = {channel: Cable,};+/** localStorage keys holding the last (agent, session) the user viewed. */+const LAST_AGENT_KEY = 'chat_last_agent';+const LAST_SESSION_KEY = 'chat_last_session';+const ChatPageInner = () => {const navigate = useNavigate();const {@@ -136,21 +140,38 @@ const ChatPageInner = () => {? (urlSessionId ?? null): null;- // Redirect: URL is missing an agent → pick the first one and rewrite- // the URL in-place (replace so we don't pollute history).+ // Remember where the user was, so coming back to a bare `/chat` —+ // from another page, or from a new tab — reopens it instead of+ // making them pick the same pair again.useEffect(() => {- if (!urlAgentId && agents.length > 0) {- navigate(`/chat/${agents[0].id}`, { replace: true });- }+ if (!urlAgentId || !urlSessionId) return;+ localStorage.setItem(LAST_AGENT_KEY, urlAgentId);+ localStorage.setItem(LAST_SESSION_KEY, urlSessionId);+ }, [urlAgentId, urlSessionId]);++ // Redirect: URL is missing an agent → reopen the last one viewed,+ // falling back to the first, and rewrite the URL in-place (replace+ // so we don't pollute history).+ useEffect(() => {+ if (urlAgentId || agents.length === 0) return;+ const remembered = localStorage.getItem(LAST_AGENT_KEY);+ const agent = agents.find((a) => a.id === remembered) ?? agents[0];+ navigate(`/chat/${agent.id}`, { replace: true });}, [agents, urlAgentId, navigate]);// Redirect: URL has an agent but no session, or its sessionId no- // longer exists for this agent → pick the first available session.+ // longer exists for this agent → reopen the last session viewed+ // under *this* agent, falling back to the first available one.useEffect(() => {if (!urlAgentId || sessions.length === 0) return;const matches = urlSessionId && sessions.some((v) => v.session.id === urlSessionId);if (matches) return;- navigate(`/chat/${urlAgentId}/${sessions[0].session.id}`, { replace: true });+ const remembered =+ localStorage.getItem(LAST_AGENT_KEY) === urlAgentId+ ? localStorage.getItem(LAST_SESSION_KEY)+ : null;+ const view = sessions.find((v) => v.session.id === remembered) ?? sessions[0];+ navigate(`/chat/${urlAgentId}/${view.session.id}`, { replace: true });}, [urlAgentId, urlSessionId, sessions, navigate]);/**@@ -493,7 +514,7 @@ const ChatPageInner = () => {<ChatViewportagentId={effectiveAgentId}sessionId={effectiveSessionId}- onTeamUpdated={refetchSessions}+ onSessionsChanged={refetchSessions}/></div>{selectedAgent && (diff --git a/examples/web_ui/pnpm-lock.yaml b/examples/web_ui/pnpm-lock.yamlindex 6b81501ec..6c95ef745 100644--- a/examples/web_ui/pnpm-lock.yaml+++ b/examples/web_ui/pnpm-lock.yaml@@ -84,6 +84,9 @@ importers:'@tailwindcss/vite':specifier: ^4.3.0+ '@tanstack/react-query':+ specifier: ^5.102.8+ version: 5.102.8([email protected])class-variance-authority:specifier: ^0.7.1version: 0.7.1@@ -1807,6 +1810,14 @@ packages:peerDependencies:vite: ^5.2.0 || ^6 || ^7 || ^8+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-ZNjkJ33CqvPNec/6lZBnHqLc3EVGPZ9ySLhYahU9TcuRFdmwXewuj0c4hwSWcGHqEUwcSrKeZ+oGcvPBqXcQcg==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-TYBea4OuXWD7MhaSHq069TWbFe7rcwWN6kzT7JF0OKi1K6c1gTv2IzD6A6ExJsCMozdkqBWeuIUZmu4KQg0O5A==}+ peerDependencies:+ react: ^18 || ^19+'@ts-morph/[email protected]':resolution: {integrity: sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==}@@ -6718,6 +6729,13 @@ snapshots:tailwindcss: 4.3.0+ '@tanstack/[email protected]': {}++ '@tanstack/[email protected]([email protected])':+ dependencies:+ '@tanstack/query-core': 5.102.8+ react: 19.2.6+'@ts-morph/[email protected]':dependencies:fast-glob: 3.3.3diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex f90cb22f6..4f4add0f1 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -45,6 +45,7 @@ from ..storage import (SessionKnowledgeConfig,TTSModelConfig,SessionConfig,+ SessionNaming,SessionRecord,StorageBase,TeamRecord,@@ -352,6 +353,10 @@ async def create_session(fallback_chat_model_config=body.fallback_chat_model_config,tts_model_config=body.tts_model_config,knowledge_config=body.knowledge_config,+ # A caller that named the session owns that name; anything+ # else starts on the creation timestamp and is the server's+ # to replace once the conversation says what it is about.+ naming=SessionNaming(auto=body.name is None),**({"name": body.name} if body.name is not None else {}),),)@@ -538,6 +543,14 @@ async def update_session(exclude={"permission_mode"},)+ # An explicit rename settles the name for good — auto-naming must+ # not overwrite what the user just typed.+ if "name" in config_updates:+ config_updates["naming"] = {+ **existing.config.naming.model_dump(),+ "auto": False,+ }+return await storage.upsert_session(user_id=user_id,agent_id=agent_id,diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex 5c01689a6..85a619082 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -18,6 +18,7 @@ from dataclasses import dataclassfrom typing import Literal, TYPE_CHECKINGfrom fastapi import HTTPException+from pydantic import BaseModel, Fieldfrom .._bus_ops import (abandon_inbox_consumer,@@ -30,7 +31,13 @@ from .._bus_ops import (from ..message_bus import MessageBus, MessageBusKeysfrom ..rag.knowledge_base_manager import KnowledgeBaseManagerBasefrom ..channel import ChatKind-from ..storage import StorageBase, AgentRecord, SessionRecord, SessionSource+from ..storage import (+ StorageBase,+ AgentRecord,+ SessionNaming,+ SessionRecord,+ SessionSource,+)from ..storage._utils import _resolve_team_leaderfrom .._manager import BackgroundTaskManager, SchedulerManagerfrom ..workspace_manager import WorkspaceManagerBase@@ -57,8 +64,10 @@ from ._projectors import SubagentHitlProjectorfrom ..._logging import loggerfrom ...agent import Agent, ModelConfig+from ...model import ChatModelBasefrom ...event import (AgentEvent,+ CustomEvent,ReplyStartEvent,ReplyEndEvent,ReplyFinishedReason,@@ -68,7 +77,7 @@ from ...event import ()from ._errors import _classify_error, _classify_setup_errorfrom ..._utils._common import _generate_id-from ...message import AssistantMsg, HintBlock, Msg, ToolCallState+from ...message import AssistantMsg, HintBlock, Msg, ToolCallState, UserMsgfrom ...permission import AdditionalWorkingDirectoryif TYPE_CHECKING:@@ -95,6 +104,30 @@ class _WorkerContext:_TeamContext = _LeaderContext | _WorkerContext+class _SessionTitle(BaseModel):+ """Structured output of the session auto-naming call."""++ title: str = Field(+ description=(+ "A short title for the conversation, written in the same "+ "language as the user's message, at most eight words, with "+ "no quotes and no trailing punctuation."+ ),+ )+++_NAMING_PROMPT = (+ "Give the conversation that opens with the following message a "+ "short title.\n\n{text}"+)++# How much of the opening message the naming model sees, and how long+# the resulting name may be. A name is a sidebar label, not a summary,+# and a pasted wall of text must not become either.+_NAMING_INPUT_LIMIT = 2000+_NAMING_NAME_LIMIT = 60++class ChatService:"""Run an agent against a session, persisting input/reply messagesand updated agent state.@@ -287,6 +320,100 @@ class ChatService:str(e),)+ async def _auto_name_session(+ self,+ user_id: str,+ agent_id: str,+ session_record: SessionRecord,+ model: ChatModelBase,+ trigger_text: str,+ ) -> None:+ """Replace a session's placeholder name with a real title.++ A session created from the UI is named after its creation+ timestamp, which says nothing about what it holds. Once its+ first reply is on disk, the opening user message is handed to+ the session's own model for a short title.++ Best-effort by construction. When the model call fails — a+ misconfigured credential being the usual reason, in which case+ the reply itself has already failed and been reported — an+ excerpt of that same message is used, which still beats a+ timestamp. Nothing is retried and nothing is surfaced to the+ user: the same broken credential must not be reported twice.++ Either way the name is settled (``naming.auto`` is cleared) so+ this runs at most once per session, and the session's event+ stream is told to re-read the session list.++ Args:+ user_id (`str`):+ Owner of the session.+ agent_id (`str`):+ The agent the session belongs to.+ session_record (`SessionRecord`):+ The session to name, as loaded at the start of the run.+ model (`ChatModelBase`):+ The session's own chat model, reused for the title.+ trigger_text (`str`):+ Text of the user turn that opened the run. Empty when+ the turn carried no text (an image-only message, or a+ background wakeup), in which case naming is skipped and+ left for a later turn.+ """+ if not session_record.config.naming.auto or not trigger_text:+ return++ name = trigger_text[:_NAMING_NAME_LIMIT]+ try:+ res = await model.generate_structured_output(+ messages=[+ UserMsg(+ name="user",+ content=_NAMING_PROMPT.format(+ text=trigger_text[:_NAMING_INPUT_LIMIT],+ ),+ ),+ ],+ structured_model=_SessionTitle,+ )+ title = str(res.content.get("title") or "").strip()+ if title:+ name = title[:_NAMING_NAME_LIMIT]+ except Exception as e: # pylint: disable=broad-except+ logger.warning(+ "Auto-naming session %r failed, keeping an excerpt of "+ "the first message instead: %s",+ session_record.id,+ e,+ )++ try:+ await self._storage.upsert_session(+ user_id=user_id,+ agent_id=agent_id,+ config=session_record.config.model_copy(+ update={"name": name, "naming": SessionNaming(auto=False)},+ ),+ session_id=session_record.id,+ )+ await publish_session_event(+ self._message_bus,+ session_record.id,+ CustomEvent(name="session_updated", value={}).model_dump(+ mode="json",+ ),+ )+ except Exception as e: # pylint: disable=broad-except+ # This runs from the run's ``finally``, where a raise would+ # replace whatever exception is already on its way out. A+ # session left on its timestamp is not worth that.+ logger.warning(+ "Recording the name of session %r failed: %s",+ session_record.id,+ e,+ )+async def _close_failed_reply(self,session_id: str,@@ -1034,6 +1161,18 @@ class ChatService:reply_msg: Msg | None = Nonereply_msgs: list[Msg] = []released = False++ # Text of the user turn that opened this run, captured+ # before the loop reassigns ``input_msg``; auto-naming+ # reads it once the reply is persisted.+ trigger_msgs: list[Msg] = []+ if isinstance(input_msg, Msg):+ trigger_msgs = [input_msg]+ elif isinstance(input_msg, list):+ trigger_msgs = input_msg+ trigger_text = "\n".join(+ msg.get_text_content() or "" for msg in trigger_msgs+ ).strip()await register_inbox_consumer(self._message_bus, session_id)try:while True:@@ -1305,6 +1444,18 @@ class ChatService:await persist_taskraise+ # Still under the session lock, so this config write+ # cannot race the next turn's snapshot of it. Skipped on+ # the cancellation path above — a run being torn down+ # has no business renaming anything.+ await self._auto_name_session(+ user_id,+ agent_id,+ session_record,+ model,+ trigger_text,+ )+async def _project_event(self,user_id: str,diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.pyindex 8db3e1b4b..b5b73c7c1 100644--- a/src/agentscope/app/storage/__init__.py+++ b/src/agentscope/app/storage/__init__.py@@ -24,6 +24,7 @@ from ._model import (ScheduleRecord,ScheduleSource,SessionConfig,+ SessionNaming,SessionKnowledgeConfig,SessionRecord,SessionSource,@@ -87,6 +88,7 @@ __all__ = ["KnowledgeDocumentStatus","MCPRecord","SessionConfig",+ "SessionNaming","SessionKnowledgeConfig","SessionRecord","SessionSource",diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.pyindex f31a3ffa1..823ed44c0 100644--- a/src/agentscope/app/storage/_model/__init__.py+++ b/src/agentscope/app/storage/_model/__init__.py@@ -25,6 +25,7 @@ from ._schedule import ScheduleData, ScheduleRecord, ScheduleSourcefrom ._session import (SessionRecord,SessionConfig,+ SessionNaming,SessionKnowledgeConfig,ChatModelConfig,TTSModelConfig,@@ -55,6 +56,7 @@ __all__ = ["ScheduleRecord","ScheduleSource","SessionConfig",+ "SessionNaming","SessionKnowledgeConfig","SessionRecord","SessionSource",diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.pyindex 79d9b8303..78ba2ffc0 100644--- a/src/agentscope/app/storage/_model/_session.py+++ b/src/agentscope/app/storage/_model/_session.py@@ -111,6 +111,29 @@ class SessionKnowledgeConfig(BaseModel):"""+class SessionNaming(BaseModel):+ """How :attr:`SessionConfig.name` is maintained."""++ auto: bool = Field(+ default=False,+ description=(+ "Whether the server may still replace the session name with "+ "a title derived from the conversation."+ ),+ )+ """Whether the display name is the server's to choose.++ Set at creation for sessions created without an explicit name, and+ cleared as soon as the name is settled — either by the user renaming+ the session or by the generated title landing.++ Defaults to ``False``, which is what makes this safe to add to an+ existing deployment: records written before auto-naming existed carry+ no ``naming`` block at all, so they load with ``auto=False`` and keep+ whatever name they already have.+ """++class SessionConfig(BaseModel):"""Session configuration — set at creation, updatable via PATCH."""@@ -131,6 +154,9 @@ class SessionConfig(BaseModel):)"""The session display name."""+ naming: SessionNaming = Field(default_factory=SessionNaming)+ """Who owns :attr:`name`; see :class:`SessionNaming`."""+cwd: str | None = Field(default=None,description=(diff --git a/tests/session_auto_naming_test.py b/tests/session_auto_naming_test.pynew file mode 100644index 000000000..326a36f18--- /dev/null+++ b/tests/session_auto_naming_test.py@@ -0,0 +1,395 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Session auto-naming test cases.++A session created without a name is named after its creation timestamp,+which says nothing about what it holds; the first reply replaces that+with a title. The name a *person* chose must never be overwritten by+that, so ownership is tracked on ``SessionConfig.naming`` and asserted+from both ends here:++- the router sets and clears the flag (creation, rename), and a record+ written before the flag existed loads as user-owned, and+- :meth:`ChatService._auto_name_session` honours it, falls back to an+ excerpt of the opening message when the model call fails, and settles+ the name so it runs at most once per session.+"""+import tempfile+from typing import Any+from unittest import IsolatedAsyncioTestCase++import fakeredis.aioredis+from fastapi.testclient import TestClient++from utils import AnyString++from agentscope.agent import ContextConfig, ReActConfig+from agentscope.app import create_app+from agentscope.app._service import ChatService+from agentscope.app.message_bus import (+ InMemoryMessageBus,+ MessageBusKeys,+ RedisMessageBus,+)+from agentscope.app.storage import (+ AgentData,+ AgentRecord,+ ChatModelConfig,+ RedisStorage,+ SessionConfig,+ SessionNaming,+ SessionRecord,+)+from agentscope.app.workspace_manager import LocalWorkspaceManager++HEADERS = {"X-User-ID": "alice"}+++class SessionNameOwnershipTest(IsolatedAsyncioTestCase):+ """Who owns ``config.name``, as decided by the session router."""++ async def asyncSetUp(self) -> None:+ """Start an app backed by fakeredis and seed one agent."""+ # enterContext binds the context manager to the test's lifetime;+ # pylint does not recognise the unittest-native helper.+ # pylint: disable=consider-using-with+ workdir = self.enterContext(tempfile.TemporaryDirectory())+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)++ class _Storage(RedisStorage):+ async def __aenter__(self) -> Any:+ self._client = redis+ return self++ async def aclose(self) -> None:+ self._client = None++ class _Bus(RedisMessageBus):+ async def __aenter__(self) -> Any:+ self._client = redis+ return self++ async def aclose(self) -> None:+ self._client = None++ app = create_app(+ storage=_Storage(),+ message_bus=_Bus(),+ workspace_manager=LocalWorkspaceManager(workdir),+ enable_index_worker=False,+ )+ self.client = self.enterContext(TestClient(app))+ self.storage = app.state.storage+ self.agent_id = await self.storage.upsert_agent(+ "alice",+ AgentRecord(+ user_id="alice",+ data=AgentData(+ name="ann",+ system_prompt="You are ann.",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ ),+ ),+ )++ async def _create(self, body: dict) -> str:+ """Create a session and return its id."""+ response = self.client.post("/sessions/", headers=HEADERS, json=body)+ self.assertEqual(response.status_code, 201)+ return response.json()["session_id"]++ async def _config(self, session_id: str) -> dict:+ """Return the stored config of *session_id* as plain JSON."""+ record = await self.storage.get_session(+ "alice",+ self.agent_id,+ session_id,+ )+ return record.config.model_dump(mode="json")++ async def test_unnamed_session_is_the_servers_to_name(self) -> None:+ """No name at creation leaves the placeholder up for grabs."""+ session_id = await self._create({"agent_id": self.agent_id})++ self.assertDictEqual(+ await self._config(session_id),+ {+ "workspace_id": AnyString(),+ # The creation timestamp — a placeholder, hence `auto`.+ "name": AnyString(),+ "naming": {"auto": True},+ "cwd": None,+ "chat_model_config": None,+ "fallback_chat_model_config": None,+ "tts_model_config": None,+ "knowledge_config": None,+ },+ )++ async def test_name_given_at_creation_is_kept(self) -> None:+ """A caller that names the session owns that name."""+ session_id = await self._create(+ {"agent_id": self.agent_id, "name": "release notes"},+ )++ self.assertDictEqual(+ await self._config(session_id),+ {+ "workspace_id": AnyString(),+ "name": "release notes",+ "naming": {"auto": False},+ "cwd": None,+ "chat_model_config": None,+ "fallback_chat_model_config": None,+ "tts_model_config": None,+ "knowledge_config": None,+ },+ )++ async def test_rename_takes_ownership(self) -> None:+ """Renaming settles the name against later auto-naming."""+ session_id = await self._create({"agent_id": self.agent_id})++ response = self.client.patch(+ f"/sessions/{session_id}",+ headers=HEADERS,+ params={"agent_id": self.agent_id},+ json={"name": "my own name"},+ )++ self.assertEqual(response.status_code, 200)+ self.assertDictEqual(+ await self._config(session_id),+ {+ "workspace_id": AnyString(),+ "name": "my own name",+ "naming": {"auto": False},+ "cwd": None,+ "chat_model_config": None,+ "fallback_chat_model_config": None,+ "tts_model_config": None,+ "knowledge_config": None,+ },+ )++ async def test_unrelated_patch_leaves_ownership_alone(self) -> None:+ """A PATCH that is not a rename must not settle the name."""+ session_id = await self._create({"agent_id": self.agent_id})++ response = self.client.patch(+ f"/sessions/{session_id}",+ headers=HEADERS,+ params={"agent_id": self.agent_id},+ json={"cwd": "sub/dir"},+ )++ self.assertEqual(response.status_code, 200)+ self.assertDictEqual(+ await self._config(session_id),+ {+ "workspace_id": AnyString(),+ "name": AnyString(),+ "naming": {"auto": True},+ "cwd": "sub/dir",+ "chat_model_config": None,+ "fallback_chat_model_config": None,+ "tts_model_config": None,+ "knowledge_config": None,+ },+ )++ def test_record_written_before_naming_existed_is_user_owned(self) -> None:+ """An upgraded deployment must not rename existing sessions.++ Sessions persisted by an earlier version carry no ``naming``+ block at all, so the field's default is what decides whether+ their names survive the upgrade.+ """+ config = SessionConfig.model_validate(+ {"workspace_id": "workspace-1", "name": "named last month"},+ )++ self.assertDictEqual(+ config.model_dump(mode="json"),+ {+ "workspace_id": "workspace-1",+ "name": "named last month",+ "naming": {"auto": False},+ "cwd": None,+ "chat_model_config": None,+ "fallback_chat_model_config": None,+ "tts_model_config": None,+ "knowledge_config": None,+ },+ )+++class _Storage:+ """Record what auto-naming writes back."""++ def __init__(self, session: SessionRecord) -> None:+ self.session = session+ self.written_configs: list[SessionConfig] = []++ async def upsert_session(+ self,+ user_id: str,+ agent_id: str,+ config: SessionConfig,+ session_id: str | None = None,+ **_: Any,+ ) -> SessionRecord:+ """Apply the config write and remember it."""+ assert user_id == self.session.user_id+ assert agent_id == self.session.agent_id+ assert session_id == self.session.id+ self.written_configs.append(config.model_copy(deep=True))+ self.session.config = config+ return self.session+++class _Model:+ """A chat model that answers the naming call, or refuses to."""++ def __init__(self, title: str | None = None) -> None:+ self.title = title+ self.calls: list[list[Any]] = []++ async def generate_structured_output(+ self,+ messages: list[Any],+ structured_model: Any,+ ) -> Any:+ """Return the configured title, or fail like a bad credential."""+ del structured_model+ self.calls.append(messages)+ if self.title is None:+ raise RuntimeError("401 Unauthorized: invalid api key")++ class _Response:+ content = {"title": self.title}++ return _Response()+++class AutoNameSessionTest(IsolatedAsyncioTestCase):+ """The naming step itself, driven directly against stubs."""++ def setUp(self) -> None:+ """Build a service over a single unnamed session."""+ self.session = SessionRecord(+ id="session-1",+ user_id="user-1",+ agent_id="agent-1",+ config=SessionConfig(+ workspace_id="workspace-1",+ name="2026-08-31 10:00:00",+ naming=SessionNaming(auto=True),+ chat_model_config=ChatModelConfig(+ type="test",+ credential_id="credential-1",+ model="test-model",+ parameters={},+ ),+ ),+ )+ self.storage = _Storage(self.session)+ self.bus = InMemoryMessageBus()+ self.service = ChatService(+ storage=self.storage,+ workspace_manager=object(),+ scheduler_manager=object(),+ background_task_manager=object(),+ message_bus=self.bus,+ resource_access_service=object(),+ )++ async def _name(self, model: _Model, trigger_text: str) -> None:+ """Run the naming step for the seeded session."""+ await self.service._auto_name_session(+ "user-1",+ "agent-1",+ self.session,+ model,+ trigger_text,+ )++ async def _published(self) -> list[dict]:+ """Return the events auto-naming put on the session stream."""+ entries = await self.bus.log_read(+ MessageBusKeys.session_events("session-1"),+ )+ return [payload for _, payload in entries]++ async def test_generated_title_replaces_the_placeholder(self) -> None:+ """A working model names the session and settles the name."""+ await self._name(_Model("Release notes for v2"), "draft the v2 notes")++ self.assertListEqual(+ [c.model_dump(mode="json") for c in self.storage.written_configs],+ [+ {+ "workspace_id": "workspace-1",+ "name": "Release notes for v2",+ "naming": {"auto": False},+ "cwd": None,+ "chat_model_config": {+ "type": "test",+ "credential_id": "credential-1",+ "model": "test-model",+ "parameters": {},+ },+ "fallback_chat_model_config": None,+ "tts_model_config": None,+ "knowledge_config": None,+ },+ ],+ )+ self.assertListEqual(+ await self._published(),+ [+ {+ "type": "CUSTOM",+ "id": AnyString(),+ "created_at": AnyString(),+ "name": "session_updated",+ "value": {},+ "metadata": {},+ },+ ],+ )++ async def test_model_failure_falls_back_to_an_excerpt(self) -> None:+ """A dead credential still beats leaving the timestamp up."""+ await self._name(_Model(), "draft the v2 release notes")++ self.assertListEqual(+ [(c.name, c.naming.auto) for c in self.storage.written_configs],+ [("draft the v2 release notes", False)],+ )++ async def test_long_title_is_truncated(self) -> None:+ """A model that ignores the brief cannot widen the sidebar."""+ await self._name(_Model("word " * 40), "anything")++ self.assertListEqual(+ [len(c.name) for c in self.storage.written_configs],+ [60],+ )++ async def test_settled_name_is_left_alone(self) -> None:+ """A session the user named is never re-named, nor announced."""+ self.session.config.naming = SessionNaming(auto=False)++ await self._name(_Model("a title"), "some opening message")++ self.assertListEqual(self.storage.written_configs, [])+ self.assertListEqual(await self._published(), [])++ async def test_textless_turn_is_left_for_later(self) -> None:+ """An image-only opening turn gives nothing to name from."""+ await self._name(_Model("a title"), "")++ self.assertListEqual(self.storage.written_configs, [])+ self.assertListEqual(await self._published(), [])