Skip to content

Build and run agents you can see, understand and trust.

feat(webui): display background tool status and execution duration (#3883)

qbcea1f1d20986d
diff --git a/examples/web_ui/frontend/src/api/backgroundTask.ts b/examples/web_ui/frontend/src/api/backgroundTask.ts
new file mode 100644
index 000000000..bcfb7fe08
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/backgroundTask.ts
@@ -0,0 +1,11 @@
+import { client } from './client';
+import type { ListBackgroundTasksResponse } from './types';
+
+export const backgroundTaskApi = {
+ list: (sessionId: string, baseUrl: string, userId: string, signal: AbortSignal) =>
+ client.get<ListBackgroundTasksResponse>(
+ '/background-tasks',
+ { session_id: sessionId },
+ { baseUrl, userId, signal, silent: true, timeoutMs: 10_000 },
+ ),
+};
diff --git a/examples/web_ui/frontend/src/api/client.ts b/examples/web_ui/frontend/src/api/client.ts
index 47252d0ee..8facbf302 100644
--- a/examples/web_ui/frontend/src/api/client.ts
+++ b/examples/web_ui/frontend/src/api/client.ts
@@ -126,7 +126,13 @@ export const client = {
get: <T>(
path: string,
params?: Record<string, string>,
- options?: { silent?: boolean; baseUrl?: string; userId?: string; timeoutMs?: number },
+ options?: {
+ silent?: boolean;
+ signal?: AbortSignal;
+ baseUrl?: string;
+ userId?: string;
+ timeoutMs?: number;
+ },
) => request<T>(path, { method: 'GET', params, ...options }),
post: <T>(
path: string,
diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.ts
index 478592bde..b080bf555 100644
--- a/examples/web_ui/frontend/src/api/index.ts
+++ b/examples/web_ui/frontend/src/api/index.ts
@@ -23,3 +23,4 @@ export type {
export type { TTSModelCard } from './types';
export { channelApi } from './channel';
export { healthApi } from './health';
+export { backgroundTaskApi } from './backgroundTask';
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index c3e876b5f..4774350e8 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -413,6 +413,31 @@ export interface SessionView {
team: TeamDetailResponse | null;
}
+// ─── Background tools ─────────────────────────────────────────────────────────
+
+export type BackgroundTaskStatus = 'running' | 'completed' | 'failed' | 'cancelled';
+
+export interface BackgroundTaskInfo {
+ task_id: string;
+ session_id: string;
+ agent_id: string;
+ tool_name: string;
+ summary: string;
+ status: BackgroundTaskStatus;
+ /** UTC date-time when the tool was registered for background execution. */
+ started_at: string;
+ /** Actual execution start, absent or null in records created by older servers. */
+ execution_started_at?: string | null;
+ completed_at: string | null;
+ error_summary: string | null;
+}
+
+export interface ListBackgroundTasksResponse {
+ tasks: BackgroundTaskInfo[];
+ /** Includes retained terminal tasks; this is not the running count. */
+ total: number;
+}
+
// ─── JSON Schema ──────────────────────────────────────────────────────────────
/**
diff --git a/examples/web_ui/frontend/src/components/panel/BackgroundTasksPanel.tsx b/examples/web_ui/frontend/src/components/panel/BackgroundTasksPanel.tsx
new file mode 100644
index 000000000..e3daabd08
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/panel/BackgroundTasksPanel.tsx
@@ -0,0 +1,260 @@
+import { formatDistanceStrict } from 'date-fns';
+import { enUS, zhCN } from 'date-fns/locale';
+import {
+ Activity,
+ Check,
+ ChevronDown,
+ CircleAlert,
+ CircleCheck,
+ CircleSlash,
+ Copy,
+ Loader2,
+ MessageSquare,
+} from 'lucide-react';
+import { useEffect, useState } from 'react';
+
+import type { BackgroundTaskInfo } from '@/api';
+import { PanelEmpty } from '@/components/panel/PanelEmpty';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+import { useTranslation } from '@/i18n/useI18n';
+import { cn } from '@/lib/utils';
+import { copyToClipboard } from '@/utils/common';
+
+const STATUS_ICONS = {
+ running: Loader2,
+ completed: CircleCheck,
+ failed: CircleAlert,
+ cancelled: CircleSlash,
+};
+
+function BackgroundTaskRow({ task, now }: { task: BackgroundTaskInfo; now: number }) {
+ const { t, i18n } = useTranslation();
+ const [copied, setCopied] = useState(false);
+ const Icon = STATUS_ICONS[task.status];
+ const started = new Date(task.started_at).getTime();
+ const ended = task.completed_at ? new Date(task.completed_at).getTime() : now;
+ const duration = formatDistanceStrict(started, Math.max(started, ended), {
+ locale: i18n.language.startsWith('zh') ? zhCN : enUS,
+ });
+ const executionStarted = task.execution_started_at
+ ? Date.parse(task.execution_started_at)
+ : null;
+ const totalDuration =
+ executionStarted !== null
+ ? formatDistanceStrict(executionStarted, Math.max(executionStarted, ended), {
+ locale: i18n.language.startsWith('zh') ? zhCN : enUS,
+ })
+ : null;
+
+ useEffect(() => {
+ if (!copied) return;
+ const timer = window.setTimeout(() => setCopied(false), 2000);
+ return () => window.clearTimeout(timer);
+ }, [copied]);
+
+ return (
+ <li className="min-w-0 rounded-xl border border-border/60 p-3">
+ <div className="flex items-start justify-between gap-2">
+ <span className="min-w-0 break-words text-sm font-medium [overflow-wrap:anywhere]">
+ {task.tool_name}
+ </span>
+ <Badge
+ variant="outline"
+ className={cn('shrink-0 gap-1', task.status === 'failed' && 'text-destructive')}
+ >
+ <Icon
+ className={cn(
+ 'size-3',
+ task.status === 'running' && 'motion-safe:animate-spin',
+ )}
+ />
+ {t(`panel.background.status.${task.status}`)}
+ </Badge>
+ </div>
+ {task.summary && (
+ <p className="mt-2 whitespace-pre-wrap text-xs leading-relaxed text-muted-foreground [overflow-wrap:anywhere]">
+ {task.summary}
+ </p>
+ )}
+ <p className="mt-2 text-xs tabular-nums text-muted-foreground">
+ {totalDuration !== null
+ ? t('panel.background.totalDuration', { duration: totalDuration })
+ : t('panel.background.duration', { duration })}
+ </p>
+ {totalDuration !== null && (
+ <p className="mt-1 text-xs tabular-nums text-muted-foreground">
+ {t('panel.background.backgroundDuration', { duration })}
+ </p>
+ )}
+ <div className="mt-1 flex min-w-0 items-center gap-1">
+ <span className="shrink-0 text-xs text-muted-foreground">ID</span>
+ <code
+ className="min-w-0 truncate text-xs text-muted-foreground"
+ title={task.task_id}
+ >
+ {task.task_id}
+ </code>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t(copied ? 'panel.background.copied' : 'panel.background.copyId')}
+ tooltip={t(copied ? 'panel.background.copied' : 'panel.background.copyId')}
+ onClick={async () => {
+ if (await copyToClipboard(task.task_id)) setCopied(true);
+ }}
+ >
+ {copied ? <Check /> : <Copy />}
+ </Button>
+ </div>
+ {task.status === 'failed' && task.error_summary && (
+ <Collapsible className="mt-2 border-t border-border/60 pt-2">
+ <CollapsibleTrigger asChild>
+ <Button variant="ghost" size="xs" className="group px-0 text-destructive">
+ <ChevronDown className="transition-transform group-data-[state=open]:rotate-180" />
+ {t('panel.background.errorDetails')}
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <p className="mt-2 whitespace-pre-wrap text-xs leading-relaxed text-muted-foreground [overflow-wrap:anywhere]">
+ {task.error_summary}
+ </p>
+ </CollapsibleContent>
+ </Collapsible>
+ )}
+ </li>
+ );
+}
+
+interface BackgroundTasksPanelProps {
+ sessionId: string | null;
+ tasks: BackgroundTaskInfo[] | undefined;
+ loading: boolean;
+ error: boolean;
+ refreshing: boolean;
+ visible: boolean;
+ updatedAt: number;
+ onRefresh: () => void;
+}
+
+/** Read-only view of running tools and the server's retained terminal snapshots. */
+export function BackgroundTasksPanel({
+ sessionId,
+ tasks,
+ loading,
+ error,
+ refreshing,
+ visible,
+ updatedAt,
+ onRefresh,
+}: BackgroundTasksPanelProps) {
+ const { t } = useTranslation();
+ const [now, setNow] = useState(Date.now);
+ const running = tasks?.filter((task) => task.status === 'running') ?? [];
+ const recent =
+ tasks
+ ?.filter((task) => task.status !== 'running')
+ .sort((a, b) => Date.parse(b.completed_at!) - Date.parse(a.completed_at!)) ?? [];
+ const ticking = visible && !error && running.length > 0;
+
+ useEffect(() => {
+ if (!ticking) return;
+ setNow(Date.now());
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [ticking]);
+
+ if (!sessionId) {
+ return <PanelEmpty icon={MessageSquare} title={t('panel.background.noSession')} />;
+ }
+ if (loading) {
+ return (
+ <div
+ role="status"
+ className="flex flex-1 items-center justify-center gap-2 p-4 text-sm text-muted-foreground"
+ >
+ <Loader2 className="size-4 motion-safe:animate-spin" />
+ {t('panel.loading')}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex min-w-0 flex-1 flex-col gap-3 py-3">
+ {error && (
+ <div
+ role="status"
+ className="rounded-xl border border-destructive/20 bg-destructive/5 p-3"
+ >
+ <p className="text-xs leading-relaxed">
+ {t(tasks ? 'panel.background.stale' : 'panel.background.loadError')}
+ </p>
+ <Button
+ variant="outline"
+ size="xs"
+ className="mt-2"
+ disabled={refreshing}
+ onClick={onRefresh}
+ >
+ {t('common.retry')}
+ </Button>
+ </div>
+ )}
+ {tasks && tasks.length === 0 && !error && (
+ <PanelEmpty
+ icon={Activity}
+ title={t('panel.background.emptyTitle')}
+ description={t('panel.background.emptyDescription')}
+ />
+ )}
+ {tasks && tasks.length > 0 && (
+ <>
+ {running.length > 0 ? (
+ <ul className="space-y-2" aria-label={t('panel.background.status.running')}>
+ {running.map((task) => (
+ <BackgroundTaskRow
+ key={task.task_id}
+ task={task}
+ now={error ? updatedAt : now}
+ />
+ ))}
+ </ul>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ {t('panel.background.noRunning')}
+ </p>
+ )}
+ {recent.length > 0 && (
+ <Collapsible className="min-w-0 border-t border-border/60 pt-2">
+ <CollapsibleTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="group w-full justify-between px-0"
+ >
+ {t('panel.background.recent', { count: recent.length })}
+ <ChevronDown className="transition-transform group-data-[state=open]:rotate-180" />
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <p className="mb-3 mt-1 text-xs leading-relaxed text-muted-foreground">
+ {t('panel.background.retention')}
+ </p>
+ <ul className="space-y-2">
+ {recent.map((task) => (
+ <BackgroundTaskRow
+ key={task.task_id}
+ task={task}
+ now={now}
+ />
+ ))}
+ </ul>
+ </CollapsibleContent>
+ </Collapsible>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/panel/PanelDock.tsx b/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
index 7cf506802..aaa50e84f 100644
--- a/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
+++ b/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
@@ -13,7 +13,14 @@ import { Separator } from '@/components/ui/separator';
* Identifier for a dockable panel. Used both as the React key and to
* look its descriptor up in {@link PanelDockProps.panels}.
*/
-export type PanelKey = 'plan' | 'mcp' | 'skill' | 'permission' | 'knowledge' | 'team';
+export type PanelKey =
+ | 'plan'
+ | 'mcp'
+ | 'skill'
+ | 'permission'
+ | 'knowledge'
+ | 'team'
+ | 'background';
/**
* The presentation of a single panel: header chrome plus its already
diff --git a/examples/web_ui/frontend/src/hooks/useBackgroundTasks.ts b/examples/web_ui/frontend/src/hooks/useBackgroundTasks.ts
new file mode 100644
index 000000000..7e77bba7c
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useBackgroundTasks.ts
@@ -0,0 +1,50 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { useEffect, useMemo, useSyncExternalStore } from 'react';
+
+import { backgroundTaskApi } from '@/api';
+import { getBaseUrl, getUserId } from '@/api/client';
+
+function subscribeVisibility(onChange: () => void) {
+ document.addEventListener('visibilitychange', onChange);
+ return () => document.removeEventListener('visibilitychange', onChange);
+}
+
+const isPageVisible = () => document.visibilityState === 'visible';
+
+/** Poll the selected session even when its last snapshot has no running tasks. */
+export function useBackgroundTasks(sessionId: string | null, open: boolean) {
+ const queryClient = useQueryClient();
+ const visible = useSyncExternalStore(subscribeVisibility, isPageVisible);
+ const baseUrl = getBaseUrl();
+ const userId = getUserId();
+ const queryKey = useMemo(
+ () => ['background-tasks', baseUrl, userId, sessionId],
+ [baseUrl, userId, sessionId],
+ );
+ const active = open && visible && sessionId !== null;
+ const query = useQuery({
+ queryKey,
+ queryFn: ({ signal }) => backgroundTaskApi.list(sessionId!, baseUrl, userId, signal),
+ enabled: active,
+ staleTime: 0,
+ gcTime: 0,
+ retry: false,
+ refetchInterval: active ? 3000 : false,
+ refetchIntervalInBackground: false,
+ refetchOnWindowFocus: true,
+ });
+
+ // Disabling a query stops its timer but does not abort an in-flight fetch.
+ useEffect(() => {
+ if (!active) void queryClient.cancelQueries({ queryKey, exact: true });
+ }, [active, queryClient, queryKey]);
+
+ useEffect(
+ () => () => {
+ void queryClient.cancelQueries({ queryKey, exact: true });
+ },
+ [queryClient, queryKey],
+ );
+
+ return { ...query, visible };
+}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index b147bf1cb..0253ef626 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -663,6 +663,31 @@
"blockedBy": "blocked by"
},
"panel": {
+ "background": {
+ "title": "Background tools",
+ "runningCount": "Running: {{count}}",
+ "refresh": "Refresh background tools",
+ "duration": "Background duration: {{duration}}",
+ "totalDuration": "Total duration: {{duration}}",
+ "backgroundDuration": "Of which in background: {{duration}}",
+ "copyId": "Copy task ID",
+ "copied": "Task ID copied",
+ "errorDetails": "Failure details",
+ "noSession": "Select a conversation to view background tools",
+ "emptyTitle": "No background tools",
+ "emptyDescription": "Tools that continue running in the background will appear here.",
+ "noRunning": "No tools are running in the background.",
+ "recent": "Recently finished ({{count}})",
+ "retention": "Recent results are kept temporarily. This is not a complete history.",
+ "loadError": "Could not load background tools. Try again.",
+ "stale": "Could not refresh. Showing the last known status; tasks may have changed.",
+ "status": {
+ "running": "Running",
+ "completed": "Completed",
+ "failed": "Failed",
+ "cancelled": "Cancelled"
+ }
+ },
"plan": {
"title": "Plan",
"completed": "Completed: {{count}}",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index b54b362d0..ccc4eab42 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -663,6 +663,31 @@
"blockedBy": "依赖"
},
"panel": {
+ "background": {
+ "title": "后台工具",
+ "runningCount": "运行中:{{count}}",
+ "refresh": "刷新后台工具",
+ "duration": "后台运行时长:{{duration}}",
+ "totalDuration": "总执行时长:{{duration}}",
+ "backgroundDuration": "其中后台运行:{{duration}}",
+ "copyId": "复制任务 ID",
+ "copied": "已复制任务 ID",
+ "errorDetails": "失败详情",
+ "noSession": "选择会话以查看后台工具",
+ "emptyTitle": "暂无后台工具",
+ "emptyDescription": "转入后台继续执行的工具会显示在这里。",
+ "noRunning": "当前没有正在后台运行的工具。",
+ "recent": "最近结束({{count}})",
+ "retention": "最近结果仅临时保留,这里不包含完整历史记录。",
+ "loadError": "无法加载后台工具,请重试。",
+ "stale": "刷新失败,当前显示上次获取的状态,任务可能已发生变化。",
+ "status": {
+ "running": "运行中",
+ "completed": "已完成",
+ "failed": "失败",
+ "cancelled": "已取消"
+ }
+ },
"plan": {
"title": "计划",
"completed": "已完成:{{count}}",
diff --git a/examples/web_ui/frontend/src/lib/query-client.ts b/examples/web_ui/frontend/src/lib/query-client.ts
index c3bec9501..b27b7a304 100644
--- a/examples/web_ui/frontend/src/lib/query-client.ts
+++ b/examples/web_ui/frontend/src/lib/query-client.ts
@@ -3,8 +3,9 @@ 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
+ * By default, nothing here is polled. Background tools opt into polling
+ * while their panel and page are visible. Other cached entries are re-fetched
+ * when a component needs them 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
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index 5045597a1..85decd4ef 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -1,13 +1,16 @@
import type { PermissionContext } from '@agentscope-ai/agentscope/permission';
import type { TaskContext } from '@agentscope-ai/agentscope/state';
import {
+ Activity,
BookText,
ChevronDown,
Database,
ListTodo,
PanelRight,
+ RefreshCw,
ShieldCheck,
UsersRound,
+ X,
} from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -25,6 +28,7 @@ import MCPSvg from '@/assets/images/mcp.svg?react';
import { ChatContent } from '@/components/chat/ChatContent.tsx';
import { SubagentHitlCard } from '@/components/chat/SubagentHitlCard';
import { CreateCredentialDialog } from '@/components/dialog/CreateCredentialDialog';
+import { BackgroundTasksPanel } from '@/components/panel/BackgroundTasksPanel';
import { KnowledgeBasePanel } from '@/components/panel/KnowledgeBasePanel';
import { McpPanel } from '@/components/panel/McpPanel';
import { PanelDock, type PanelDescriptor, type PanelKey } from '@/components/panel/PanelDock.tsx';
@@ -43,6 +47,7 @@ import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
+ DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
@@ -50,10 +55,13 @@ import {
ResizablePanel,
ResizablePanelGroup,
} from '@/components/ui/resizable.tsx';
+import { Sheet, SheetClose, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { SidebarTrigger } from '@/components/ui/sidebar';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useAvailableASRModels } from '@/hooks/useAvailableASRModels';
import { useAvailableModels } from '@/hooks/useAvailableModels';
import { useAvailableRealtimeModels } from '@/hooks/useAvailableRealtimeModels';
+import { useBackgroundTasks } from '@/hooks/useBackgroundTasks';
import { useKnowledgeBaseMiddlewareSchema } from '@/hooks/useKnowledgeBaseMiddlewareSchema';
import { useKnowledgeBases } from '@/hooks/useKnowledgeBases';
import { useMessages } from '@/hooks/useMessages';
@@ -103,6 +111,7 @@ const KNOWN_PANELS: Record<PanelKey, true> = {
permission: true,
knowledge: true,
team: true,
+ background: true,
};
/**
@@ -205,6 +214,37 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
// panels stacked top→bottom. Open order determines placement.
// Persisted so leaving and returning to /chat keeps the same panels.
const [panelLayout, setPanelLayout] = useState<PanelKey[][]>(loadPanelLayout);
+ const viewportRef = useRef<HTMLElement>(null);
+ const [panelsInSheet, setPanelsInSheet] = useState(false);
+ // Dismissing the narrow-screen overlay must preserve the desktop layout.
+ const [sheetOpen, setSheetOpen] = useState(true);
+ const [selectedSheetPanel, setSelectedSheetPanel] = useState<PanelKey | null>(null);
+
+ useEffect(() => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+ let frame = 0;
+ // Measure available chat space, including changes to the app sidebars.
+ const observer = new ResizeObserver(([entry]) => {
+ // Change layout in the next frame, outside the observer's delivery loop.
+ window.cancelAnimationFrame(frame);
+ frame = window.requestAnimationFrame(() => {
+ setPanelsInSheet(entry.contentRect.width < 768);
+ });
+ });
+ observer.observe(viewport);
+ return () => {
+ observer.disconnect();
+ window.cancelAnimationFrame(frame);
+ };
+ }, []);
+
+ const dockLayout = panelsInSheet ? [] : panelLayout;
+ const sheetPanelKeys = panelLayout.flat();
+ const activeSheetPanel =
+ selectedSheetPanel && sheetPanelKeys.includes(selectedSheetPanel)
+ ? selectedSheetPanel
+ : sheetPanelKeys[0];
useEffect(() => {
localStorage.setItem(PANEL_LAYOUT_KEY, JSON.stringify(panelLayout));
@@ -322,6 +362,21 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
(key: PanelKey) => panelLayout.some((column) => column.includes(key)),
[panelLayout],
);
+ const backgroundOpen = isPanelOpen('background');
+ const {
+ data: backgroundData,
+ isPending: backgroundLoading,
+ error: backgroundError,
+ isPaused: backgroundPaused,
+ isFetching: backgroundRefreshing,
+ dataUpdatedAt: backgroundUpdatedAt,
+ refetch: refetchBackground,
+ visible: backgroundVisible,
+ } = useBackgroundTasks(
+ sessionId,
+ panelsInSheet ? sheetOpen && activeSheetPanel === 'background' : backgroundOpen,
+ );
+ const backgroundUnavailable = !!backgroundError || backgroundPaused;
/**
* Persist a knowledge-base attachment change. `null` detaches every
@@ -405,6 +460,52 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
// dock itself stays free of any data dependency.
const panels = useMemo<Record<PanelKey, PanelDescriptor>>(
() => ({
+ background: {
+ title: (
+ <span className="flex items-center gap-2">
+ {t('panel.background.title')}
+ {backgroundData && !backgroundUnavailable && (
+ <Badge variant="outline" className="tabular-nums">
+ {t('panel.background.runningCount', {
+ count: backgroundData.tasks.filter(
+ (task) => task.status === 'running',
+ ).length,
+ })}
+ </Badge>
+ )}
+ </span>
+ ),
+ icon: <Activity className="size-4" />,
+ actions: (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('panel.background.refresh')}
+ tooltip={t('panel.background.refresh')}
+ disabled={!sessionId || backgroundRefreshing}
+ onClick={() => void refetchBackground()}
+ >
+ <RefreshCw
+ className={
+ backgroundRefreshing ? 'motion-safe:animate-spin' : undefined
+ }
+ />
+ </Button>
+ ),
+ content: (
+ <BackgroundTasksPanel
+ key={sessionId}
+ sessionId={sessionId}
+ tasks={backgroundData?.tasks}
+ loading={backgroundLoading && !backgroundUnavailable}
+ error={backgroundUnavailable}
+ refreshing={backgroundRefreshing}
+ visible={backgroundVisible}
+ updatedAt={backgroundUpdatedAt}
+ onRefresh={() => void refetchBackground()}
+ />
+ ),
+ },
plan: {
title: t('panel.plan.title'),
icon: <ListTodo className="size-4" />,
@@ -495,6 +596,13 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
}),
[
t,
+ backgroundData,
+ backgroundUnavailable,
+ backgroundLoading,
+ backgroundRefreshing,
+ backgroundUpdatedAt,
+ backgroundVisible,
+ refetchBackground,
tasksContext,
mcps,
mcpsLoading,
@@ -807,15 +915,21 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
return (
<>
- <main className="flex size-full">
+ <main ref={viewportRef} className="flex size-full min-w-0">
<ResizablePanelGroup orientation="horizontal">
<ResizablePanel
className="flex flex-1 rounded-[22px] bg-card shadow-panel"
- minSize="24rem"
+ minSize={panelsInSheet ? '100%' : '24rem'}
>
<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 min-w-0 flex-row items-center gap-x-1">
+ <div
+ className={
+ panelsInSheet
+ ? 'flex min-w-0 max-w-24 items-center gap-x-1'
+ : '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
@@ -839,9 +953,14 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
</span>
)}
</div>
- {/* Never squeezed by a long session name: the
- name truncates instead. */}
- <div className="flex shrink-0 flex-row gap-x-1">
+ {/* Keep the panel menu reachable when chat space is narrow. */}
+ <div
+ className={
+ panelsInSheet
+ ? 'flex min-w-0 flex-1 flex-wrap justify-end gap-1'
+ : 'flex shrink-0 flex-row gap-x-1'
+ }
+ >
<RealtimeModelSelect
value={selectedRealtimeModel}
onChange={handleRealtimeModelChange}
@@ -862,7 +981,7 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
<LlmSelect
id="tour-llm-select"
variant="ghost"
- className="font-mono text-muted-foreground hover:text-foreground"
+ className="max-w-full font-mono text-muted-foreground hover:text-foreground"
value={selectedModel}
onChange={handleLlmChange}
onAddCredential={() => setCredentialOpen(true)}
@@ -900,54 +1019,43 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-auto">
- <DropdownMenuCheckboxItem
- checked={isPanelOpen('plan')}
- onCheckedChange={() => togglePanel('plan')}
- onSelect={(e) => e.preventDefault()}
- >
- <ListTodo />
- {t('panel.plan.title')}
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={isPanelOpen('mcp')}
- onCheckedChange={() => togglePanel('mcp')}
- onSelect={(e) => e.preventDefault()}
- >
- <MCPSvg className="size-4" />
- MCP
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={isPanelOpen('skill')}
- onCheckedChange={() => togglePanel('skill')}
- onSelect={(e) => e.preventDefault()}
- >
- <BookText />
- {t('panel.skill.title')}
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={isPanelOpen('permission')}
- onCheckedChange={() => togglePanel('permission')}
- onSelect={(e) => e.preventDefault()}
- >
- <ShieldCheck />
- {t('panel.permission.title')}
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={isPanelOpen('knowledge')}
- onCheckedChange={() => togglePanel('knowledge')}
- onSelect={(e) => e.preventDefault()}
- >
- <Database />
- {t('panel.knowledge.title')}
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={isPanelOpen('team')}
- onCheckedChange={() => togglePanel('team')}
- onSelect={(e) => e.preventDefault()}
- >
- <UsersRound />
- {t('common.team')}
- </DropdownMenuCheckboxItem>
+ {(
+ [
+ ['background', t('panel.background.title')],
+ ['plan', t('panel.plan.title')],
+ ['mcp', 'MCP'],
+ ['skill', t('panel.skill.title')],
+ ['permission', t('panel.permission.title')],
+ ['knowledge', t('panel.knowledge.title')],
+ ['team', t('common.team')],
+ ] satisfies [PanelKey, string][]
+ ).map(([key, title]) =>
+ panelsInSheet ? (
+ <DropdownMenuItem
+ key={key}
+ onSelect={() => {
+ setPanelLayout((layout) =>
+ openPanelInLayout(layout, key),
+ );
+ setSelectedSheetPanel(key);
+ setSheetOpen(true);
+ }}
+ >
+ {panels[key].icon}
+ {title}
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuCheckboxItem
+ key={key}
+ checked={isPanelOpen(key)}
+ onCheckedChange={() => togglePanel(key)}
+ onSelect={(e) => e.preventDefault()}
+ >
+ {panels[key].icon}
+ {title}
+ </DropdownMenuCheckboxItem>
+ ),
+ )}
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -1075,12 +1183,64 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
</div>
</div>
</ResizablePanel>
- {panelLayout.length > 0 && (
+ {dockLayout.length > 0 && (
<ResizableHandle withHandle className="bg-transparent w-1.5" />
)}
- <PanelDock layout={panelLayout} panels={panels} onClosePanel={closePanel} />
+ <PanelDock layout={dockLayout} panels={panels} onClosePanel={closePanel} />
</ResizablePanelGroup>
</main>
+ {panelsInSheet && activeSheetPanel && (
+ <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
+ <SheetContent
+ className="gap-0 data-[side=right]:w-full sm:max-w-md"
+ aria-describedby={undefined}
+ showCloseButton={false}
+ >
+ <SheetHeader className="flex-row items-center justify-between gap-2">
+ <SheetTitle className="min-w-0 text-sm">
+ {panels[activeSheetPanel].title}
+ </SheetTitle>
+ <div className="flex shrink-0 items-center gap-1">
+ {panels[activeSheetPanel].actions}
+ <SheetClose asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('common.close')}
+ >
+ <X />
+ </Button>
+ </SheetClose>
+ </div>
+ </SheetHeader>
+ <Tabs
+ value={activeSheetPanel}
+ onValueChange={(key) => setSelectedSheetPanel(key as PanelKey)}
+ className="min-h-0 flex-1 gap-3 px-4 pb-4"
+ >
+ <div className="shrink-0 overflow-x-auto">
+ <TabsList>
+ {sheetPanelKeys.map((key) => (
+ <TabsTrigger key={key} value={key}>
+ {panels[key].icon}
+ {panels[key].title}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </div>
+ {sheetPanelKeys.map((key) => (
+ <TabsContent
+ key={key}
+ value={key}
+ className="min-h-0 overflow-y-auto"
+ >
+ {panels[key].content}
+ </TabsContent>
+ ))}
+ </Tabs>
+ </SheetContent>
+ </Sheet>
+ )}
<CreateCredentialDialog open={credentialOpen} onOpenChange={setCredentialOpen} />
</>
);
diff --git a/src/agentscope/app/_manager/_background_task_manager.py b/src/agentscope/app/_manager/_background_task_manager.py
index 48d2ca04f..4fad1d15f 100644
--- a/src/agentscope/app/_manager/_background_task_manager.py
+++ b/src/agentscope/app/_manager/_background_task_manager.py
@@ -73,6 +73,9 @@ class BackgroundTask:
error_summary (`str | None`):
Brief description of the failure reason when
``status == FAILED``.
+ execution_started_at (`float | None`):
+ Unix epoch (UTC) when tool execution began, before offload.
+ ``None`` when the original start time was not recorded.
"""
asyncio_task: asyncio.Task
@@ -108,6 +111,9 @@ class BackgroundTask:
error_summary: str | None = None
"""Brief failure description (populated only for FAILED tasks)."""
+ execution_started_at: float | None = None
+ """Unix epoch (UTC) when tool execution began, if known."""
+
class BackgroundTaskRecord(BaseModel):
"""Serializable task snapshot, independent of the local task handle."""
@@ -124,6 +130,7 @@ class BackgroundTaskRecord(BaseModel):
completed_at: float | None
status: TaskStatus
error_summary: str | None
+ execution_started_at: float | None = None
class _ToolStopParams(BaseModel):
@@ -322,6 +329,7 @@ class BackgroundTaskManager:
tool_name: str = "",
*,
summary: str = "",
+ execution_started_at: float | None = None,
) -> str:
"""Register an already-running asyncio task.
@@ -343,6 +351,9 @@ class BackgroundTaskManager:
summary (`str`, optional):
Short human-readable summary of the tool invocation
for frontend display.
+ execution_started_at (`float | None`, optional):
+ Unix epoch (UTC) when execution began, before offload.
+ Omit when the original start time is unknown.
Returns:
`str`:
@@ -355,6 +366,7 @@ class BackgroundTaskManager:
user_id=user_id,
tool_name=tool_name,
summary=summary,
+ execution_started_at=execution_started_at,
)
task_id = bg_task.id
self.tasks[task_id] = bg_task
diff --git a/src/agentscope/app/_router/_schema/_background_task.py b/src/agentscope/app/_router/_schema/_background_task.py
index eee507069..d83a08a50 100644
--- a/src/agentscope/app/_router/_schema/_background_task.py
+++ b/src/agentscope/app/_router/_schema/_background_task.py
@@ -25,6 +25,11 @@ class BackgroundTaskInfo(BaseModel):
started_at: datetime = Field(
description="UTC timestamp when the task was registered.",
)
+ execution_started_at: datetime | None = Field(
+ default=None,
+ description="UTC timestamp when tool execution began, before "
+ "offload. Null when the original start time was not recorded.",
+ )
completed_at: datetime | None = Field(
default=None,
description="UTC timestamp when the task reached a terminal "
@@ -67,6 +72,14 @@ def to_info(task: BackgroundTaskRecord) -> BackgroundTaskInfo:
task.started_at,
tz=timezone.utc,
),
+ execution_started_at=(
+ datetime.fromtimestamp(
+ task.execution_started_at,
+ tz=timezone.utc,
+ )
+ if task.execution_started_at is not None
+ else None
+ ),
completed_at=(
datetime.fromtimestamp(task.completed_at, tz=timezone.utc)
if task.completed_at is not None
diff --git a/src/agentscope/app/middleware/_tool_offload_middleware.py b/src/agentscope/app/middleware/_tool_offload_middleware.py
index e5fe4deeb..2bc1aedb0 100644
--- a/src/agentscope/app/middleware/_tool_offload_middleware.py
+++ b/src/agentscope/app/middleware/_tool_offload_middleware.py
@@ -21,6 +21,7 @@ bus/wakeup infrastructure, which works correctly across processes.
"""
import asyncio
import json
+import time
from copy import deepcopy
from typing import Any, AsyncGenerator, Callable
@@ -248,6 +249,7 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-method
await queue.put(_QUEUE_SENTINEL)
return response
+ execution_started_at = time.time()
drain_task: asyncio.Task = asyncio.create_task(_drain_to_queue())
# ----------------------------------------------------------------
@@ -424,6 +426,7 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-method
user_id=self._user_id,
tool_name=tool_name,
summary=_make_summary(tool_name, tool_call.input),
+ execution_started_at=execution_started_at,
)
logger.info(
diff --git a/tests/background_task_endpoint_test.py b/tests/background_task_endpoint_test.py
index 23b87a5ca..f568c8a37 100644
--- a/tests/background_task_endpoint_test.py
+++ b/tests/background_task_endpoint_test.py
@@ -33,6 +33,7 @@ from agentscope.app.message_bus import (
from agentscope.app.middleware._tool_offload_middleware import (
_make_summary,
)
+from agentscope.app._router._schema._background_task import to_info
_MANAGER_MODULE = BackgroundTaskManager.__module__
@@ -66,6 +67,7 @@ class TestBackgroundTaskCompatibility(IsolatedAsyncioTestCase):
"completed_at": None,
"status": TaskStatus.RUNNING,
"error_summary": None,
+ "execution_started_at": None,
}
self.assertTrue(is_dataclass(positional))
self.assertEqual(
@@ -109,6 +111,7 @@ class TestBackgroundTaskCompatibility(IsolatedAsyncioTestCase):
"completed_at": None,
"status": "running",
"error_summary": None,
+ "execution_started_at": None,
}
self.assertEqual(json.loads(record.model_dump_json()), expected)
local.status = TaskStatus.COMPLETED
@@ -117,6 +120,44 @@ class TestBackgroundTaskCompatibility(IsolatedAsyncioTestCase):
record.summary = "Changed"
self.assertEqual(local.summary, "Tool(x=1)")
+ async def test_api_preserves_execution_and_background_times(self) -> None:
+ """Total time includes the foreground interval for every outcome."""
+ for status in TaskStatus:
+ with self.subTest(status=status):
+ completed_at = None if status == TaskStatus.RUNNING else 130
+ record = BackgroundTaskRecord(
+ id="id",
+ session_id="s1",
+ agent_id="a1",
+ user_id="alice",
+ tool_name="Bash",
+ summary="Bash(command=sleep 30)",
+ started_at=110,
+ execution_started_at=100,
+ completed_at=completed_at,
+ status=status,
+ error_summary=None,
+ )
+ self.assertEqual(
+ to_info(record).model_dump(mode="json"),
+ {
+ "task_id": "id",
+ "session_id": "s1",
+ "agent_id": "a1",
+ "tool_name": "Bash",
+ "summary": "Bash(command=sleep 30)",
+ "status": status.value,
+ "started_at": "1970-01-01T00:01:50Z",
+ "execution_started_at": "1970-01-01T00:01:40Z",
+ "completed_at": (
+ "1970-01-01T00:02:10Z"
+ if completed_at is not None
+ else None
+ ),
+ "error_summary": None,
+ },
+ )
+
class TestBackgroundTaskRecords( # pylint: disable=too-many-public-methods
IsolatedAsyncioTestCase,
@@ -142,6 +183,7 @@ class TestBackgroundTaskRecords( # pylint: disable=too-many-public-methods
manager: BackgroundTaskManager,
user_id: str = "alice",
session_id: str = "s1",
+ execution_started_at: float | None = None,
) -> tuple[asyncio.Event, asyncio.Task, str]:
"""Register a tool that finishes only when explicitly released."""
gate = asyncio.Event()
@@ -153,6 +195,7 @@ class TestBackgroundTaskRecords( # pylint: disable=too-many-public-methods
user_id,
"Tool",
summary="Tool(x=1)",
+ execution_started_at=execution_started_at,
)
return gate, task, task_id
@@ -194,6 +237,54 @@ class TestBackgroundTaskRecords( # pylint: disable=too-many-public-methods
self.assertEqual(self.owner._completion_tasks, set())
self.assertEqual(self.reader._completion_tasks, set())
+ async def test_execution_start_survives_renewal_and_completion(
+ self,
+ ) -> None:
+ """Preserve the supplied start through shared lifecycle writes."""
+ gate, task, task_id = await self._register(
+ self.owner,
+ execution_started_at=123.0,
+ )
+ expected = BackgroundTaskRecord.model_validate(
+ self.owner.tasks[task_id],
+ ).model_dump()
+ expected["execution_started_at"] = 123.0
+ await self._renew_once()
+ record = await self.reader.get_task(task_id, user_id="alice")
+ self.assertEqual(record.model_dump(), expected)
+ gate.set()
+ await self._settle(task)
+ record = await self.reader.get_task(task_id, user_id="alice")
+ expected.update(
+ status=TaskStatus.COMPLETED,
+ completed_at=record.completed_at,
+ )
+ self.assertEqual(record.model_dump(), expected)
+
+ async def test_old_snapshot_has_unknown_execution_start(self) -> None:
+ """Old snapshots remain readable without inventing a total duration."""
+ gate, task, task_id = await self._register(self.owner)
+ namespace = MessageBusKeys.bg_task_records("alice")
+ payload = json.loads(
+ await self.bus.registry_get(namespace, task_id),
+ )
+ del payload["execution_started_at"]
+ await self.bus.registry_set(
+ namespace,
+ task_id,
+ json.dumps(payload),
+ ttl_secs=MessageBusKeys.BG_TASKS_TTL_SECS,
+ )
+ expected = BackgroundTaskRecord.model_validate(
+ self.owner.tasks[task_id],
+ ).model_dump()
+ expected["execution_started_at"] = None
+ record = await self.reader.get_task(task_id, user_id="alice")
+ self.assertEqual(record.model_dump(), expected)
+ self.assertIsNone(to_info(record).execution_started_at)
+ gate.set()
+ await self._settle(task)
+
async def test_shared_lifecycle_and_isolation(self) -> None:
"""Running and completed records are identical on either worker."""
gate, task, task_id = await self._register(self.owner)
@@ -1247,7 +1338,10 @@ class TestBackgroundTaskRecords( # pylint: disable=too-many-public-methods
async def test_http_routes_read_another_workers_records(self) -> None:
"""The actual app exposes filtered lists, details and isolated 404s."""
- gate, task, task_id = await self._register(self.owner)
+ gate, task, task_id = await self._register(
+ self.owner,
+ execution_started_at=100.0,
+ )
record = await self.reader.get_task(task_id, user_id="alice")
expected = {
"task_id": task_id,
@@ -1262,6 +1356,7 @@ class TestBackgroundTaskRecords( # pylint: disable=too-many-public-methods
)
.isoformat()
.replace("+00:00", "Z"),
+ "execution_started_at": "1970-01-01T00:01:40Z",
"completed_at": None,
"error_summary": None,
}
diff --git a/tests/tool_offload_middleware_test.py b/tests/tool_offload_middleware_test.py
index 86d245222..7854434db 100644
--- a/tests/tool_offload_middleware_test.py
+++ b/tests/tool_offload_middleware_test.py
@@ -5,7 +5,7 @@ import asyncio
import json
from typing import Any, AsyncGenerator
from unittest.async_case import IsolatedAsyncioTestCase
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
from pydantic import BaseModel
@@ -280,6 +280,49 @@ class ToolOffloadMiddlewareTest(IsolatedAsyncioTestCase):
# Background task should be registered
self.assertEqual(len(self.bg_manager.tasks), 1)
+ async def test_execution_start_is_captured_before_offload(self) -> None:
+ """Capture execution start before the handler changes the clock."""
+ agent, middleware = self._make_agent(
+ Toolkit(tools=[SlowTool()]),
+ timeout_secs=0.01,
+ )
+ gate = asyncio.Event()
+ tool_call = ToolCallBlock(
+ id="call_start",
+ name="slow_tool",
+ input='{"delay": 30}',
+ )
+ with patch(f"{ToolOffloadMiddleware.__module__}.time") as clock:
+ clock.time.return_value = 100.0
+
+ async def handler(**_kwargs: Any) -> AsyncGenerator:
+ """Advance wall time after execution has already begun."""
+ clock.time.return_value = 110.0
+ await gate.wait()
+ yield ToolResponse(content=[TextBlock(text="done")])
+
+ async for _ in middleware.on_acting(
+ agent,
+ {"tool_call": tool_call},
+ handler,
+ ):
+ pass
+ (bg_task,) = self.bg_manager.tasks.values()
+ self.assertEqual(
+ {
+ "execution_started_at": bg_task.execution_started_at,
+ "tool_name": bg_task.tool_name,
+ "clock_at_offload": clock.time(),
+ },
+ {
+ "execution_started_at": 100.0,
+ "tool_name": "slow_tool",
+ "clock_at_offload": 110.0,
+ },
+ )
+ gate.set()
+ await asyncio.wait_for(bg_task.asyncio_task, timeout=1)
+
async def test_background_task_result_injected_into_context(
self,
) -> None: