"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: FW-2 wave 2 — durable activity object, Agent decomposition, full ja/ko/ar parity, serif reading voice
Haozhe Wud8c2a600c761
diff --git a/frontend/src/components/chat/ActivityLine.tsx b/frontend/src/components/chat/ActivityLine.tsxnew file mode 100644index 000000000..5d97b886e--- /dev/null+++ b/frontend/src/components/chat/ActivityLine.tsx@@ -0,0 +1,192 @@+import {+ memo,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+ type JSX,+} from "react";+import { useTranslation } from "react-i18next";+import {+ CheckCircle2,+ ChevronDown,+ ChevronRight,+ Clock3,+ Loader2,+ Octagon,+ XCircle,+} from "lucide-react";+import { cn } from "@/lib/utils";+import { localizeToolName } from "@/lib/tools";+import { ToolProgressIndicator } from "@/components/chat/ToolProgressIndicator";+import type { AgentActivity } from "@/stores/agent";++interface ActivityLineProps {+ activity: AgentActivity;+ onContinue?: () => void;+ onReattach?: () => void;+}++const ACTIVE_STATES = new Set<AgentActivity["state"]>([+ "thinking",+ "working",+ "responding",+]);++export function formatActivityElapsed(milliseconds: number): string {+ const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000));+ if (totalSeconds < 60) return `${totalSeconds}s`;+ return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`;+}++function StateIcon({ state }: { state: AgentActivity["state"] }): JSX.Element {+ if (ACTIVE_STATES.has(state)) {+ return <Loader2 className="h-3.5 w-3.5 animate-spin text-primary" aria-hidden="true" />;+ }+ if (state === "done") {+ return <CheckCircle2 className="h-3.5 w-3.5 text-success" aria-hidden="true" />;+ }+ if (state === "stopped") {+ return <Octagon className="h-3.5 w-3.5 text-muted-foreground" aria-hidden="true" />;+ }+ if (state === "timeout") {+ return <Clock3 className="h-3.5 w-3.5 text-amber-600 dark:text-amber-400" aria-hidden="true" />;+ }+ return <XCircle className="h-3.5 w-3.5 text-danger" aria-hidden="true" />;+}++/** The single live and historical status surface for one agent attempt. */+export const ActivityLine = memo(function ActivityLine({+ activity,+ onContinue,+ onReattach,+}: ActivityLineProps): JSX.Element {+ const { t } = useTranslation();+ const detailsId = useId();+ const isActive = ACTIVE_STATES.has(activity.state);+ const [userOpen, setUserOpen] = useState<boolean | null>(null);+ const [autoOpen, setAutoOpen] = useState(true);+ const [now, setNow] = useState(() => Date.now());+ const intervalRef = useRef(0);+ const expanded = userOpen ?? autoOpen;++ useEffect(() => {+ if (isActive) {+ setAutoOpen(true);+ return;+ }+ const timer = window.setTimeout(() => setAutoOpen(false), 900);+ return () => window.clearTimeout(timer);+ }, [isActive]);++ useEffect(() => {+ const stopTimer = () => {+ window.clearInterval(intervalRef.current);+ intervalRef.current = 0;+ };+ if (!isActive) {+ stopTimer();+ setNow(activity.endedAt ?? Date.now());+ return stopTimer;+ }++ const syncTimer = () => {+ stopTimer();+ if (document.hidden) return;+ setNow(Date.now());+ intervalRef.current = window.setInterval(() => setNow(Date.now()), 1000);+ };+ syncTimer();+ document.addEventListener("visibilitychange", syncTimer);+ return () => {+ document.removeEventListener("visibilitychange", syncTimer);+ stopTimer();+ };+ }, [activity.endedAt, isActive]);++ const elapsed = formatActivityElapsed(+ Math.max(0, (activity.endedAt ?? now) - activity.startedAt),+ );+ const stepCount = activity.steps.length;+ const stepsLabel = t("agent.activity.steps" as never, { count: stepCount });+ const verb = t(`agent.activity.verbs.${activity.verb}` as never);+ const newestStep = activity.steps[activity.steps.length - 1];++ const summary = useMemo(() => {+ if (activity.state === "stopped") {+ return `${t("agent.activity.stopped" as never)} · ${stepsLabel} · ${elapsed}`;+ }+ if (activity.state === "timeout") {+ return `${t("agent.activity.timeout" as never, { elapsed })} · ${stepsLabel}`;+ }+ if (activity.state === "failed") {+ return `${t("agent.activity.failed" as never)} · ${stepsLabel} · ${elapsed}`;+ }+ if (activity.state === "done") {+ return `${t("agent.activity.done" as never)} · ${stepsLabel} · ${elapsed}`;+ }+ const latest = newestStep ? localizeToolName(newestStep.tool) : "";+ return [verb, latest, elapsed, stepsLabel].filter(Boolean).join(" · ");+ }, [activity.state, elapsed, newestStep, stepsLabel, t, verb]);++ return (+ <div+ role="status"+ aria-live="polite"+ aria-atomic="false"+ className={cn(+ "overflow-hidden rounded-lg border border-border/40 bg-muted/5",+ isActive && "border-primary/20 bg-primary/[0.025]",+ )}+ >+ <button+ type="button"+ aria-controls={detailsId}+ aria-expanded={expanded}+ onClick={() => setUserOpen(!expanded)}+ className="flex min-h-8 w-full min-w-0 items-center gap-2 px-3 py-1.5 text-[13px] transition-colors hover:bg-muted/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"+ >+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">+ <StateIcon state={activity.state} />+ </span>+ <span className="min-w-0 flex-1 truncate text-start text-muted-foreground">+ {summary}+ </span>+ {expanded+ ? <ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />+ : <ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />}+ </button>++ <div id={detailsId} hidden={!expanded}>+ {activity.steps.length > 0 && (+ <div className="border-t border-border/30 px-3 py-2">+ <ToolProgressIndicator toolCalls={activity.steps} />+ </div>+ )}+ {(activity.state === "stopped" && onContinue) && (+ <div className="flex justify-end border-t border-border/30 px-3 py-2">+ <button+ type="button"+ onClick={onContinue}+ className="rounded-full border border-border/60 px-3 py-1 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("agent.activity.continue" as never)}+ </button>+ </div>+ )}+ {(activity.state === "timeout" && onReattach) && (+ <div className="flex justify-end border-t border-border/30 px-3 py-2">+ <button+ type="button"+ onClick={onReattach}+ className="rounded-full border border-border/60 px-3 py-1 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("agent.activity.reattach" as never)}+ </button>+ </div>+ )}+ </div>+ </div>+ );+});diff --git a/frontend/src/components/chat/Composer.tsx b/frontend/src/components/chat/Composer.tsxnew file mode 100644index 000000000..d32cc967d--- /dev/null+++ b/frontend/src/components/chat/Composer.tsx@@ -0,0 +1,412 @@+import {+ forwardRef,+ memo,+ useCallback,+ useEffect,+ useImperativeHandle,+ useRef,+ useState,+ type ChangeEvent,+ type FormEvent,+ type ReactNode,+} from "react";+import { useTranslation } from "react-i18next";+import {+ Download,+ Landmark,+ Loader2,+ Paperclip,+ Plus,+ Send,+ Square,+ Target,+ Users,+ X,+} from "lucide-react";+import { toast } from "sonner";+import { api } from "@/lib/api";+import type { AgentActivity } from "@/stores/agent";+import {+ LiveRuntimeControl,+ LiveRuntimeStatus,+} from "@/components/chat/LiveRuntimePanel";++const CONNECTOR_CHECK_PROMPT =+ "List my trading connector profiles, show which one is selected, then check that selected connector. If it is not ready, tell me exactly what setup step is missing. Do not place or modify orders.";+const CONNECTOR_PORTFOLIO_PROMPT =+ "Use the selected trading connector profile to summarize my account, positions, concentration, cash, and portfolio risk. Do not place or modify orders.";++const ACCEPTED_FILE_TYPES =+ ".pdf,.docx,.xlsx,.xls,.pptx,.csv,.tsv,.txt,.md,.log,.json,.yaml,.yml,.toml,.html,.xml,.rst,.png,.jpg,.jpeg,.gif,.bmp,.webp,.tiff";++export interface ComposerAttachment {+ filename: string;+ filePath: string;+}++export interface ComposerHandle {+ fill(prompt: string): void;+ focus(): void;+ submit(prompt: string): void;+}++interface Props {+ streaming: boolean;+ activityVerb?: AgentActivity["verb"];+ hasCompletedTurn: boolean;+ showExport: boolean;+ canExport: boolean;+ goalComposerActive: boolean;+ swarmPreset: { name: string; title: string } | null;+ panels?: ReactNode;+ onSubmit: (prompt: string, attachment: ComposerAttachment | null) => void;+ onCancel: () => void;+ onExport: () => void;+ onStartGoal: () => void;+ onCancelGoal: () => void;+ onStartSwarm: () => void;+ onCancelSwarm: () => void;+}++export const Composer = memo(forwardRef<ComposerHandle, Props>(function Composer({+ streaming,+ activityVerb,+ hasCompletedTurn,+ showExport,+ canExport,+ goalComposerActive,+ swarmPreset,+ panels,+ onSubmit,+ onCancel,+ onExport,+ onStartGoal,+ onCancelGoal,+ onStartSwarm,+ onCancelSwarm,+}, ref) {+ const { t } = useTranslation();+ const [input, setInput] = useState("");+ const inputRef = useRef<HTMLTextAreaElement>(null);+ const isComposingRef = useRef(false);+ const lastCompositionEndRef = useRef(0);+ const [attachment, setAttachment] = useState<ComposerAttachment | null>(null);+ const [uploading, setUploading] = useState(false);+ const [showUploadMenu, setShowUploadMenu] = useState(false);+ const uploadMenuRef = useRef<HTMLDivElement>(null);+ const uploadMenuTriggerRef = useRef<HTMLButtonElement>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);++ const focus = useCallback(() => {+ inputRef.current?.focus({ preventScroll: true });+ }, []);++ const submitPrompt = useCallback((prompt: string) => {+ if (!prompt.trim() || streaming) return;+ setInput("");+ if (inputRef.current) inputRef.current.style.height = "auto";+ const submittedAttachment = attachment;+ if (!goalComposerActive) setAttachment(null);+ onSubmit(prompt.trim(), submittedAttachment);+ inputRef.current?.focus();+ }, [attachment, goalComposerActive, onSubmit, streaming]);++ useImperativeHandle(ref, () => ({+ fill(prompt: string) {+ setInput(prompt);+ requestAnimationFrame(() => {+ const composer = inputRef.current;+ if (!composer) return;+ composer.focus({ preventScroll: true });+ composer.style.height = "auto";+ composer.style.height = `${composer.scrollHeight}px`;+ });+ },+ focus,+ submit: submitPrompt,+ }), [focus, submitPrompt]);++ const handleSubmit = useCallback((event: FormEvent) => {+ event.preventDefault();+ submitPrompt(input);+ }, [input, submitPrompt]);++ const handleFileSelect = useCallback(async (event: ChangeEvent<HTMLInputElement>) => {+ const file = event.target.files?.[0];+ if (!file) return;+ event.target.value = "";+ const blockedExts = [+ ".exe", ".msi", ".bat", ".cmd", ".com", ".scr", ".app", ".dmg",+ ".so", ".dll", ".dylib",+ ".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz",+ ];+ const lowered = file.name.toLowerCase();+ if (blockedExts.some((ext) => lowered.endsWith(ext))) {+ toast.error(t("agent.executablesNotAllowed"));+ return;+ }+ if (file.size > 50 * 1024 * 1024) {+ toast.error(t("agent.fileSizeExceeds"));+ return;+ }+ setUploading(true);+ setShowUploadMenu(false);+ try {+ const result = await api.uploadFile(file);+ setAttachment({ filename: result.filename, filePath: result.file_path });+ toast.success(t("agent.uploaded", { filename: result.filename }));+ } catch (error) {+ toast.error(t("agent.uploadFailed", {+ error: error instanceof Error ? error.message : "Unknown error",+ }));+ } finally {+ setUploading(false);+ }+ }, [t]);++ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ if (uploadMenuRef.current && !uploadMenuRef.current.contains(event.target as Node)) {+ setShowUploadMenu(false);+ }+ };+ const handleEscape = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ event.preventDefault();+ setShowUploadMenu(false);+ uploadMenuTriggerRef.current?.focus();+ };+ if (showUploadMenu) {+ document.addEventListener("mousedown", handleClickOutside);+ document.addEventListener("keydown", handleEscape);+ return () => {+ document.removeEventListener("mousedown", handleClickOutside);+ document.removeEventListener("keydown", handleEscape);+ };+ }+ }, [showUploadMenu]);++ return (+ <form onSubmit={handleSubmit} className="space-y-2">+ {swarmPreset && (+ <div className="flex items-center gap-1">+ <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">+ <Users className="h-3 w-3" />+ {swarmPreset.title}+ <button type="button" onClick={onCancelSwarm} className="hover:text-destructive transition-colors">+ <X className="h-3 w-3" />+ </button>+ </span>+ </div>+ )}+ {goalComposerActive && (+ <div className="flex items-center gap-1">+ <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">+ <Target className="h-3 w-3" />+ {t("agent.newResearchGoal")}+ <button type="button" onClick={onCancelGoal} className="hover:text-destructive transition-colors">+ <X className="h-3 w-3" />+ </button>+ </span>+ </div>+ )}+ {panels}+ <LiveRuntimeStatus />+ {attachment && (+ <div className="flex items-center gap-1">+ <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">+ <Paperclip className="h-3 w-3" />+ {attachment.filename}+ <button type="button" onClick={() => setAttachment(null)} className="hover:text-destructive transition-colors">+ <X className="h-3 w-3" />+ </button>+ </span>+ </div>+ )}+ {uploading && (+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin" />+ {t("agent.uploading")}+ </div>+ )}+ <LiveRuntimeControl />+ <div className="flex items-end gap-2 rounded-2xl border border-border/60 bg-background p-1.5 shadow-[0_1px_2px_rgba(0,0,0,0.03),0_8px_24px_-12px_rgba(0,0,0,0.12)] transition-shadow focus-within:ring-2 focus-within:ring-primary/25 dark:bg-card">+ <div className="relative" ref={uploadMenuRef}>+ <button+ ref={uploadMenuTriggerRef}+ type="button"+ onClick={() => setShowUploadMenu((previous) => !previous)}+ disabled={streaming || uploading}+ aria-haspopup="menu"+ aria-expanded={showUploadMenu}+ aria-controls="agent-more-options-menu"+ className="w-10 h-10 rounded-full border flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40 shrink-0"+ title={t("agent.moreOptions")}+ >+ <Plus className="h-4 w-4" />+ </button>+ {showUploadMenu && (+ <div+ id="agent-more-options-menu"+ role="menu"+ className="absolute bottom-full left-0 mb-2 w-52 rounded-xl border bg-background/95 backdrop-blur-sm shadow-lg py-1 z-50"+ >+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ fileInputRef.current?.click();+ setShowUploadMenu(false);+ }}+ className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"+ >+ <Paperclip className="h-4 w-4" />+ {t("agent.uploadPdf")}+ </button>+ <div className="border-t my-1" />+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setShowUploadMenu(false);+ onStartGoal();+ inputRef.current?.focus();+ }}+ className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"+ >+ <Target className="h-4 w-4" />+ {t("agent.researchGoal")}+ </button>+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setShowUploadMenu(false);+ onStartSwarm();+ inputRef.current?.focus();+ }}+ className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"+ >+ <Users className="h-4 w-4" />+ {t("agent.agentSwarm")}+ </button>+ <div className="border-t my-1" />+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setShowUploadMenu(false);+ submitPrompt(CONNECTOR_CHECK_PROMPT);+ }}+ className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"+ >+ <Landmark className="h-4 w-4" />+ {t("agent.checkConnector")}+ </button>+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setShowUploadMenu(false);+ submitPrompt(CONNECTOR_PORTFOLIO_PROMPT);+ }}+ className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"+ >+ <Landmark className="h-4 w-4" />+ {t("agent.analyzePortfolio")}+ </button>+ </div>+ )}+ </div>+ <input+ ref={fileInputRef}+ type="file"+ accept={ACCEPTED_FILE_TYPES}+ onChange={handleFileSelect}+ className="hidden"+ />+ <textarea+ ref={inputRef}+ value={input}+ rows={1}+ onChange={(e) => setInput(e.target.value)}+ onCompositionStart={() => {+ isComposingRef.current = true;+ }}+ onCompositionEnd={() => {+ isComposingRef.current = false;+ lastCompositionEndRef.current = Date.now();+ }}+ onInput={(e) => {+ const el = e.target as HTMLTextAreaElement;+ el.style.height = "auto";+ el.style.height = el.scrollHeight + "px";+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ const nativeEvent = e.nativeEvent as KeyboardEvent & { isComposing?: boolean };+ const justFinishedComposing = Date.now() - lastCompositionEndRef.current < 80;+ if (isComposingRef.current || nativeEvent.isComposing || nativeEvent.keyCode === 229) {+ return;+ }+ if (justFinishedComposing) {+ e.preventDefault();+ return;+ }+ e.preventDefault();+ submitPrompt(input);+ }+ }}+ placeholder={+ streaming+ ? t(`agent.activity.verbs.${activityVerb ?? "working"}` as never)+ : goalComposerActive+ ? t("agent.describeGoal")+ : hasCompletedTurn+ ? t("agent.followUpPlaceholder" as never)+ : t("agent.placeholder")+ }+ aria-label={t("agent.messageInputLabel")}+ aria-readonly={streaming}+ className={[+ "min-h-[52px] flex-1 resize-none overflow-y-auto bg-transparent px-3 py-3 text-sm outline-none max-h-32",+ streaming ? "cursor-not-allowed text-muted-foreground/70" : "",+ ].join(" ")}+ readOnly={streaming}+ />+ {showExport && (+ <button+ type="button"+ onClick={onExport}+ disabled={!canExport}+ className="h-10 px-3 rounded-xl border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 disabled:pointer-events-none"+ title={t("agent.exportChat")}+ >+ <Download className="h-4 w-4" />+ </button>+ )}+ {streaming ? (+ <button+ type="button"+ onClick={onCancel}+ className="h-10 px-4 rounded-xl bg-destructive text-destructive-foreground text-sm font-medium hover:opacity-90 transition-opacity"+ title={t("agent.stopGeneration")}+ >+ <Square className="h-4 w-4" />+ </button>+ ) : (+ <button+ type="submit"+ disabled={goalComposerActive ? !input.trim() : (!input.trim() && !attachment)}+ className="h-10 px-4 rounded-xl bg-primary text-primary-foreground text-sm font-medium disabled:opacity-40 hover:opacity-90 transition-opacity"+ title={t("agent.send")}+ aria-label={t("agent.send")}+ >+ <Send className="h-4 w-4" />+ </button>+ )}+ </div>+ <p className="px-1 text-[11px] text-muted-foreground">{t("agent.inputHint")}</p>+ </form>+ );+}));diff --git a/frontend/src/components/chat/GoalPanel.tsx b/frontend/src/components/chat/GoalPanel.tsxnew file mode 100644index 000000000..0a48613a2--- /dev/null+++ b/frontend/src/components/chat/GoalPanel.tsx@@ -0,0 +1,285 @@+import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Check, ChevronDown, Pencil, Play, Target, X } from "lucide-react";+import { toast } from "sonner";+import { api, type GoalSnapshot } from "@/lib/api";++function isCriterionStatusMet(status: string): boolean {+ return !["", "pending", "open", "unsatisfied"].includes(status.toLowerCase());+}++function criterionEvidenceCount(snapshot: GoalSnapshot, criterionId: string): number {+ return snapshot.evidence.filter((item) => item.criterion_id === criterionId).length;+}++function criterionCovered(snapshot: GoalSnapshot, criterion: GoalSnapshot["criteria"][number]): boolean {+ return isCriterionStatusMet(criterion.status) || criterionEvidenceCount(snapshot, criterion.criterion_id) > 0;+}++function getGoalProgress(snapshot: GoalSnapshot): {+ met: number;+ total: number;+ label: string;+ metLabel: string;+ evidenceTotal: number;+} {+ const total = snapshot.criteria.length;+ const met = snapshot.criteria.filter((item) => criterionCovered(snapshot, item)).length;+ const evidenceTotal = snapshot.evidence_count;+ return {+ met,+ total,+ label: total > 0 ? `${met}/${total}` : "",+ metLabel: total > 0 ? `${met}/${total} met` : "",+ evidenceTotal,+ };+}++function statusLabel(status: string): string {+ return status.replace(/_/g, " ");+}++function criterionIndexLabel(index: number): string {+ return String(index + 1);+}++function latestGoalEvidence(snapshot: GoalSnapshot) {+ return [...snapshot.evidence]+ .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())+ .slice(0, 2);+}++interface Props {+ snapshot: GoalSnapshot;+ sessionId: string | null;+ streaming: boolean;+ openRequest: number;+ onSnapshotChange: (snapshot: GoalSnapshot | null) => void;+ onContinue: () => void;+}++export const GoalPanel = memo(function GoalPanel({+ snapshot,+ sessionId,+ streaming,+ openRequest,+ onSnapshotChange,+ onContinue,+}: Props) {+ const { t } = useTranslation();+ const [detailsOpen, setDetailsOpen] = useState(openRequest > 0);+ const [editActive, setEditActive] = useState(false);+ const [editValue, setEditValue] = useState("");+ const goalProgress = useMemo(() => getGoalProgress(snapshot), [snapshot]);++ useEffect(() => {+ if (openRequest > 0) setDetailsOpen(true);+ }, [openRequest]);++ const handleCancel = useCallback(async () => {+ if (!sessionId) return;+ try {+ await api.updateGoalStatus(sessionId, {+ goal_id: snapshot.goal.goal_id,+ expected_goal_id: snapshot.goal.goal_id,+ status: "cancelled",+ recap: "Cancelled from Web UI.",+ });+ onSnapshotChange(null);+ setDetailsOpen(false);+ toast.success(t("agent.researchGoalCancelled"));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("agent.failedToCancelGoal"));+ }+ }, [onSnapshotChange, sessionId, snapshot, t]);++ const handleStartEdit = useCallback(() => {+ setEditValue(snapshot.goal.objective);+ setEditActive(true);+ }, [snapshot]);++ const handleSaveEdit = useCallback(async () => {+ const objective = editValue.trim();+ if (!sessionId || !objective) return;+ try {+ const response = await api.updateGoal(sessionId, {+ goal_id: snapshot.goal.goal_id,+ expected_goal_id: snapshot.goal.goal_id,+ objective,+ });+ onSnapshotChange(response.snapshot);+ setEditActive(false);+ toast.success(t("agent.researchGoalUpdated"));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("agent.failedToUpdateGoal"));+ }+ }, [editValue, onSnapshotChange, sessionId, snapshot, t]);++ return (+ <div className="grid gap-2">+ <button+ type="button"+ onClick={() => setDetailsOpen((open) => !open)}+ className="inline-flex max-w-full items-center gap-1.5 justify-self-start rounded-lg bg-primary/10 px-2.5 py-1 text-left text-xs font-medium text-primary transition-colors hover:bg-primary/15"+ title={snapshot.goal.objective}+ aria-label={t("agent.activeResearchGoal")}+ aria-expanded={detailsOpen}+ >+ <Target className="h-3 w-3 shrink-0" />+ <span className="shrink-0">{t("agent.goal")}</span>+ <span className="truncate text-muted-foreground">+ {snapshot.goal.ui_summary || snapshot.goal.objective}+ </span>+ {goalProgress.metLabel && (+ <span className="shrink-0 font-mono text-[11px] text-emerald-600 dark:text-emerald-400">+ {goalProgress.metLabel}+ </span>+ )}+ {goalProgress.evidenceTotal > 0 && (+ <span+ className="shrink-0 rounded bg-background px-1 font-mono text-[10px] text-primary"+ title={t("agent.evidenceCollectedTitle")}+ >+ {t("agent.evidenceCount", { count: goalProgress.evidenceTotal })}+ </span>+ )}+ <ChevronDown+ className={[+ "h-3 w-3 shrink-0 transition-transform",+ detailsOpen ? "rotate-180" : "",+ ].join(" ")}+ aria-hidden="true"+ />+ </button>+ {detailsOpen && (+ <div className="grid gap-3 rounded-xl border border-primary/20 bg-background/95 p-3 text-xs shadow-sm">+ {editActive ? (+ <div className="grid gap-2">+ <textarea+ value={editValue}+ onChange={(event) => setEditValue(event.target.value)}+ rows={3}+ aria-label={t("agent.editGoalObjectiveLabel")}+ className="w-full rounded-lg border bg-background px-3 py-2 text-xs leading-relaxed text-foreground outline-none focus:ring-2 focus:ring-primary/30"+ />+ <div className="flex justify-end gap-2">+ <button+ type="button"+ onClick={() => setEditActive(false)}+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground"+ >+ <X className="h-3 w-3" />+ {t("agent.cancel")}+ </button>+ <button+ type="button"+ onClick={handleSaveEdit}+ disabled={!editValue.trim()}+ className="inline-flex items-center gap-1 rounded-lg bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground transition-opacity disabled:opacity-40"+ >+ <Check className="h-3 w-3" />+ {t("agent.save")}+ </button>+ </div>+ </div>+ ) : (+ <div className="rounded-lg border bg-muted/20 px-3 py-2 text-[11px] leading-relaxed text-muted-foreground">+ {snapshot.goal.objective}+ </div>+ )}+ <div className="grid grid-cols-2 gap-2">+ <div className="rounded-lg border bg-muted/20 p-2.5">+ <div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">+ {t("agent.criteria")}+ </div>+ <div className="mt-1 font-mono text-base font-semibold text-foreground">+ {goalProgress.label || "0/0"}+ </div>+ </div>+ <div className="rounded-lg border bg-muted/20 p-2.5">+ <div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">+ {t("agent.evidence")}+ </div>+ <div className="mt-1 font-mono text-base font-semibold text-foreground">+ {goalProgress.evidenceTotal}+ </div>+ </div>+ </div>+ <div className="grid gap-1.5">+ {snapshot.criteria.map((criterion, index) => {+ const evidenceCount = criterionEvidenceCount(snapshot, criterion.criterion_id);+ const displayStatus = criterionCovered(snapshot, criterion) && !isCriterionStatusMet(criterion.status)+ ? "covered"+ : statusLabel(criterion.status);+ return (+ <div+ key={criterion.criterion_id}+ className="grid grid-cols-[1.25rem_minmax(0,1fr)_auto] items-start gap-2 rounded-lg border bg-muted/20 p-2"+ >+ <span className="flex h-5 w-5 items-center justify-center rounded-full bg-muted text-[10px] text-muted-foreground">+ {criterionIndexLabel(index)}+ </span>+ <span className="min-w-0">+ <span className="block truncate font-medium text-foreground">{criterion.text}</span>+ <span className="block text-[11px] text-muted-foreground">+ {displayStatus}+ </span>+ </span>+ <span className="rounded-full border px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">+ {evidenceCount} ev+ </span>+ </div>+ );+ })}+ </div>+ {snapshot.evidence.length > 0 && (+ <div className="grid gap-1.5 border-t pt-2">+ <div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">+ {t("agent.recentEvidence")}+ </div>+ {latestGoalEvidence(snapshot).map((item) => (+ <div key={item.evidence_id} className="rounded-lg bg-muted/20 px-2 py-1.5">+ <div className="mb-0.5 flex items-center justify-between gap-2 text-[10px] text-muted-foreground">+ <span className="truncate">{item.source_provider || "evidence"}</span>+ <span>{statusLabel(item.verification_status)}</span>+ </div>+ <div className="line-clamp-2 text-[11px] leading-relaxed text-foreground">+ {item.text}+ </div>+ </div>+ ))}+ </div>+ )}+ <div className="flex flex-wrap justify-end gap-2 border-t pt-2">+ <button+ type="button"+ onClick={onContinue}+ disabled={streaming}+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"+ >+ <Play className="h-3 w-3" />+ {t("agent.continue")}+ </button>+ <button+ type="button"+ onClick={handleStartEdit}+ disabled={editActive}+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"+ >+ <Pencil className="h-3 w-3" />+ {t("agent.edit")}+ </button>+ <button+ type="button"+ onClick={handleCancel}+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-destructive/40 hover:text-destructive"+ >+ <X className="h-3 w-3" />+ {t("agent.cancelGoal")}+ </button>+ </div>+ </div>+ )}+ </div>+ );+});diff --git a/frontend/src/components/chat/LiveRuntimePanel.tsx b/frontend/src/components/chat/LiveRuntimePanel.tsxnew file mode 100644index 000000000..dea5c85ab--- /dev/null+++ b/frontend/src/components/chat/LiveRuntimePanel.tsx@@ -0,0 +1,282 @@+import {+ createContext,+ forwardRef,+ memo,+ useCallback,+ useContext,+ useEffect,+ useImperativeHandle,+ useMemo,+ useState,+ type ReactNode,+} from "react";+import { useTranslation } from "react-i18next";+import { Activity, Ban, CheckCircle2, Loader2, OctagonX } from "lucide-react";+import { toast } from "sonner";+import {+ ApiError,+ api,+ type LiveAction,+ type LiveHalted,+ type LiveStatus,+} from "@/lib/api";+import { AgentAvatar } from "@/components/chat/AgentAvatar";+import { RunnerStatus } from "@/components/chat/RunnerStatus";++const LIVE_STATUS_POLL_INTERVAL_MS = 15_000;++function normalizeBrokerScope(broker: string | null | undefined): string | null {+ const normalized = broker?.trim().toLowerCase();+ return normalized || null;+}++function isGlobalLiveHalt(halt: LiveHalted | null): boolean {+ return halt != null && normalizeBrokerScope(halt.broker) == null;+}++function haltScopeStillActive(halt: LiveHalted, status: LiveStatus): boolean {+ const broker = normalizeBrokerScope(halt.broker);+ if (!broker) return status.global_halted;+ return status.global_halted || status.brokers.some((item) => (+ normalizeBrokerScope(item.auth.broker) === broker && item.halted+ ));+}++function liveActionStyle(kind: string): { icon: typeof Activity; tone: string } {+ switch (kind) {+ case "order_rejected":+ case "breach":+ return { icon: Ban, tone: "border-amber-500/40 bg-amber-500/5 text-amber-600 dark:text-amber-400" };+ case "halt_tripped":+ return { icon: OctagonX, tone: "border-destructive/40 bg-destructive/5 text-destructive" };+ case "mandate_committed":+ case "halt_cleared":+ return { icon: CheckCircle2, tone: "border-emerald-500/40 bg-emerald-500/5 text-emerald-600 dark:text-emerald-400" };+ default:+ return { icon: Activity, tone: "border-sky-500/40 bg-sky-500/5 text-sky-600 dark:text-sky-400" };+ }+}++function liveActionLabel(action: LiveAction): string {+ return action.kind.replace(/_/g, " ");+}++export const LiveActionChip = memo(function LiveActionChip({ action }: { action: LiveAction }) {+ const { t } = useTranslation();+ const { icon: Icon, tone } = liveActionStyle(action.kind);+ return (+ <div className="flex gap-3">+ <AgentAvatar />+ <div className="flex-1 min-w-0">+ <div className={["inline-flex max-w-full flex-wrap items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs", tone].join(" ")}>+ <Icon className="h-3 w-3 shrink-0" />+ <span className="shrink-0 font-medium uppercase tracking-wide text-[10px]">{t("agent.runtimeBadge")}</span>+ <span className="shrink-0 font-medium">{liveActionLabel(action)}</span>+ {action.intent_normalized && (+ <span className="truncate text-foreground/80">· {action.intent_normalized}</span>+ )}+ {action.outcome && (+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground">· {action.outcome}</span>+ )}+ {action.remote_tool && (+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground">· {action.remote_tool}</span>+ )}+ {action.error && <span className="truncate text-destructive">· {action.error}</span>}+ </div>+ </div>+ </div>+ );+});++export interface LiveRuntimePanelHandle {+ resetSession(): void;+ handleMandateCommitted(): void;+ handleHalted(halted: LiveHalted): void;+ handleResumed(): void;+ handleLiveAction(action: LiveAction): void;+}++interface RuntimeContextValue {+ liveStatus: LiveStatus | null;+ liveStatusUnavailable: boolean;+ liveActive: boolean;+ liveIsHalted: boolean;+ halting: boolean;+ refreshLiveStatus: () => Promise<void>;+ haltLive: () => Promise<void>;+}++const RuntimeContext = createContext<RuntimeContextValue | null>(null);++interface Props {+ sessionId: string | null;+ hasLiveItems: boolean;+ children: ReactNode;+}++export const LiveRuntimePanel = memo(forwardRef<LiveRuntimePanelHandle, Props>(+ function LiveRuntimePanel({ sessionId, hasLiveItems, children }, ref) {+ const { t } = useTranslation();+ const [hasCommittedMandate, setHasCommittedMandate] = useState(false);+ const [liveHalted, setLiveHalted] = useState<LiveHalted | null>(null);+ const [halting, setHalting] = useState(false);+ const [liveStatusRefresh, setLiveStatusRefresh] = useState(0);+ const [liveStatus, setLiveStatus] = useState<LiveStatus | null>(null);+ const [liveStatusUnavailable, setLiveStatusUnavailable] = useState(false);++ const refreshLiveStatus = useCallback(async () => {+ try {+ const next = await api.getLiveStatus();+ setLiveStatus(next);+ setLiveHalted((current) => (+ current && !haltScopeStillActive(current, next) ? null : current+ ));+ setLiveStatusUnavailable(false);+ } catch (error) {+ if (error instanceof ApiError && (error.status === 404 || error.status === 501)) {+ setLiveStatus(null);+ setLiveStatusUnavailable(true);+ }+ }+ }, []);++ useEffect(() => {+ refreshLiveStatus();+ const timer = setInterval(refreshLiveStatus, LIVE_STATUS_POLL_INTERVAL_MS);+ return () => clearInterval(timer);+ }, [refreshLiveStatus]);++ useEffect(() => {+ if (liveStatusRefresh > 0) refreshLiveStatus();+ }, [liveStatusRefresh, refreshLiveStatus]);++ useImperativeHandle(ref, () => ({+ resetSession() {+ setHasCommittedMandate(false);+ setLiveHalted(null);+ setLiveStatusRefresh((value) => value + 1);+ },+ handleMandateCommitted() {+ setHasCommittedMandate(true);+ setLiveStatusRefresh((value) => value + 1);+ },+ handleHalted(halted: LiveHalted) {+ setLiveHalted(halted);+ setLiveStatusRefresh((value) => value + 1);+ },+ handleResumed() {+ setLiveHalted(null);+ setLiveStatusRefresh((value) => value + 1);+ },+ handleLiveAction(action: LiveAction) {+ if (action.kind === "mandate_committed") setHasCommittedMandate(true);+ if (action.kind === "halt_tripped") {+ setLiveHalted({ broker: action.broker, reason: action.intent_normalized });+ }+ if (action.kind === "halt_cleared") setLiveHalted(null);+ if (["mandate_committed", "halt_tripped", "halt_cleared"].includes(action.kind)) {+ setLiveStatusRefresh((value) => value + 1);+ }+ },+ }), []);++ const haltLive = useCallback(async () => {+ if (halting) return;+ setHalting(true);+ try {+ await api.haltLive(sessionId ?? undefined);+ setLiveHalted((current) => current ?? {+ broker: null,+ by: "frontend",+ tripped_at: new Date().toISOString(),+ });+ setLiveStatusRefresh((value) => value + 1);+ toast.success(t("agent.connectorHalted"));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("agent.failedToHaltConnector"));+ } finally {+ setHalting(false);+ }+ }, [halting, sessionId, t]);++ const liveStatusActive =+ liveStatus != null &&+ (liveStatus.global_halted ||+ liveStatus.brokers.some((broker) => (+ broker.auth.oauth_token_present || broker.runner?.alive || broker.mandate != null+ )));+ const liveActive =+ hasLiveItems ||+ hasCommittedMandate ||+ liveHalted != null ||+ liveStatusActive;+ const liveIsHalted =+ isGlobalLiveHalt(liveHalted) || (liveStatus?.global_halted ?? false);++ const value = useMemo<RuntimeContextValue>(() => ({+ liveStatus,+ liveStatusUnavailable,+ liveActive,+ liveIsHalted,+ halting,+ refreshLiveStatus,+ haltLive,+ }), [+ haltLive,+ halting,+ liveActive,+ liveIsHalted,+ liveStatus,+ liveStatusUnavailable,+ refreshLiveStatus,+ ]);++ return (+ <RuntimeContext.Provider value={value}>+ {children}+ </RuntimeContext.Provider>+ );+ },+));++export function LiveRuntimeStatus() {+ const runtime = useContext(RuntimeContext);+ if (!runtime) return null;+ return (+ <RunnerStatus+ status={runtime.liveStatus}+ unavailable={runtime.liveStatusUnavailable}+ halted={runtime.liveIsHalted}+ onRefresh={runtime.refreshLiveStatus}+ />+ );+}++export function LiveRuntimeControl() {+ const { t } = useTranslation();+ const runtime = useContext(RuntimeContext);+ if (!runtime?.liveActive) return null;+ return (+ <div className="flex items-center gap-2 border-t border-border/60 pt-2">+ {runtime.liveIsHalted ? (+ <span className="inline-flex items-center gap-1.5 rounded-lg bg-destructive/10 px-2.5 py-1 text-xs font-medium text-destructive">+ <OctagonX className="h-3 w-3" />+ {t("agent.connectorHalted")}+ </span>+ ) : (+ <button+ type="button"+ onClick={runtime.haltLive}+ disabled={runtime.halting}+ className="inline-flex items-center gap-1.5 rounded-lg border border-destructive/40 bg-destructive/5 px-2.5 py-1 text-xs font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-40"+ title={t("agent.haltConnectorTitle")}+ >+ {runtime.halting+ ? <Loader2 className="h-3 w-3 animate-spin" />+ : <OctagonX className="h-3 w-3" />}+ {t("agent.haltConnector")}+ </button>+ )}+ </div>+ );+}diff --git a/frontend/src/components/chat/MessageBubble.tsx b/frontend/src/components/chat/MessageBubble.tsxindex 1bfb1ec48..417b77b46 100644--- a/frontend/src/components/chat/MessageBubble.tsx+++ b/frontend/src/components/chat/MessageBubble.tsx@@ -34,7 +34,7 @@ const markdownComponents: ReactMarkdownOptions["components"] = {return <a {...props} target="_blank" rel="noopener noreferrer" />;},};-const proseClassName = "prose prose-sm dark:prose-invert max-w-none text-[15px] leading-relaxed prose-table:border prose-table:border-border/50 prose-th:bg-muted/30 prose-th:px-3 prose-th:py-1.5 prose-td:px-3 prose-td:py-1.5 prose-th:text-left prose-th:text-xs prose-th:font-medium prose-td:text-xs prose-hr:hidden";+const proseClassName = "prose prose-sm dark:prose-invert max-w-none text-[15px] leading-relaxed prose-p:font-serif prose-p:text-[15.5px] prose-p:leading-[1.75] prose-li:font-serif prose-li:text-[15.5px] prose-li:leading-[1.75] prose-headings:font-sans prose-table:font-sans prose-code:font-mono prose-blockquote:font-sans [&_blockquote_p]:font-sans prose-table:border prose-table:border-border/50 prose-th:bg-muted/30 prose-th:px-3 prose-th:py-1.5 prose-td:px-3 prose-td:py-1.5 prose-th:text-left prose-th:text-xs prose-th:font-medium prose-td:text-xs prose-hr:hidden";interface MarkdownErrorBoundaryProps {content: string;diff --git a/frontend/src/components/chat/ThinkingTimeline.tsx b/frontend/src/components/chat/ThinkingTimeline.tsxindex e1c0428fb..e632d269d 100644--- a/frontend/src/components/chat/ThinkingTimeline.tsx+++ b/frontend/src/components/chat/ThinkingTimeline.tsx@@ -1,141 +1,84 @@-import { useTranslation } from 'react-i18next';-import { memo, useId, useMemo, useState } from "react";-import { ChevronDown, ChevronRight, CheckCircle2, XCircle, Circle, Loader2 } from "lucide-react";-import { cn } from "@/lib/utils";-import { localizeToolName } from "@/lib/tools";-import type { AgentMessage } from "@/types/agent";+import { memo, useMemo } from "react";+import { ActivityLine } from "@/components/chat/ActivityLine";+import {+ deriveActivityVerb,+ type AgentActivity,+ type StoredAgentMessage,+} from "@/stores/agent";+import type { ToolCallEntry } from "@/types/agent";interface Props {- messages: AgentMessage[];+ messages: StoredAgentMessage[];isLatest?: boolean;+ onContinue?: (activity: AgentActivity) => void;+ onReattach?: (activity: AgentActivity) => void;}-export const ThinkingTimeline = memo(function ThinkingTimeline({ messages, isLatest = false }: Props) {- const { t } = useTranslation();- const [userOpen, setUserOpen] = useState<boolean | null>(null);- const detailsId = useId();- const expanded = userOpen ?? isLatest;- const processingLabel = t('thinking.processing');+function rebuildLegacyActivity(+ messages: StoredAgentMessage[],+ isLatest: boolean,+): AgentActivity {+ const steps: ToolCallEntry[] = [];- const { steps, hasError, isRunning, totalMs, latestTool, latestThinking } = useMemo(() => {- let totalMs = 0;- let latestTool = "";- let latestThinking = "";- // Merge tool_call + tool_result pairs into "steps"- const steps: Array<{ tool: string; label: string; status: "running" | "ok" | "error"; elapsed_ms?: number }> = [];-- for (const m of messages) {- if (m.type === "thinking" && m.content) latestThinking = m.content;- if (m.type === "tool_call") {- steps.push({ tool: m.tool || "", label: m.tool ? localizeToolName(m.tool) : processingLabel, status: m.status === "running" ? "running" : "ok", elapsed_ms: undefined });- if (m.status === "running") latestTool = m.tool || "";- }- if (m.type === "tool_result") {- const existing = [...steps].reverse().find(s => s.tool === m.tool);- if (existing) {- existing.status = m.status === "ok" ? "ok" : "error";- existing.elapsed_ms = m.elapsed_ms;- }- if (m.elapsed_ms) totalMs += m.elapsed_ms;- }+ for (const message of messages) {+ if (message.type === "tool_call") {+ steps.push({+ id: message.id,+ tool: message.tool || "",+ arguments: message.args ?? {},+ status: message.status === "running" ? "running" : "ok",+ timestamp: message.timestamp,+ });+ continue;+ }+ if (message.type !== "tool_result") continue;+ const existing = [...steps].reverse().find((step) => (+ step.tool === message.tool && step.status === "running"+ )) ?? [...steps].reverse().find((step) => step.tool === message.tool);+ if (existing) {+ existing.status = message.status === "error" ? "error" : "ok";+ existing.elapsed_ms = message.elapsed_ms;+ existing.preview = message.content;}+ }- return {- steps,- hasError: steps.some(s => s.status === "error"),- isRunning: steps.some(s => s.status === "running"),- totalMs,- latestTool,- latestThinking,- };- }, [messages, processingLabel]);+ const startedAt = messages[0]?.timestamp ?? Date.now();+ const isRunning = isLatest || steps.some((step) => step.status === "running");+ return {+ attemptId: messages[0]?.id || `legacy-${startedAt}`,+ state: isRunning ? (steps.length > 0 ? "working" : "thinking") : "done",+ verb: deriveActivityVerb(steps[steps.length - 1]?.tool),+ steps,+ startedAt,+ endedAt: isRunning+ ? undefined+ : startedAt + steps.reduce((sum, step) => sum + (step.elapsed_ms ?? 0), 0),+ };+}- const stepCount = steps.length;- const summaryText = isRunning- ? `${t('thinking.running')} ${latestTool ? localizeToolName(latestTool) : processingLabel}...`- : `${t('thinking.done')} · ${t('thinking.steps', { count: stepCount })}${totalMs > 0 ? ` · ${(totalMs / 1000).toFixed(1)}s` : ""}`;+/**+ * Compatibility adapter for transcript groups.+ *+ * New turns carry one durable activity object; older tool_call/tool_result+ * groups are reconstructed once and handed to the same ActivityLine renderer.+ */+export const ThinkingTimeline = memo(function ThinkingTimeline({+ messages,+ isLatest = false,+ onContinue,+ onReattach,+}: Props) {+ const activity = useMemo(+ () => messages.find((message) => message.meta?.activity)?.meta?.activity+ ?? rebuildLegacyActivity(messages, isLatest),+ [isLatest, messages],+ );return (- <div className="rounded-lg border border-border/40 bg-muted/5 overflow-hidden">- {/* Summary bar */}- <button- aria-controls={detailsId}- aria-expanded={expanded}- onClick={() => setUserOpen(!expanded)}- className="w-full min-w-0 flex items-center gap-2 px-3 py-2 text-xs hover:bg-muted/10 transition-colors"- >- {expanded- ? <ChevronDown className="h-3 w-3 text-muted-foreground shrink-0" />- : <ChevronRight className="h-3 w-3 text-muted-foreground shrink-0" />}- {isRunning ? (- <Loader2 className="h-3 w-3 text-primary animate-spin shrink-0" />- ) : hasError ? (- <XCircle className="h-3 w-3 text-danger shrink-0" />- ) : (- <CheckCircle2 className="h-3 w-3 text-success/70 shrink-0" />- )}- <span className={cn("min-w-0 flex-1 truncate text-start text-muted-foreground", isRunning && "text-foreground")}>- {summaryText}- </span>- </button>-- {/* Thinking preview when running but collapsed */}- {!expanded && isRunning && latestThinking && (- <div className="px-3 pb-2 -mt-1">- <p className="text-[11px] text-muted-foreground/40 line-clamp-1 pl-5 italic">- {latestThinking.slice(-100)}- </p>- </div>- )}-- <div id={detailsId} hidden={!expanded}>- {/* Expanded step list */}- {expanded && steps.length > 0 && (- <div className="border-t border-border/30 px-3 py-1.5 space-y-0.5">- {steps.map((step, i) => (- <div key={`${step.tool}-${i}`} className="flex items-center gap-2 py-1 text-xs">- {/* Tree connector */}- <span className="text-border/60 shrink-0 w-3 text-center">- {i < steps.length - 1 ? "├" : "└"}- </span>-- {/* Status icon */}- {step.status === "running" ? (- <Loader2 className="h-3 w-3 text-primary animate-spin shrink-0" />- ) : step.status === "error" ? (- <XCircle className="h-3 w-3 text-danger shrink-0" />- ) : (- <Circle className="h-3 w-3 text-success/50 shrink-0" fill="currentColor" />- )}-- {/* Label */}- <span className={cn(- "flex-1",- step.status === "running" ? "text-foreground" : "text-muted-foreground/60"- )}>- {step.label}- </span>-- {/* Duration or status */}- {step.status === "running" ? (- <span className="text-[10px] text-primary/60">{t('thinking.running')}</span>- ) : step.elapsed_ms != null ? (- <span className="text-[10px] text-muted-foreground/40 tabular-nums">{(step.elapsed_ms / 1000).toFixed(1)}s</span>- ) : null}- </div>- ))}- </div>- )}-- {/* Expanded: show thinking content if any (for Q&A without tools) */}- {expanded && steps.length === 0 && latestThinking && (- <div className="border-t border-border/30 px-3 py-2">- <p className="text-xs text-muted-foreground/50 leading-relaxed line-clamp-4">- {latestThinking}- </p>- </div>- )}- </div>- </div>+ <ActivityLine+ activity={activity}+ onContinue={onContinue ? () => onContinue(activity) : undefined}+ onReattach={onReattach ? () => onReattach(activity) : undefined}+ />);});diff --git a/frontend/src/components/chat/ToolProgressIndicator.tsx b/frontend/src/components/chat/ToolProgressIndicator.tsxindex 4145da307..372dec264 100644--- a/frontend/src/components/chat/ToolProgressIndicator.tsx+++ b/frontend/src/components/chat/ToolProgressIndicator.tsx@@ -1,7 +1,6 @@-import { memo, useEffect, useMemo, useRef, useState, type JSX } from "react";+import { memo, useEffect, useMemo, useRef, type JSX } from "react";import { useTranslation } from "react-i18next";import { Loader2, CheckCircle2, XCircle } from "lucide-react";-import { cn } from "@/lib/utils";import { ProgressBar } from "@/components/chat/ProgressBar";import { localizeToolName } from "@/lib/tools";import type { ToolCallEntry } from "@/types/agent";@@ -36,6 +35,12 @@ function calculateEta(tc: ToolCallEntry, previous?: EtaSample): number | null {return Math.round(eta);}+function formatStepElapsed(seconds: number): string {+ const wholeSeconds = Math.max(0, Math.floor(seconds));+ if (wholeSeconds < 60) return `${wholeSeconds}s`;+ return `${Math.floor(wholeSeconds / 60)}m ${wholeSeconds % 60}s`;+}+/* ---------- Determinate progress ring ---------- */interface RingProps {current: number;@@ -92,6 +97,9 @@ function ToolRow({ entry, stepIndex, connector = "none", eta }: RowProps): JSX.Econst hasDeterminate = !!(progress && typeof progress.current === "number" && typeof progress.total === "number" && progress.total > 0);const stage = progress?.stage || "";const message = progress?.message || "";+ const elapsedSeconds = entry.elapsed_s ?? (+ entry.elapsed_ms != null ? entry.elapsed_ms / 1000 : undefined+ );const icon = entry.status === "error"? <XCircle className="h-3 w-3 text-danger shrink-0" />@@ -115,12 +123,12 @@ function ToolRow({ entry, stepIndex, connector = "none", eta }: RowProps): JSX.E)}{icon}<span className="text-foreground truncate">{stepLabel}</span>- {entry.elapsed_s != null && (+ {elapsedSeconds != null && (<spanaria-hidden="true"className="ml-auto sm:ml-0 tabular-nums text-[10px] text-muted-foreground/70 shrink-0">- {entry.elapsed_s.toFixed(0)}s+ {formatStepElapsed(elapsedSeconds)}</span>)}</div>@@ -161,53 +169,46 @@ function ToolRow({ entry, stepIndex, connector = "none", eta }: RowProps): JSX.E}/* ---------- Public component ---------- */-interface Props {- /** Full toolCalls slice from the store for the current attempt. */+export interface ToolProgressIndicatorProps {+ /** Full step list from the durable activity object. */toolCalls: ToolCallEntry[];}-const MAX_VISIBLE = 3;-const COLLAPSED_ROW_COUNT = MAX_VISIBLE - 1;-interface IndexedToolCall {entry: ToolCallEntry;index: number;}+/**+ * Expanded activity step rows.+ *+ * ActivityLine owns status, disclosure and announcements; this component is+ * deliberately only the shared row renderer so the chat has one status surface.+ */export const ToolProgressIndicator = memo(function ToolProgressIndicator({toolCalls,-}: Props): JSX.Element | null {- const { t } = useTranslation();- const [showEarlier, setShowEarlier] = useState(false);+}: ToolProgressIndicatorProps): JSX.Element | null {const etaSamplesRef = useRef<Map<string, EtaSample>>(new Map());- const { indexedRows, running, anyError, collapsedRows } = useMemo(() => {- const indexedRows: IndexedToolCall[] = [];+ const { rows, running } = useMemo(() => {const runningRows: IndexedToolCall[] = [];const terminalRows: IndexedToolCall[] = [];const running: ToolCallEntry[] = [];- let anyError = false;toolCalls.forEach((entry, index) => {const indexed = { entry, index };- indexedRows.push(indexed);if (entry.status === "running") {running.push(entry);runningRows.push(indexed);} else {terminalRows.push(indexed);}- if (entry.status === "error") anyError = true;});- const collapsedRows = toolCalls.length <= MAX_VISIBLE- ? indexedRows- : [- ...runningRows.slice(-COLLAPSED_ROW_COUNT),- ...terminalRows.reverse(),- ].slice(0, COLLAPSED_ROW_COUNT);-- return { indexedRows, running, anyError, collapsedRows };+ return {+ running,+ rows: [...runningRows, ...terminalRows.reverse()],+ };}, [toolCalls]);const etaById = useMemo(() => {@@ -244,75 +245,17 @@ export const ToolProgressIndicator = memo(function ToolProgressIndicator({if (toolCalls.length === 0) return null;- const totalSoFar = toolCalls.length;- const rows = showEarlier ? indexedRows : collapsedRows;- const overflow = showEarlier ? 0 : toolCalls.length - rows.length;- const coarseStatus = running.length > 0- ? t("toolProgress.toolsRunning" as never, { count: running.length })- : t("toolProgress.toolsCompleted" as never, { count: toolCalls.length });-- /* ---------- aggregate icon state for the header row ---------- */- const aggregateIcon = anyError- ? <XCircle className="h-3 w-3 text-danger shrink-0" />- : running.length > 0- ? <Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />- : <CheckCircle2 className="h-3 w-3 text-success shrink-0" />;-- /* ---------- render ---------- */- if (toolCalls.length === 1) {- const only = toolCalls[0];- return (- <div className="min-w-0">- <span className="sr-only" role="status" aria-live="polite">- {coarseStatus}- </span>+ return (+ <div className="min-w-0 space-y-1">+ {rows.map(({ entry, index }, rowIndex) => (<ToolRow- entry={only}- stepIndex={totalSoFar}- eta={etaById.get(only.id) ?? null}+ key={entry.id}+ entry={entry}+ stepIndex={index + 1}+ connector={rowIndex === rows.length - 1 ? "end" : "branch"}+ eta={etaById.get(entry.id) ?? null}/>- </div>- );- }-- // 2+ calls — header + indented rows.- return (- <div className={cn("min-w-0 space-y-1")}>- <span className="sr-only" role="status" aria-live="polite">- {coarseStatus}- </span>- {/* Header row */}- <div- aria-hidden="true"- className="flex items-center gap-2 text-xs text-muted-foreground"- >- {aggregateIcon}- <span className="text-foreground">{coarseStatus}</span>- </div>- {/* Indented rows */}- <div className="pl-4 space-y-1">- {rows.map(({ entry, index }, i) => (- <ToolRow- key={entry.id}- entry={entry}- stepIndex={index + 1}- connector={i === rows.length - 1 && overflow === 0 ? "end" : "branch"}- eta={etaById.get(entry.id) ?? null}- />- ))}- {overflow > 0 && (- <div className="flex items-center gap-2 text-[10px] text-muted-foreground/60">- <span className="text-border/60 shrink-0 w-3 text-center" aria-hidden="true">└</span>- <button- type="button"- className="rounded-sm hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- onClick={() => setShowEarlier(true)}- >- {t("toolProgress.earlier" as never, { count: overflow })}- </button>- </div>- )}- </div>+ ))}</div>);});diff --git a/frontend/src/components/chat/__tests__/ActivityLine.test.tsx b/frontend/src/components/chat/__tests__/ActivityLine.test.tsxnew file mode 100644index 000000000..1ff803ad5--- /dev/null+++ b/frontend/src/components/chat/__tests__/ActivityLine.test.tsx@@ -0,0 +1,146 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { ActivityLine, formatActivityElapsed } from "../ActivityLine";+import type { AgentActivity } from "@/stores/agent";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, values?: Record<string, string | number>) => {+ const labels: Record<string, string> = {+ "agent.activity.verbs.working": "Working",+ "agent.activity.verbs.readingMarketData": "Reading the market data",+ "agent.activity.verbs.writingStrategy": "Writing the strategy",+ "agent.activity.verbs.runningBacktest": "Running the backtest",+ "agent.activity.verbs.validatingNumbers": "Double-checking the numbers",+ "agent.activity.done": "Done",+ "agent.activity.failed": "Failed",+ "agent.activity.stopped": "Stopped by you",+ "agent.activity.continue": "Continue",+ "agent.activity.reattach": "Re-attach",+ };+ if (key === "agent.activity.steps") return `${values?.count} steps`;+ if (key === "agent.activity.timeout") {+ return `Stopped waiting after ${values?.elapsed} — the run may still be finishing`;+ }+ if (key === "toolProgress.step") return `Step ${values?.step} · ${values?.tool}`;+ return labels[key] ?? key;+ },+ }),+}));++function makeActivity(overrides: Partial<AgentActivity> = {}): AgentActivity {+ return {+ attemptId: "attempt-1",+ state: "working",+ verb: "runningBacktest",+ steps: [{+ id: "tool-1",+ tool: "backtest",+ arguments: {},+ status: "running",+ timestamp: 5000,+ }],+ startedAt: 5000,+ ...overrides,+ };+}++describe("ActivityLine", () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("renders the compact verb, newest step, timer and count", () => {+ vi.spyOn(Date, "now").mockReturnValue(10_000);+ render(<ActivityLine activity={makeActivity()} />);++ expect(screen.getByText(+ "Running the backtest · Run the backtest · 5s · 1 steps",+ )).toBeInTheDocument();+ });++ it("ticks only while the page is visible and freezes at endedAt", () => {+ vi.useFakeTimers();+ vi.setSystemTime(10_000);+ const hidden = vi.spyOn(document, "hidden", "get").mockReturnValue(false);+ const { rerender } = render(<ActivityLine activity={makeActivity()} />);++ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(screen.getByText(/6s/)).toBeInTheDocument();++ hidden.mockReturnValue(true);+ act(() => document.dispatchEvent(new Event("visibilitychange")));+ act(() => {+ vi.setSystemTime(20_000);+ vi.advanceTimersByTime(9000);+ });+ expect(screen.getByText(/6s/)).toBeInTheDocument();++ rerender(<ActivityLine activity={makeActivity({+ state: "done",+ endedAt: 12_000,+ })} />);+ expect(screen.getByText("Done · 1 steps · 7s")).toBeInTheDocument();+ });++ it("auto-collapses 900ms after a terminal state", () => {+ vi.useFakeTimers();+ render(<ActivityLine activity={makeActivity({+ state: "done",+ endedAt: 6000,+ })} />);++ const disclosure = screen.getByRole("button");+ expect(disclosure).toHaveAttribute("aria-expanded", "true");+ act(() => vi.advanceTimersByTime(900));+ expect(disclosure).toHaveAttribute("aria-expanded", "false");+ });++ it("respects an explicit user disclosure choice across state changes", () => {+ vi.useFakeTimers();+ const { rerender } = render(<ActivityLine activity={makeActivity()} />);+ const disclosure = screen.getByRole("button");+ fireEvent.click(disclosure);+ expect(disclosure).toHaveAttribute("aria-expanded", "false");++ rerender(<ActivityLine activity={makeActivity({+ state: "done",+ endedAt: 6000,+ })} />);+ act(() => vi.advanceTimersByTime(900));+ expect(disclosure).toHaveAttribute("aria-expanded", "false");+ });++ it("renders stopped and timeout terminal affordances", () => {+ const onContinue = vi.fn();+ const onReattach = vi.fn();+ const { rerender } = render(+ <ActivityLine+ activity={makeActivity({ state: "stopped", endedAt: 8000 })}+ onContinue={onContinue}+ />,+ );+ expect(screen.getByText("Stopped by you · 1 steps · 3s")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ expect(onContinue).toHaveBeenCalledOnce();++ rerender(+ <ActivityLine+ activity={makeActivity({ state: "timeout", endedAt: 10_000 })}+ onReattach={onReattach}+ />,+ );+ expect(screen.getByText(+ "Stopped waiting after 5s — the run may still be finishing · 1 steps",+ )).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Re-attach" }));+ expect(onReattach).toHaveBeenCalledOnce();+ });++ it("uses one elapsed format for seconds and minutes", () => {+ expect(formatActivityElapsed(59_999)).toBe("59s");+ expect(formatActivityElapsed(65_000)).toBe("1m 5s");+ });+});diff --git a/frontend/src/components/chat/__tests__/Composer.test.tsx b/frontend/src/components/chat/__tests__/Composer.test.tsxnew file mode 100644index 000000000..4a247017c--- /dev/null+++ b/frontend/src/components/chat/__tests__/Composer.test.tsx@@ -0,0 +1,77 @@+import { memo } from "react";+import { fireEvent, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import i18n from "../../../i18n";+import { Composer } from "../Composer";++const baseProps = {+ streaming: false,+ hasCompletedTurn: false,+ showExport: false,+ canExport: false,+ goalComposerActive: false,+ swarmPreset: null,+ onSubmit: vi.fn(),+ onCancel: vi.fn(),+ onExport: vi.fn(),+ onStartGoal: vi.fn(),+ onCancelGoal: vi.fn(),+ onStartSwarm: vi.fn(),+ onCancelSwarm: vi.fn(),+};++describe("Composer", () => {+ beforeAll(async () => {+ await i18n.changeLanguage("en");+ });++ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("does not submit Enter during composition or immediately after compositionend", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 6, 30, 12));+ render(<Composer {...baseProps} />);+ const textarea = screen.getByRole("textbox");++ fireEvent.change(textarea, { target: { value: "你好" } });+ fireEvent.compositionStart(textarea);+ fireEvent.keyDown(textarea, { key: "Enter", code: "Enter" });+ expect(baseProps.onSubmit).not.toHaveBeenCalled();++ fireEvent.compositionEnd(textarea);+ fireEvent.keyDown(textarea, { key: "Enter", code: "Enter" });+ expect(baseProps.onSubmit).not.toHaveBeenCalled();++ vi.advanceTimersByTime(81);+ fireEvent.keyDown(textarea, { key: "Enter", code: "Enter" });+ expect(baseProps.onSubmit).toHaveBeenCalledTimes(1);+ expect(baseProps.onSubmit).toHaveBeenCalledWith("你好", null);+ });++ it("keeps composer keystrokes inside the composer render boundary", async () => {+ let messageListRenderCount = 0;+ const MessageListProbe = memo(function MessageListProbe() {+ messageListRenderCount += 1;+ return <div>message list</div>;+ });+ const user = userEvent.setup();++ render(+ <>+ <MessageListProbe />+ <Composer {...baseProps} />+ </>,+ );+ expect(messageListRenderCount).toBe(1);++ await user.type(screen.getByRole("textbox"), "local composer state");++ expect(messageListRenderCount).toBe(1);+ });+});diff --git a/frontend/src/components/chat/__tests__/ThinkingTimeline.test.tsx b/frontend/src/components/chat/__tests__/ThinkingTimeline.test.tsxindex 19845b2fe..68b197023 100644--- a/frontend/src/components/chat/__tests__/ThinkingTimeline.test.tsx+++ b/frontend/src/components/chat/__tests__/ThinkingTimeline.test.tsx@@ -1,150 +1,183 @@-import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";+import { act, fireEvent, render, screen } from "@testing-library/react";import { ThinkingTimeline } from "../ThinkingTimeline";-import type { AgentMessage } from "@/types/agent";--function makeMsg(overrides: Partial<AgentMessage> = {}): AgentMessage {+import type { AgentActivity, StoredAgentMessage } from "@/stores/agent";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, values?: Record<string, string | number>) => {+ const labels: Record<string, string> = {+ "agent.activity.verbs.working": "Working",+ "agent.activity.verbs.readingMarketData": "Reading the market data",+ "agent.activity.verbs.writingStrategy": "Writing the strategy",+ "agent.activity.verbs.runningBacktest": "Running the backtest",+ "agent.activity.verbs.validatingNumbers": "Double-checking the numbers",+ "agent.activity.done": "Done",+ "agent.activity.failed": "Failed",+ "agent.activity.stopped": "Stopped by you",+ };+ if (key === "agent.activity.steps") return `${values?.count} steps`;+ if (key === "agent.activity.timeout") return `Stopped waiting after ${values?.elapsed}`;+ if (key === "toolProgress.step") return `Step ${values?.step} · ${values?.tool}`;+ return labels[key] ?? key;+ },+ }),+}));++function makeMsg(overrides: Partial<StoredAgentMessage> = {}): StoredAgentMessage {return {id: "msg-1",type: "tool_call",content: "",tool: "bash",status: "running",- timestamp: Date.now(),+ timestamp: 1000,...overrides,};}+function activityMessage(activity: AgentActivity): StoredAgentMessage {+ return makeMsg({+ id: `activity-${activity.attemptId}`,+ type: "thinking",+ meta: { activity },+ timestamp: activity.startedAt,+ });+}+describe("ThinkingTimeline", () => {- it("shows summary text when done", () => {- const msgs: AgentMessage[] = [+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("rebuilds a legacy completed group through ActivityLine", () => {+ render(<ThinkingTimeline messages={[makeMsg({ type: "tool_call", tool: "backtest", status: "ok" }),makeMsg({+ id: "result",type: "tool_result",tool: "backtest",status: "ok",elapsed_ms: 3200,content: "done",}),- ];+ ]} />);- render(<ThinkingTimeline messages={msgs} />);- expect(screen.getByText(/Done · 1 steps/)).toBeInTheDocument();- expect(screen.getByText(/3\.2s/)).toBeInTheDocument();+ expect(screen.getByText(/Done · 1 steps · 3s/)).toBeInTheDocument();});- it("shows running state with spinner", () => {- const msgs: AgentMessage[] = [- makeMsg({ type: "tool_call", tool: "backtest", status: "running" }),- ];+ it("shows the latest legacy group as active", () => {+ vi.spyOn(Date, "now").mockReturnValue(2000);+ render(<ThinkingTimeline messages={[+ makeMsg({ tool: "backtest", status: "running" }),+ ]} isLatest />);- render(<ThinkingTimeline messages={msgs} isLatest />);- expect(screen.getByText(/Running Run the backtest/)).toBeInTheDocument();+ expect(screen.getByText(/Running the backtest · Run the backtest/)).toBeInTheDocument();});- it("expands and collapses on click", async () => {- const user = userEvent.setup();- const msgs: AgentMessage[] = [- makeMsg({ type: "tool_call", tool: "bash", status: "ok" }),- makeMsg({ type: "tool_result", tool: "bash", status: "ok", elapsed_ms: 100, content: "output" }),- ];-- render(<ThinkingTimeline messages={msgs} />);-- // Initially collapsed- expect(screen.queryByText("Run command")).not.toBeInTheDocument();-- // Click to expand- await user.click(screen.getByRole("button"));+ it("auto-collapses a completed activity after 900ms", () => {+ vi.useFakeTimers();+ render(<ThinkingTimeline messages={[+ activityMessage({+ attemptId: "done-1",+ state: "done",+ verb: "working",+ steps: [{+ id: "tool-1",+ tool: "bash",+ arguments: {},+ status: "ok",+ timestamp: 1000,+ }],+ startedAt: 1000,+ endedAt: 2000,+ }),+ ]} />);- // Now expanded — should show step labels- expect(screen.getByText("Run command")).toBeVisible();+ const disclosure = screen.getByRole("button");+ expect(disclosure).toHaveAttribute("aria-expanded", "true");+ act(() => vi.advanceTimersByTime(900));+ expect(disclosure).toHaveAttribute("aria-expanded", "false");});- it("shows error icon when a step failed", () => {- const msgs: AgentMessage[] = [+ it("expands a historical activity on demand", () => {+ vi.useFakeTimers();+ render(<ThinkingTimeline messages={[makeMsg({ type: "tool_call", tool: "bash", status: "ok" }),- makeMsg({ type: "tool_result", tool: "bash", status: "error", content: "err" }),- ];-- render(<ThinkingTimeline messages={msgs} isLatest />);- // Error state should be visible in summary- expect(screen.getByText(/Done · 1 steps/)).toBeInTheDocument();- });-- it("shows thinking content when expanded with no tools", async () => {- const user = userEvent.setup();- const msgs: AgentMessage[] = [- makeMsg({ type: "thinking", content: "Let me analyze this strategy carefully." }),- ];-- render(<ThinkingTimeline messages={msgs} />);+ makeMsg({ id: "result", type: "tool_result", tool: "bash", status: "ok", elapsed_ms: 100 }),+ ]} />);+ act(() => vi.advanceTimersByTime(900));- await user.click(screen.getByRole("button"));- expect(screen.getByText("Let me analyze this strategy carefully.")).toBeInTheDocument();+ const disclosure = screen.getByRole("button");+ fireEvent.click(disclosure);+ expect(disclosure).toHaveAttribute("aria-expanded", "true");+ expect(screen.getByText(/Run command/)).toBeVisible();});- it("starts expanded when isLatest is true", () => {- const msgs: AgentMessage[] = [- makeMsg({ type: "tool_call", tool: "write_file", status: "ok" }),- makeMsg({ type: "tool_result", tool: "write_file", status: "ok", content: "ok" }),- ];+ it("renders the durable failed state instead of inferring from row icons", () => {+ render(<ThinkingTimeline messages={[+ activityMessage({+ attemptId: "failed-1",+ state: "failed",+ verb: "readingMarketData",+ steps: [],+ startedAt: 1000,+ endedAt: 2500,+ }),+ ]} />);- render(<ThinkingTimeline messages={msgs} isLatest />);- // Should be expanded immediately — "Generate code" label visible- expect(screen.getByText("Generate code")).toBeInTheDocument();+ expect(screen.getByText("Failed · 0 steps · 1s")).toBeInTheDocument();});- it("handles multiple tool steps", async () => {- const user = userEvent.setup();- const msgs: AgentMessage[] = [- makeMsg({ type: "tool_call", tool: "bash", status: "ok" }),- makeMsg({ type: "tool_result", tool: "bash", status: "ok", elapsed_ms: 500, content: "ok" }),- makeMsg({ type: "tool_call", tool: "write_file", status: "ok" }),- makeMsg({ type: "tool_result", tool: "write_file", status: "ok", elapsed_ms: 200, content: "ok" }),- makeMsg({ type: "tool_call", tool: "backtest", status: "ok" }),- makeMsg({ type: "tool_result", tool: "backtest", status: "ok", elapsed_ms: 5000, content: "ok" }),- ];-- render(<ThinkingTimeline messages={msgs} />);- expect(screen.getByText(/Done · 3 steps/)).toBeInTheDocument();- expect(screen.getByText(/5\.7s/)).toBeInTheDocument();+ it("keeps zero-tool turns as an activity row", () => {+ render(<ThinkingTimeline messages={[+ activityMessage({+ attemptId: "empty-1",+ state: "done",+ verb: "working",+ steps: [],+ startedAt: 1000,+ endedAt: 1000,+ }),+ ]} />);- await user.click(screen.getByRole("button"));- expect(screen.getByText("Run command")).toBeInTheDocument();- expect(screen.getByText("Generate code")).toBeInTheDocument();- expect(screen.getByText("Run the backtest")).toBeInTheDocument();+ expect(screen.getByText("Done · 0 steps · 0s")).toBeInTheDocument();});- it("exposes disclosure semantics and preserves an explicit user expansion", async () => {- const user = userEvent.setup();- const msgs: AgentMessage[] = [- makeMsg({ type: "tool_call", tool: "bash", status: "ok" }),- makeMsg({ type: "tool_result", tool: "bash", status: "ok", content: "ok" }),- ];- const { rerender } = render(<ThinkingTimeline messages={msgs} />);-- const button = screen.getByRole("button");- const detailsId = button.getAttribute("aria-controls");- expect(button).toHaveAttribute("aria-expanded", "false");- expect(detailsId).toBeTruthy();- expect(document.getElementById(detailsId!)).not.toBeVisible();-- await user.click(button);- expect(button).toHaveAttribute("aria-expanded", "true");- expect(document.getElementById(detailsId!)).toBeVisible();-- rerender(<ThinkingTimeline messages={msgs} isLatest />);- rerender(<ThinkingTimeline messages={msgs} isLatest={false} />);- expect(button).toHaveAttribute("aria-expanded", "true");- expect(document.getElementById(detailsId!)).toBeVisible();+ it("delegates Continue for stopped turns", () => {+ const onContinue = vi.fn();+ const stopped: AgentActivity = {+ attemptId: "stopped-1",+ state: "stopped",+ verb: "working",+ steps: [],+ startedAt: 1000,+ endedAt: 4000,+ };+ render(+ <ThinkingTimeline+ messages={[activityMessage(stopped)]}+ onContinue={onContinue}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: "agent.activity.continue" }));+ expect(onContinue).toHaveBeenCalledWith(stopped);});- it("truncates long summary text within the disclosure row", () => {+ it("exposes polite, non-atomic status semantics", () => {render(<ThinkingTimeline messages={[- makeMsg({ type: "tool_call", tool: "unusually_long_tool_name", status: "running" }),+ activityMessage({+ attemptId: "done-a11y",+ state: "done",+ verb: "working",+ steps: [],+ startedAt: 1000,+ endedAt: 1000,+ }),]} />);- expect(screen.getByText(/Running Unusually long tool name/)).toHaveClass("truncate");+ expect(screen.getByRole("status")).toHaveAttribute("aria-live", "polite");+ expect(screen.getByRole("status")).toHaveAttribute("aria-atomic", "false");});});diff --git a/frontend/src/components/chat/__tests__/ToolProgressIndicator.test.tsx b/frontend/src/components/chat/__tests__/ToolProgressIndicator.test.tsxindex 4ee9e5fe2..33fdf1729 100644--- a/frontend/src/components/chat/__tests__/ToolProgressIndicator.test.tsx+++ b/frontend/src/components/chat/__tests__/ToolProgressIndicator.test.tsx@@ -1,5 +1,4 @@import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";import { ToolProgressIndicator } from "../ToolProgressIndicator";import type { ToolCallEntry } from "@/types/agent";@@ -31,7 +30,6 @@ describe("ToolProgressIndicator", () => {it("keeps completed tools visible for the remainder of the attempt", () => {const tcs = [makeTc({ status: "ok" }), makeTc({ id: "tc-2", status: "error" })];render(<ToolProgressIndicator toolCalls={tcs} />);- expect(screen.getAllByText("2 tools completed")).toHaveLength(2);expect(screen.getAllByText(/Run the backtest/)).toHaveLength(2);});@@ -43,18 +41,26 @@ describe("ToolProgressIndicator", () => {it("renders single running tool", () => {const tcs = [makeTc({ elapsed_s: 5 })];render(<ToolProgressIndicator toolCalls={tcs} />);- expect(screen.getByRole("status")).toBeInTheDocument();+ expect(screen.queryByRole("status")).not.toBeInTheDocument();expect(screen.getByText(/Run the backtest/)).toBeInTheDocument();expect(screen.getByText("5s")).toBeInTheDocument();});- it("renders multiple running tools with header", () => {+ it("uses the shared elapsed format for persisted completed steps", () => {+ render(<ToolProgressIndicator toolCalls={[+ makeTc({ status: "ok", elapsed_s: undefined, elapsed_ms: 65_000 }),+ ]} />);++ expect(screen.getByText("1m 5s")).toHaveAttribute("aria-hidden", "true");+ });++ it("renders multiple running tools without a second status header", () => {const tcs = [makeTc({ id: "tc-1", tool: "bash" }),makeTc({ id: "tc-2", tool: "write_file" }),];render(<ToolProgressIndicator toolCalls={tcs} />);- expect(screen.getAllByText("2 tools running")).toHaveLength(2);+ expect(screen.queryByText("2 tools running")).not.toBeInTheDocument();expect(screen.getByText(/Run command/)).toBeInTheDocument();expect(screen.getByText(/Generate code/)).toBeInTheDocument();});@@ -68,8 +74,7 @@ describe("ToolProgressIndicator", () => {expect(screen.getAllByText(/Run the backtest/)).toHaveLength(2);});- it("shows the most recent running tools behind a clickable earlier count", async () => {- const user = userEvent.setup();+ it("shows every row when ActivityLine is expanded", () => {const tcs = [makeTc({ id: "tc-1", tool: "bash" }),makeTc({ id: "tc-2", tool: "write_file" }),@@ -78,18 +83,13 @@ describe("ToolProgressIndicator", () => {];render(<ToolProgressIndicator toolCalls={tcs} />);- expect(screen.queryByText(/Run command/)).not.toBeInTheDocument();- expect(screen.queryByText(/Generate code/)).not.toBeInTheDocument();- expect(screen.getByText(/Run the backtest/)).toBeInTheDocument();- expect(screen.getByText(/Read file/)).toBeInTheDocument();-- await user.click(screen.getByRole("button", { name: "+2 earlier" }));expect(screen.getByText(/Run command/)).toBeInTheDocument();expect(screen.getByText(/Generate code/)).toBeInTheDocument();+ expect(screen.getByText(/Run the backtest/)).toBeInTheDocument();+ expect(screen.getByText(/Read file/)).toBeInTheDocument();});- it("prioritizes running rows, then the most recent terminal row", async () => {- const user = userEvent.setup();+ it("prioritizes running rows, then all terminal rows newest-first", () => {const tcs = [makeTc({ id: "tc-1", tool: "bash", status: "ok" }),makeTc({ id: "tc-2", tool: "write_file", status: "error" }),@@ -102,12 +102,9 @@ describe("ToolProgressIndicator", () => {expect(visibleSteps).toEqual(["Step 4 · Read file","Step 3 · Run the backtest",+ "Step 2 · Generate code",+ "Step 1 · Run command",]);- expect(screen.queryByText(/Generate code/)).not.toBeInTheDocument();-- await user.click(screen.getByRole("button", { name: "+2 earlier" }));- expect(screen.getByText(/Generate code/)).toBeInTheDocument();- expect(screen.getByText(/Run command/)).toBeInTheDocument();});it("shows determinate progress bar when progress data exists", () => {@@ -123,12 +120,10 @@ describe("ToolProgressIndicator", () => {expect(screen.getByRole("progressbar")).toBeInTheDocument();});- it("announces only coarse status and hides ticking elapsed numerals", () => {+ it("leaves announcements to ActivityLine and hides ticking elapsed numerals", () => {render(<ToolProgressIndicator toolCalls={[makeTc({ elapsed_s: 5 })]} />);- const status = screen.getByRole("status");- expect(status).toHaveClass("sr-only");- expect(status).not.toHaveAttribute("aria-atomic");+ expect(screen.queryByRole("status")).not.toBeInTheDocument();expect(screen.getByText("5s")).toHaveAttribute("aria-hidden", "true");});});diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 748c29732..5e47a9d16 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -1,18 +1,18 @@{"app": {- "version": "v0.1.11"+ "version": "v0.1.12"},"layout": {"home": "الرئيسية","agent": "الوكيل","runtime": "وقت التشغيل","reports": "التقارير",- "alphaZoo": "Alpha Zoo",+ "alphaZoo": "مكتبة ألفا","settings": "الإعدادات","correlation": "مصفوفة الارتباط","sessions": "الجلسات","newChat": "محادثة جديدة",- "noSessions": "لا توجد جلسات بعد",+ "noSessions": "لا توجد محادثات بعد — اضغط + لبدء محادثة","confirm": "تأكيد","cancel": "إلغاء","rename": "إعادة تسمية",@@ -83,42 +83,42 @@"leverageSuffix": "ضعف الرافعة","never": "أبدًا","ago": "منذ",- "notConfigured": "Not configured",- "readyToVerify": "Ready to verify",- "connectedReadOnly": "Connected · Read-only",- "connectionFailed": "Connection failed",- "verifyConnection": "Verify connection",- "retry": "Retry",- "credentialSource": "Credential source",+ "notConfigured": "غير مُعَدّ",+ "readyToVerify": "جاهز للتحقق",+ "connectedReadOnly": "متصل · للقراءة فقط",+ "connectionFailed": "فشل الاتصال",+ "verifyConnection": "التحقق من الاتصال",+ "retry": "إعادة المحاولة",+ "credentialSource": "مصدر بيانات الاعتماد","sdk": "SDK",- "configDeclared": "Config-declared",- "connectorStatusUnavailable": "Status unavailable",- "connectedAccessUnknown": "Connected · Access unknown",- "missingLongbridgeVariables": "Missing configuration. Configure these variables in agent/.env and recreate the service:",- "sdkConnectorProfile": "Direct SDK connector · read-only profile",- "connectionDetails": "Connection details",- "environment": "Environment",- "environmentIdentity": "Declared environment",- "capabilities": "Capabilities",- "capabilityAccount": "Account",- "capabilityPositions": "positions",- "capabilityOpenOrders": "open orders",- "capabilityQuotes": "quotes",- "capabilityHistory": "history",- "readOnly": "read-only",- "accessUnknown": "access unknown",- "diagnostics": "Diagnostics",- "lastChecked": "Last checked",- "errorCode": "Error code",- "installed": "Installed",- "notInstalled": "Not installed",- "connectorVerifyFailed": "Connection verification failed.",- "diagnosticCredentialsPartial": "Credentials are incomplete. Configure all required variables and recreate the service.",- "diagnosticCredentialsConflict": "Credential sources conflict. Keep one complete source, then retry.",- "diagnosticSdkMissing": "The Longbridge SDK is not installed in the backend service.",- "diagnosticAuthenticationFailed": "Authentication failed. Check the configured credentials.",- "diagnosticNetworkUnreachable": "The Longbridge service is unreachable. Check network access and retry.",- "diagnosticBrokerError": "The broker rejected the read-only verification request. Retry or check backend logs."+ "configDeclared": "مُعلَن في الإعدادات",+ "connectorStatusUnavailable": "الحالة غير متاحة",+ "connectedAccessUnknown": "متصل · صلاحية الوصول غير معروفة",+ "missingLongbridgeVariables": "الإعدادات ناقصة. اضبط المتغيرات التالية في agent/.env، ثم أعد إنشاء الخدمة:",+ "sdkConnectorProfile": "اتصال مباشر عبر SDK · ملف تعريف للقراءة فقط",+ "connectionDetails": "تفاصيل الاتصال",+ "environment": "البيئة",+ "environmentIdentity": "البيئة المُعلنة",+ "capabilities": "الإمكانات",+ "capabilityAccount": "الحساب",+ "capabilityPositions": "المراكز",+ "capabilityOpenOrders": "الأوامر المفتوحة",+ "capabilityQuotes": "الأسعار",+ "capabilityHistory": "السجل",+ "readOnly": "للقراءة فقط",+ "accessUnknown": "صلاحية الوصول غير معروفة",+ "diagnostics": "التشخيصات",+ "lastChecked": "آخر تحقق",+ "errorCode": "رمز الخطأ",+ "installed": "مثبّت",+ "notInstalled": "غير مثبّت",+ "connectorVerifyFailed": "فشل التحقق من الاتصال.",+ "diagnosticCredentialsPartial": "بيانات الاعتماد غير مكتملة. اضبط جميع المتغيرات المطلوبة، ثم أعد إنشاء الخدمة.",+ "diagnosticCredentialsConflict": "تتعارض مصادر بيانات الاعتماد. احتفظ بمصدر واحد مكتمل، ثم أعد المحاولة.",+ "diagnosticSdkMissing": "حزمة Longbridge SDK غير مثبّتة في خدمة الخادم.",+ "diagnosticAuthenticationFailed": "فشلت المصادقة. تحقق من بيانات الاعتماد المضبوطة.",+ "diagnosticNetworkUnreachable": "يتعذر الوصول إلى خدمة Longbridge. تحقق من اتصال الشبكة، ثم أعد المحاولة.",+ "diagnosticBrokerError": "رفض الوسيط طلب التحقق المخصص للقراءة فقط. أعد المحاولة أو راجع سجلات الخادم."},"reports": {"badge": "التقارير",@@ -151,14 +151,14 @@},"connection": {"reconnecting": "جارٍ إعادة الاتصال…",- "disconnected": "فُقد الاتصال",- "reload": "Reload"+ "disconnected": "فُقد الاتصال. أعد تحميل الصفحة لاستعادة الاتصال.",+ "reload": "إعادة التحميل"},"welcome": {"categories": {- "multiMarketBacktest": "اختبار عكسي لأسواق متعددة",+ "multiMarketBacktest": "اختبار عكسي لأسهم A","researchAnalysis": "البحث والتحليل",- "swarmTeams": "فرق السرب",+ "swarmTeams": "فرق محللي الذكاء الاصطناعي","docWebResearch": "بحث المستندات والويب","tradeJournal": "يومية التداول","tradingConnectors": "موصلات التداول",@@ -167,26 +167,26 @@},"examples": {"crossMarketPortfolio": "موازنة محفظة من ثلاثة أسهم",- "crossMarketPortfolioDesc": "تحسين محفظة أسهم A بمُحسّن تكافؤ المخاطر",+ "crossMarketPortfolioDesc": "وزّع الأموال على ثلاثة أسهم A بحيث يتحمل كل سهم المخاطر نفسها، ثم قارنها بالأوزان المتساوية","btcMacd": "استراتيجية MACD لأسهم A","btcMacdDesc": "اختبار عكسي لاستراتيجية MACD لأسهم A على مستوى الدقيقة",- "usTechMaxDiv": "أقصى تنويع للأسهم الزرقاء",- "usTechMaxDivDesc": "محفظة أقصى تنويع للأسهم الزرقاء",+ "usTechMaxDiv": "توزيع المخاطر بين الأسهم القيادية",+ "usTechMaxDivDesc": "وزّع أوزان خمسة أسهم قيادية بحيث لا يهيمن سهم واحد على المخاطر، باستخدام تحسين أقصى تنويع","multiFactorAlpha": "نموذج ألفا متعدد العوامل",- "multiFactorAlphaDesc": "تركيب عوامل مرجّحة بـ IC عبر 300 سهم",+ "multiFactorAlphaDesc": "ادمج أربع إشارات لاختيار الأسهم عبر 300 سهم، مع ترجيح كل إشارة وفق قدرتها السابقة على توقع العوائد (IC)","optionsGreeks": "فحص مخاطر الخيارات (Greeks)",- "optionsGreeksDesc": "تسعير Black-Scholes مع تحليل Delta/Gamma/Theta/Vega",+ "optionsGreeksDesc": "سعّر الخيار، ثم افحص مدى تأثره بسعر السهم والوقت والتقلب عبر مؤشرات Greeks","valueCommittee": "لجنة استثمار القيمة","valueCommitteeDesc": "نقاش أربعة أساتذة حول سهم واحد: Buffett / Munger / Duan Yongping / Li Lu","valueCommitteePrompt": "استخدم run_swarm مع الإعداد المسبق value_investing_committee لتحليل Tencent (00700.HK): Buffett حول الخندق والسعر، Munger حول التفكير العكسي، Duan Yongping حول العمل والإدارة، Li Lu حول يقين 10 سنوات، ثم يلخّص الرئيس نقاط الاتفاق والتعارض","bottleneckHunter": "صياد اختناقات سلسلة الإمداد",- "bottleneckHunterDesc": "العثور على فائزين مخفيين في اختناقات Layer 2/3 داخل اتجاه فائق",+ "bottleneckHunterDesc": "اعثر على الموردين الصغار الذين لا يستغني عنهم اتجاه كبير، ثم تحقق مما إذا كانت أسعارهم ما تزال جذابة","bottleneckHunterPrompt": "استخدم مهارة bottleneck-hunter للعثور على فرص اختناق Layer 2/3 في بنية الذكاء الاصطناعي (البصريات / الليزر / ركائز InP)، قيّم كل اختناق واسرد الشركات المرشحة التي تجتاز بوابة التقييم","thesisTracker": "متتبع أطروحة الاستثمار",- "thesisTrackerDesc": "اكتب أطروحة من 5 جمل + خطوط حمراء + مراسي تقييم لحيازة",+ "thesisTrackerDesc": "دوّن سبب امتلاك السهم في خمس جمل، وحدد الخطوط الحمراء التي تستدعي البيع","thesisTrackerPrompt": "استخدم مهارة thesis-tracker لبناء أطروحة استثمارية لـ Kweichow Moutai (600519.SH): أطروحة أساسية من 5 جمل، افتراضات قابلة للدحض، خطوط حمراء، ومراسي تقييم، مع التحقق عبر financial_rigor","valuationCheck": "هل السهم مُقيَّم بأكثر من قيمته؟",- "valuationCheckDesc": "تحقق من PE / PB / ROE / القيمة السوقية بحساب عشري دقيق دون انجراف عائم",+ "valuationCheckDesc": "أعد حساب PE وPB وROE والقيمة السوقية بدقة، ثم اختبرها تحت ثلاثة سيناريوهات للنمو","valuationCheckPrompt": "استخدم أداة financial_rigor للتحقق من تقييم Kweichow Moutai: السعر 1500، EPS 68.6، القيمة الدفترية للسهم 180 — احسب PE وPB وROE بدقة، ثم تقييمًا بثلاثة سيناريوهات (نمو 12%/8%/0%، PE 22/18/14، 3 سنوات)","investmentCommittee": "شراء أم بيع؟ دع اللجنة تتناقش","investmentCommitteeDesc": "نقاش متعدد الوكلاء: شراء مقابل بيع، مراجعة المخاطر، قرار مدير المحفظة",@@ -195,9 +195,9 @@"earningsReport": "تحليل ملف PDF لتقرير الأرباح","earningsReportDesc": "حمّل ملف PDF واسأل عن الأمور المالية","macroResearch": "بحث ويب: النظرة الكلية",- "macroResearchDesc": "اقرأ مصادر الويب الحية لإجراء تحليل كلي",+ "macroResearchDesc": "تحليل الاقتصاد الكلي وتوقعات سوق أسهم A","analyzeBrokerExport": "تحليل تصدير الوسيط الخاص بي",- "analyzeBrokerExportDesc": "تحليل ملفات CSV لـ تونغهوا شون/دونغتشاي/فوتو/عام — أيام الاحتفاظ، معدل الفوز، نسبة الربح/الخسارة، التوزيع الساعي",+ "analyzeBrokerExportDesc": "اقرأ ملفات Tonghuashun وEastmoney وFutu أو أي ملف CSV، وحلّل مدة الاحتفاظ ومعدل الربح ونسبة الربح إلى الخسارة ونمط أوقات التداول","diagnoseBehavior": "تشخيص تحيّزات سلوكي","diagnoseBehaviorDesc": "تأثير التصرّف، فرط التداول، مطاردة الزخم، التثبيت — الشدة + أدلة رقمية","checkConnector": "فحص الموصل المحدد",@@ -211,10 +211,10 @@"shadowDelta": "كم أترك على الطاولة؟","shadowDeltaDesc": "اختبار عكسي لاستراتيجية الظلّ وإرجاع الفرق مقابل الأرباح الفعلية","shadowReport": "إنشاء تقرير الظلّ",- "shadowReportDesc": "HTML/PDF من 8 أقسام — منحنى رأس المال، Sharpe لكل سوق، شلال إرجاع",+ "shadowReportDesc": "تقرير قابل للمشاركة من ثمانية أقسام يعرض منحنى قيمة الحساب والعائد المعدّل حسب المخاطر ومصادر كل ربح","crossMarketPortfolioPrompt": "ابنِ محفظة تكافؤ مخاطر مع 000001.SZ و600519.SH و000858.SZ، اختبر عكسيًا لعام 2024 كاملاً، وقارن بمؤشر الأوزان المتساوية","btcMacdPrompt": "اختبر استراتيجية MACD عكسيًا على أعمدة 5 دقائق لـ 000001.SZ: سريع=12، بطيء=26، إشارة=9، آخر 30 يومًا",- "usTechMaxDivPrompt": "اختبر عكسيًا محفظة التنويع الأقصى لـ 600519.SH و600858.SZ و601318.SH و000001.SZ و600036.SH لعام 2024 كاملاً",+ "usTechMaxDivPrompt": "اختبر عكسيًا محفظة التنويع الأقصى لـ 600519.SH و000858.SZ و601318.SH و000001.SZ و600036.SH لعام 2024 كاملاً","multiFactorAlphaPrompt": "ابنِ نموذج ألفا متعدد العوامل باستخدام الزخم والانعكاس والحجم والتذبذب على مكونات CSI 300 مع تركيب عوامل مرجّحة بـ IC، واختبر عكسيًا 2023-2024","optionsGreeksPrompt": "احسب Greeks للخيارات باستخدام Black-Scholes: فوري=100، سعر التنفيذ=105، معدل خالي من المخاطر=3%، تقلب=25%، انتهاء=90 يومًا، حلل Delta/Gamma/Theta/Vega","investmentCommitteePrompt": "[وضع فريق السرب] استخدم الإعداد المسبق investment_committee لتقييم ما إذا كنت ستشتري أو تبيع 600519.SH في ظل ظروف السوق الحالية",@@ -261,10 +261,10 @@"provider": "المزوّد","refresh": "تحديث","modelName": "اسم النموذج",- "baseUrl": "Base URL",+ "baseUrl": "عنوان URL الأساسي","apiAuthKey": "مفتاح مصادقة API","loading": "جارٍ التحميل…",- "temperature": "Temperature",+ "temperature": "درجة الحرارة","timeoutSeconds": "المهلة (ثوانٍ)","maxRetries": "الحد الأقصى للمحاولات","reasoningEffort": "جهد الاستدلال",@@ -367,7 +367,7 @@"title": "سوق أدوات QVeris","subtitle": "أبقِ البيانات العامة المجانية كخيار افتراضي، وفعّل تنفيذ QVeris المدفوع عند الحاجة فقط.","enabled": "تفعيل مسار QVeris المدفوع",- "baseUrl": "Base URL",+ "baseUrl": "عنوان URL الأساسي","apiKey": "مفتاح API","apiKeyPlaceholder": "اتركه فارغًا للاحتفاظ بالمفتاح الحالي","mode": "الوضع",@@ -389,8 +389,8 @@"agent": {"connectionLostReconnect": "فُقد الاتصال، جارٍ إعادة الاتصال…","connectionRestored": "تمت استعادة الاتصال",- "agentWorking": "الوكيل يعمل…",- "reasoning": "استدلال…",+ "agentWorking": "جارٍ بدء العمل…",+ "reasoning": "جارٍ التفكير مليًا…","running": "قيد التشغيل","newMessages": "رسائل جديدة","newResearchGoal": "هدف بحث جديد",@@ -404,7 +404,7 @@"save": "حفظ","cancelGoal": "إلغاء الهدف","describeGoal": "صف هدف البحث لإرفاقه بهذه الجلسة",- "placeholder": "مثال: أنشئ استراتيجية تقاطع MA مزدوجة لـ 000001.SZ، واختبرها عكسيًا لعام 2024",+ "placeholder": "مثال: اختبر استراتيجية بسيطة للمتوسط المتحرك على 000001.SZ خلال عام 2024","send": "إرسال","messageInputLabel": "رسالة إلى الوكيل","inputHint": "Enter للإرسال · Shift+Enter لسطر جديد",@@ -423,8 +423,8 @@"researchGoalUpdated": "تم تحديث هدف البحث","failedToUpdateGoal": "فشل تحديث الهدف.","failedToLoadGoal": "فشل تحميل الهدف.",- "cancelRequestSent": "تم إرسال طلب الإلغاء",- "cancelFailed": "فشل الإلغاء",+ "cancelRequestSent": "جارٍ الإيقاف…",+ "cancelFailed": "تعذّر الإيقاف — حاول مرة أخرى.","connectorHalted": "تم إيقاف وقت تشغيل الموصل","failedToHaltConnector": "فشل إيقاف وقت تشغيل الموصل.","cancelledFromUI": "تم الإلغاء من واجهة الويب.",@@ -450,7 +450,27 @@"goalModeChip": "هدف البحث","continueGoalMessage": "متابعة هدف البحث: {{goal}}","loadEarlier": "تحميل الرسائل الأقدم",- "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use."+ "authRequired": "يتطلب الوصول إلى API عن بُعد مفتاح API. أضفه في الإعدادات، أو شغّل الخادم على localhost للاستخدام المحلي فقط.",+ "followUpPlaceholder": "اسأل عن هذا التشغيل — مثلًا: لماذا يبلغ التراجع هذا الحد؟",+ "continuePrompt": "تابع من حيث توقفت.",+ "doneMarker": "اكتمل التشغيل",+ "backgroundRunComplete": "اكتمل تشغيل في جلسة أخرى.",+ "activity": {+ "verbs": {+ "readingMarketData": "جارٍ قراءة بيانات السوق",+ "writingStrategy": "جارٍ إعداد الاستراتيجية",+ "runningBacktest": "جارٍ تشغيل الاختبار التاريخي",+ "validatingNumbers": "جارٍ التحقق من الأرقام",+ "working": "جارٍ العمل"+ },+ "done": "تم",+ "stopped": "أوقفته أنت",+ "timeout": "توقف الانتظار بعد {{elapsed}} — ربما لا يزال التشغيل في مراحله النهائية",+ "failed": "فشل",+ "steps": "{{count}} خطوات",+ "continue": "متابعة",+ "reattach": "إعادة الاتصال"+ }},"runDetail": {"title": "تفاصيل التشغيل",@@ -465,7 +485,7 @@"downloadTradesCsv": "تنزيل CSV للتداولات","downloadMetricsCsv": "تنزيل CSV للمقاييس","noChartData": "لا توجد بيانات رسم بياني",- "noChartDataDesc": "ربما لم يُولِّد محرك الاختبار العكسي بيانات أسعار. تحقّق من دليل artifacts/.",+ "noChartDataDesc": "لم يحفظ هذا التشغيل بيانات الأسعار، لذلك لا يوجد مخطط. تظل المقاييس أدناه صالحة.","symbol": "الرمز","showOnly": "عرض فقط","addSymbol": "إضافة رمز",@@ -500,7 +520,9 @@"noValidationPayload": "لم يتم تسجيل حمولة التحقق.","noArtifactChecksums": "لم يتم تسجيل مجاميع التحقق للمنتجات.","noCodeFiles": "لا توجد ملفات شفرة.",- "fullReport": "التقرير الكامل →"+ "fullReport": "التقرير الكامل →",+ "unknown": "غير معروف",+ "noneRecorded": "لا توجد سجلات"},"compare": {"title": "مقارنة الاستراتيجيات",@@ -535,7 +557,7 @@"correlation": {"title": "مصفوفة الارتباط","assetCodes": "رموز الأصول",- "assetCodesHint": "رموز مفصولة بفواصل، مثال: BTC-USDT,ETH-USDT,AAPL,SPY",+ "assetCodesHint": "رموز أسهم مفصولة بفواصل، مثل: 000001.SZ,600519.SH,000858.SZ","windowDays": "النافذة (أيام)","method": "الطريقة","compute": "احتساب",@@ -552,10 +574,10 @@"regimeExitThreshold": "عتبة الخروج"},"alphaZoo": {- "title": "Alpha Zoo",+ "title": "مكتبة عوامل ألفا","prebuiltAlpha": "{{count}} ألفا كمي مُعدّ مسبقًا عبر 5 مكتبات عوامل","prebuiltAlphaLoading": "ألفا كمي مُعدّ مسبقًا عبر 5 مكتبات عوامل",- "browseDesc": "تصفّح الإشارات العرضية المعتمدة على الصيغ من Qlib ومجموعة Kakushadze 101 وGTJA 191 وأدبيات الشذوذ الأكاديمي والعوامل الأساسية الآمنة PIT. انقر على أي ألفا لقراءة صيغتها وشفرتها المصدرية، أو نفّذ قياسًا لتسجيل مكتبة العوامل بأكملها على'universe وفترة محددة.",+ "browseDesc": "تصفّح الإشارات العرضية المعتمدة على الصيغ من Qlib ومجموعة Kakushadze 101 وGTJA 191 وأدبيات الشذوذ الأكاديمي والعوامل الأساسية الآمنة PIT. انقر على أي ألفا لقراءة صيغتها وشفرتها المصدرية، أو نفّذ قياسًا لتقييم مكتبة العوامل بأكملها ضمن كون وفترة محددين.","search": "بحث","searchPlaceholder": "تصفية حسب المعرّف أو الاسم المستعار…","zoo": "مكتبة العوامل",@@ -614,7 +636,7 @@"selected": "{{count}} مُختار","alphaIdsHint": "افصل المعرّفات بفواصل أو مسافات. تلميح: حدّد الألفا في الكتالوج واضغط \"مقارنة\" لتعبئة هذا الحقل تلقائيًا.","rankBy": "الترتيب حسب",- "pickAtLeast2": "اختر ألفا واحدًا على الأقل.",+ "pickAtLeast2": "اختر عاملَي ألفا على الأقل.","enterAtLeast2": "أدخل معرّفي ألفا مختلفين على الأقل للمقارنة.","winner": "الفائز","compared": "تمت المقارنة",@@ -670,7 +692,7 @@"growth": "النمو","leverage": "الرافعة"},- "compareTooltip": "حدّد ألفا أو أكثر أدناه، ثم قارنها مباشرة",+ "compareTooltip": "حدّد عاملَي ألفا أو أكثر أدناه، ثم قارنها مباشرة","loadingAlpha": "جارٍ تحميل {{id}}…","comparedRankedBy": "{{count}} مقارنة · مرتّبة حسب {{sort}} · {{universe}} · {{period}}","skippedCount": "{{count}} تم تخطيها",@@ -680,7 +702,16 @@"icMean": "متوسط IC","icPositiveRatio": "نسبة IC > 0","icCount": "عدد العينات"- }+ },+ "failedToLoadAlphas": "تعذّر تحميل قائمة ألفا",+ "selectAlphaForCompare": "حدّد {{id}} للمقارنة",+ "failedToLoadAlpha": "تعذّر تحميل ألفا",+ "failedToStartBench": "تعذّر بدء الاختبار المعياري",+ "singleAssetHint": "{{message}} جرّب `sp500` أو `csi300` للحصول على معامل IC مقطعي ذي دلالة.",+ "benchStreamError": "خطأ في تدفق الاختبار المعياري",+ "job": "المهمة {{id}}…",+ "compareStreamError": "خطأ في تدفق المقارنة",+ "failedToStartComparison": "تعذّر بدء المقارنة"},"validation": {"noData": "لا توجد بيانات تحقق متاحة.",@@ -697,7 +728,7 @@"ciIncludes0": "CI يتضمن 0","bootstrapDesc": "تمت إعادة عينة العوائد اليومية {{n}} مرة لتقدير فاصل ثقة {{pct}}.","observedSharpe": "Sharpe المُلاحَظ",- "ci": "{{pct}} CI",+ "ci": "فاصل ثقة {{pct}}","medianSharpe": "وسيط Sharpe","probSharpePositive": "احتمال (Sharpe > 0)","walkForward": "تحليل Walk-Forward",@@ -750,12 +781,12 @@},"swarmStatus": {"agents": "{{done}}/{{total}} وكيل",- "layer": "الطبقة {{current}}/{{total}}",+ "layer": "الجولة {{current}} من {{total}}","agent": "الوكيل","status": "الحالة","tool": "الأداة","time": "الوقت",- "iters": "التكرارات",+ "iters": "التمريرات","output": "المخرجات","waitingForEvents": "بانتظار أحداث الوكيل...","teamStarting": "الفريق قيد التشغيل — أولى التحديثات خلال ثوانٍ…",@@ -787,18 +818,18 @@"confirmTitle": "تأكيد الالتزام بالتفويض","confirmDescription": "سيؤدي الالتزام إلى منح الوكيل صلاحية تداول فورية ضمن الحدود الموضحة أدناه.","confirmButton": "تأكيد والالتزام",- "maxPerOrder": "≤{{amount}}/order",- "expiresOn": "expires {{date}}",- "accountSummary": "{{broker}} · {{type}} account · funded by {{fundedBy}}",- "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}"+ "maxPerOrder": "بحد أقصى {{amount}} لكل أمر",+ "expiresOn": "ينتهي في {{date}}",+ "accountSummary": "{{broker}} · حساب {{type}} · ممول من {{fundedBy}}",+ "adjustRequestMessage": "لطلب تعديل اقتراح التفويض «{{label}}» (الخيار {{ordinal}}): {{text}}"},"messageBubble": {"copied": "تم النسخ","copy": "نسخ",- "timeoutHint": "Timed out. Simplify the strategy or use fewer assets.",- "apiFailedHint": "API request failed. Try again shortly.",- "executionFailedHint": "Execution failed. Try again.",- "retry": "Try again"+ "timeoutHint": "انتهت المهلة. بسّط الاستراتيجية أو استخدم عددًا أقل من الأصول.",+ "apiFailedHint": "فشل طلب API. حاول مرة أخرى بعد قليل.",+ "executionFailedHint": "فشل التنفيذ. حاول مرة أخرى.",+ "retry": "إعادة المحاولة"},"pineViewer": {"pineScript": "Pine Script v6",@@ -819,7 +850,7 @@"featureAgent": "وكيل ذكاء اصطناعي","featureAgentDesc": "توليد استراتيجيات من اللغة الطبيعية باستدلال ReAct","featureBacktest": "اختبار عكسي مدمج",- "featureBacktestDesc": "7 مصادر بيانات عبر الأسهم الصينية، هونج كونج/أمريكا، والعملات الرقمية",+ "featureBacktestDesc": "مصادر بيانات متعددة للتحليل الكمي لأسهم A","featureStreaming": "بث في الوقت الفعلي","featureStreamingDesc": "راقب الوكيل وهو يفكّر، ويستدعي الأدوات، ويتكرّر","featureReplay": "إعادة تشغيل الاستراتيجية",@@ -835,24 +866,24 @@"step4Desc": "يمكنك اختياريًا الموافقة على تفويض تداول بحدود واضحة — لن يُنفَّذ أي أمر دون تأكيدك."},"errorBoundary": {- "somethingWrong": "حدث خطأ ما"+ "somethingWrong": "حدث خطأ ما. أعد تحميل الصفحة للمتابعة."},"charts": {- "noPriceData": "لا توجد بيانات أسعار",- "noCorrelationData": "لا توجد بيانات ارتباط",- "noEquityData": "لا توجد بيانات أصول"+ "noPriceData": "لا توجد بيانات أسعار لهذا الرمز حتى الآن",+ "noCorrelationData": "اختر رمزين على الأقل للمقارنة",+ "noEquityData": "لا يوجد منحنى لقيمة الحساب حتى الآن — شغّل اختبارًا عكسيًا أولًا"},"toolProgress": {"step": "الخطوة {{step}} · {{tool}}",- "toolsRunning": "الأدوات قيد التشغيل: {{count}}",- "toolsCompleted": "الأدوات المكتملة: {{count}}",+ "toolsRunning": "جارٍ العمل على {{count}} مهام في آن واحد",+ "toolsCompleted": "اكتملت {{count}} خطوات","more": "… و{{count}} أخرى","etaSeconds": "متبقٍ نحو {{seconds}} ثانية","earlier": "+{{count}} سابقة"},"swarm": {"assemblingTeam": "جارٍ تشكيل الفريق…",- "preparingLayers": "جارٍ تجهيز الطبقات…",+ "preparingLayers": "جارٍ تحديد ترتيب العمل…","agentProgress": "تقدم وكلاء السرب","status": {"waiting": "في الانتظار",@@ -880,107 +911,107 @@"good": "جيد","poor": "ضعيف","gloss": {- "total_return": "How much the strategy gained or lost over the full test period.",- "annual_return": "The strategy's return scaled to a typical one-year period.",- "sharpe": "Return earned per unit of total risk, where higher is generally better.",- "max_drawdown": "The largest peak-to-trough loss during the test period.",- "win_rate": "The share of completed trades that made a profit.",- "trade_count": "The number of trades completed during the test period.",- "calmar": "Annual return divided by maximum drawdown, balancing growth against worst loss.",- "sortino": "Return earned per unit of downside risk, where higher is generally better.",- "profit_loss_ratio": "The average winning trade compared with the average losing trade.",- "max_consecutive_loss": "The longest run of losing trades in a row.",- "benchmark_return": "The return of the comparison benchmark over the same period.",- "excess_return": "How much the strategy outperformed or underperformed its benchmark.",- "information_ratio": "Excess return earned per unit of tracking error against the benchmark.",- "final_value": "The portfolio value at the end of the test period.",- "avg_holding_days": "The average number of days each position stayed open."+ "total_return": "مقدار ما ربحته الاستراتيجية أو خسرته خلال فترة الاختبار كاملة.",+ "annual_return": "عائد الاستراتيجية بعد تحويله إلى فترة قياسية مدتها سنة واحدة.",+ "sharpe": "العائد المحقق لكل وحدة من إجمالي المخاطر، ويكون الأعلى أفضل عمومًا.",+ "max_drawdown": "أكبر خسارة من قمة إلى قاع خلال فترة الاختبار.",+ "win_rate": "نسبة الصفقات المكتملة التي حققت ربحًا.",+ "trade_count": "عدد الصفقات المكتملة خلال فترة الاختبار.",+ "calmar": "العائد السنوي مقسومًا على أقصى تراجع، لموازنة النمو مع أسوأ خسارة.",+ "sortino": "العائد المحقق لكل وحدة من مخاطر الهبوط، ويكون الأعلى أفضل عمومًا.",+ "profit_loss_ratio": "مقارنة متوسط ربح الصفقة الرابحة بمتوسط خسارة الصفقة الخاسرة.",+ "max_consecutive_loss": "أطول سلسلة متتالية من الصفقات الخاسرة.",+ "benchmark_return": "عائد المؤشر المرجعي للمقارنة خلال الفترة نفسها.",+ "excess_return": "مقدار تفوق الاستراتيجية على مؤشرها المرجعي أو تأخرها عنه.",+ "information_ratio": "العائد الزائد المحقق لكل وحدة من خطأ التتبع مقابل المؤشر المرجعي.",+ "final_value": "قيمة المحفظة في نهاية فترة الاختبار.",+ "avg_holding_days": "متوسط عدد الأيام التي ظل فيها كل مركز مفتوحًا."}},"tools": {- "add_goal_evidence": "Add goal evidence",- "alpha_bench": "Benchmark alpha factors",- "alpha_compare": "Compare alpha factors",- "alpha_zoo": "Browse alpha library",- "analyze_image": "Analyze the image",- "analyze_trade_journal": "Analyze trade journal",- "background_run": "Start background task",- "backtest": "Run the backtest",- "bash": "Run command",- "cancel_background": "Cancel background task",- "check_background": "Check background task",- "compact": "Summarize conversation",- "create_hypothesis": "Create research hypothesis",- "delete_skill": "Delete custom skill",- "edit_file": "Edit code",- "extract_shadow_strategy": "Extract shadow strategy",- "factor_analysis": "Analyze factors",- "financial_rigor": "Verify financial analysis",- "generate_backtest_config": "Generate backtest config",- "get_block_trades": "Fetch block trades",- "get_dragon_tiger": "Fetch dragon-tiger list",- "get_financial_statements": "Fetch financial statements",- "get_fund_flow": "Fetch fund flow",- "get_fundamentals": "Fetch fundamentals",- "get_lockup_expiry": "Fetch lockup expiries",- "get_macro_series": "Fetch macro series",- "get_margin_trading": "Fetch margin trading",- "get_market_data": "Fetch market data",- "get_northbound_flow": "Fetch northbound flow",- "get_options_chain": "Fetch options chain",- "get_research_goal": "View research goal",- "get_research_reports": "Fetch research reports",- "get_sec_filings": "Fetch SEC filings",- "get_sector_info": "Fetch sector data",- "get_shareholder_count": "Fetch shareholder count",- "get_stock_news": "Fetch stock news",- "get_stock_profile": "Fetch stock profile",- "iwencai_search": "Search iWenCai",- "link_autopilot_backtest": "Link autopilot backtest",- "link_backtest": "Link hypothesis backtest",- "load_skill": "Load strategy knowledge",- "options_pricing": "Price options",- "patch_skill": "Update custom skill",- "pattern": "Detect chart patterns",- "portfolio_risk_xray": "X-ray portfolio risk",- "propose_mandate_profiles": "Propose trading mandates",- "qveris_execute": "Execute QVeris action",- "qveris_inspect": "Inspect QVeris action",- "qveris_search": "Search QVeris",- "read_document": "Read document",- "read_file": "Read file",- "read_url": "Read webpage",- "remember": "Remember this",- "render_shadow_report": "Create shadow report",- "report_audit": "Audit research report",- "run_research_autopilot": "Run research autopilot",- "run_shadow_backtest": "Run shadow backtest",- "run_swarm": "Convene the team",- "save_skill": "Save custom skill",- "scaffold_signal_engine": "Build signal engine",- "scan_shadow_signals": "Scan shadow signals",- "screen_market": "Screen market",- "sdm_decay_scan": "Scan strategy decay",- "sdm_register": "Register strategy",- "sdm_status": "Check strategy status",- "search_hypotheses": "Search hypotheses",- "search_symbol": "Search symbols",- "session_search": "Search past sessions",- "skill_file": "Read skill file",- "start_research_goal": "Start research goal",- "trading_account": "View broker account",- "trading_cancel_order": "Cancel broker order",- "trading_check": "Check broker connection",- "trading_connections": "List broker connections",- "trading_history": "View trade history",- "trading_orders": "View broker orders",- "trading_place_order": "Place broker order",- "trading_positions": "View broker positions",- "trading_quote": "Fetch broker quote",- "trading_select_connection": "Select broker connection",- "update_hypothesis": "Update research hypothesis",- "update_research_goal_status": "Update goal status",- "web_search": "Search the web",- "write_file": "Generate code"+ "add_goal_evidence": "إضافة دليل إلى الهدف",+ "alpha_bench": "قياس عوامل ألفا مرجعيًا",+ "alpha_compare": "مقارنة عوامل ألفا",+ "alpha_zoo": "تصفح مكتبة ألفا",+ "analyze_image": "تحليل الصورة",+ "analyze_trade_journal": "تحليل يومية التداول",+ "background_run": "بدء مهمة في الخلفية",+ "backtest": "تشغيل الاختبار العكسي",+ "bash": "تشغيل أمر",+ "cancel_background": "إلغاء مهمة الخلفية",+ "check_background": "التحقق من مهمة الخلفية",+ "compact": "تلخيص المحادثة",+ "create_hypothesis": "إنشاء فرضية بحث",+ "delete_skill": "حذف مهارة مخصصة",+ "edit_file": "تعديل الشيفرة",+ "extract_shadow_strategy": "استخراج استراتيجية الظل",+ "factor_analysis": "تحليل العوامل",+ "financial_rigor": "التحقق من التحليل المالي",+ "generate_backtest_config": "إنشاء إعدادات الاختبار العكسي",+ "get_block_trades": "جلب الصفقات الضخمة",+ "get_dragon_tiger": "جلب قائمة التنين والنمر",+ "get_financial_statements": "جلب القوائم المالية",+ "get_fund_flow": "جلب تدفقات الأموال",+ "get_fundamentals": "جلب البيانات الأساسية",+ "get_lockup_expiry": "جلب مواعيد انتهاء حظر البيع",+ "get_macro_series": "جلب السلاسل الاقتصادية الكلية",+ "get_margin_trading": "جلب بيانات التداول بالهامش",+ "get_market_data": "جلب بيانات السوق",+ "get_northbound_flow": "جلب تدفقات الاستثمار المتجه شمالًا",+ "get_options_chain": "جلب سلسلة الخيارات",+ "get_research_goal": "عرض هدف البحث",+ "get_research_reports": "جلب تقارير الأبحاث",+ "get_sec_filings": "جلب إفصاحات SEC",+ "get_sector_info": "جلب بيانات القطاعات",+ "get_shareholder_count": "جلب عدد المساهمين",+ "get_stock_news": "جلب أخبار السهم",+ "get_stock_profile": "جلب ملف السهم",+ "iwencai_search": "البحث في iWenCai",+ "link_autopilot_backtest": "ربط الاختبار العكسي بالبحث التلقائي",+ "link_backtest": "ربط الاختبار العكسي بالفرضية",+ "load_skill": "تحميل معرفة الاستراتيجية",+ "options_pricing": "تسعير الخيارات",+ "patch_skill": "تحديث مهارة مخصصة",+ "pattern": "اكتشاف أنماط المخطط",+ "portfolio_risk_xray": "فحص مخاطر المحفظة بعمق",+ "propose_mandate_profiles": "اقتراح تفويضات التداول",+ "qveris_execute": "تنفيذ إجراء QVeris",+ "qveris_inspect": "فحص إجراء QVeris",+ "qveris_search": "البحث في QVeris",+ "read_document": "قراءة مستند",+ "read_file": "قراءة ملف",+ "read_url": "قراءة صفحة ويب",+ "remember": "حفظ في الذاكرة",+ "render_shadow_report": "إنشاء تقرير الظل",+ "report_audit": "تدقيق تقرير البحث",+ "run_research_autopilot": "تشغيل البحث التلقائي",+ "run_shadow_backtest": "تشغيل الاختبار العكسي للظل",+ "run_swarm": "جمع الفريق",+ "save_skill": "حفظ مهارة مخصصة",+ "scaffold_signal_engine": "بناء محرك الإشارات",+ "scan_shadow_signals": "مسح إشارات الظل",+ "screen_market": "فرز السوق",+ "sdm_decay_scan": "فحص تدهور الاستراتيجية",+ "sdm_register": "تسجيل الاستراتيجية",+ "sdm_status": "التحقق من حالة الاستراتيجية",+ "search_hypotheses": "البحث في الفرضيات",+ "search_symbol": "البحث عن الرموز",+ "session_search": "البحث في الجلسات السابقة",+ "skill_file": "قراءة ملف المهارة",+ "start_research_goal": "بدء هدف البحث",+ "trading_account": "عرض حساب الوسيط",+ "trading_cancel_order": "إلغاء أمر لدى الوسيط",+ "trading_check": "فحص اتصال الوسيط",+ "trading_connections": "سرد اتصالات الوسطاء",+ "trading_history": "عرض سجل التداول",+ "trading_orders": "عرض أوامر الوسيط",+ "trading_place_order": "إرسال أمر إلى الوسيط",+ "trading_positions": "عرض مراكز الوسيط",+ "trading_quote": "جلب سعر من الوسيط",+ "trading_select_connection": "اختيار اتصال الوسيط",+ "update_hypothesis": "تحديث فرضية البحث",+ "update_research_goal_status": "تحديث حالة الهدف",+ "web_search": "البحث في الويب",+ "write_file": "إنشاء الشيفرة"}}diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 88244632c..e6e183ea3 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -455,7 +455,27 @@"goalModeChip": "Research goal","continueGoalMessage": "Continue research goal: {{goal}}","loadEarlier": "Load earlier messages",- "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use."+ "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use.",+ "followUpPlaceholder": "Ask about this run — e.g. why is the drawdown so deep?",+ "continuePrompt": "Continue from where you stopped.",+ "doneMarker": "Run complete",+ "backgroundRunComplete": "A run finished in another session.",+ "activity": {+ "verbs": {+ "readingMarketData": "Reading the market data",+ "writingStrategy": "Writing the strategy",+ "runningBacktest": "Running the backtest",+ "validatingNumbers": "Double-checking the numbers",+ "working": "Working"+ },+ "done": "Done",+ "stopped": "Stopped by you",+ "timeout": "Stopped waiting after {{elapsed}} — the run may still be finishing",+ "failed": "Failed",+ "steps": "{{count}} steps",+ "continue": "Continue",+ "reattach": "Re-attach"+ }},"runDetail": {"title": "Run Detail",@@ -505,7 +525,9 @@"noValidationPayload": "No validation payload recorded.","noArtifactChecksums": "No artifact checksums recorded.","noCodeFiles": "No code files.",- "fullReport": "Full Report →"+ "fullReport": "Full Report →",+ "unknown": "unknown",+ "noneRecorded": "None recorded"},"compare": {"title": "Strategy Comparison",@@ -685,7 +707,16 @@"icMean": "IC mean","icPositiveRatio": "IC > 0 ratio","icCount": "Sample count"- }+ },+ "failedToLoadAlphas": "Failed to load alphas",+ "selectAlphaForCompare": "Select {{id}} for compare",+ "failedToLoadAlpha": "Failed to load alpha",+ "failedToStartBench": "Failed to start bench",+ "singleAssetHint": "{{message}} Try `sp500` or `csi300` for a meaningful cross-sectional IC.",+ "benchStreamError": "Bench stream error",+ "job": "Job {{id}}…",+ "compareStreamError": "Compare stream error",+ "failedToStartComparison": "Failed to start comparison"},"validation": {"noData": "No validation data available.",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 83572b66a..5446cdc52 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -1,18 +1,18 @@{"app": {- "version": "v0.1.11"+ "version": "v0.1.12"},"layout": {"home": "ホーム","agent": "エージェント","runtime": "ランタイム","reports": "レポート",- "alphaZoo": "Alpha Zoo",+ "alphaZoo": "アルファ・ライブラリ","settings": "設定","correlation": "相関行列","sessions": "セッション","newChat": "新規チャット",- "noSessions": "セッションがありません",+ "noSessions": "チャットはまだありません。+を押して始めましょう","confirm": "確認","cancel": "キャンセル","rename": "名前を変更",@@ -83,42 +83,42 @@"leverageSuffix": "倍レバレッジ","never": "なし","ago": "前",- "notConfigured": "Not configured",- "readyToVerify": "Ready to verify",- "connectedReadOnly": "Connected · Read-only",- "connectionFailed": "Connection failed",- "verifyConnection": "Verify connection",- "retry": "Retry",- "credentialSource": "Credential source",+ "notConfigured": "未設定",+ "readyToVerify": "検証できます",+ "connectedReadOnly": "接続済み・読み取り専用",+ "connectionFailed": "接続に失敗しました",+ "verifyConnection": "接続を検証",+ "retry": "再試行",+ "credentialSource": "認証情報の取得元","sdk": "SDK",- "configDeclared": "Config-declared",- "connectorStatusUnavailable": "Status unavailable",- "connectedAccessUnknown": "Connected · Access unknown",- "missingLongbridgeVariables": "Missing configuration. Configure these variables in agent/.env and recreate the service:",- "sdkConnectorProfile": "Direct SDK connector · read-only profile",- "connectionDetails": "Connection details",- "environment": "Environment",- "environmentIdentity": "Declared environment",- "capabilities": "Capabilities",- "capabilityAccount": "Account",- "capabilityPositions": "positions",- "capabilityOpenOrders": "open orders",- "capabilityQuotes": "quotes",- "capabilityHistory": "history",- "readOnly": "read-only",- "accessUnknown": "access unknown",- "diagnostics": "Diagnostics",- "lastChecked": "Last checked",- "errorCode": "Error code",- "installed": "Installed",- "notInstalled": "Not installed",- "connectorVerifyFailed": "Connection verification failed.",- "diagnosticCredentialsPartial": "Credentials are incomplete. Configure all required variables and recreate the service.",- "diagnosticCredentialsConflict": "Credential sources conflict. Keep one complete source, then retry.",- "diagnosticSdkMissing": "The Longbridge SDK is not installed in the backend service.",- "diagnosticAuthenticationFailed": "Authentication failed. Check the configured credentials.",- "diagnosticNetworkUnreachable": "The Longbridge service is unreachable. Check network access and retry.",- "diagnosticBrokerError": "The broker rejected the read-only verification request. Retry or check backend logs."+ "configDeclared": "設定ファイルで指定",+ "connectorStatusUnavailable": "状態を取得できません",+ "connectedAccessUnknown": "接続済み・アクセス権不明",+ "missingLongbridgeVariables": "設定が不足しています。agent/.env に次の変数を設定し、サービスを再作成してください:",+ "sdkConnectorProfile": "SDK 直接接続・読み取り専用プロファイル",+ "connectionDetails": "接続の詳細",+ "environment": "環境",+ "environmentIdentity": "設定上の環境",+ "capabilities": "利用可能な機能",+ "capabilityAccount": "アカウント",+ "capabilityPositions": "ポジション",+ "capabilityOpenOrders": "未約定注文",+ "capabilityQuotes": "クォート",+ "capabilityHistory": "履歴",+ "readOnly": "読み取り専用",+ "accessUnknown": "アクセス権不明",+ "diagnostics": "診断",+ "lastChecked": "最終確認",+ "errorCode": "エラーコード",+ "installed": "インストール済み",+ "notInstalled": "未インストール",+ "connectorVerifyFailed": "接続を検証できませんでした。",+ "diagnosticCredentialsPartial": "認証情報が不足しています。必要な変数をすべて設定し、サービスを再作成してください。",+ "diagnosticCredentialsConflict": "認証情報の取得元が競合しています。完全な取得元を1つだけ残して、再試行してください。",+ "diagnosticSdkMissing": "バックエンドサービスに Longbridge SDK がインストールされていません。",+ "diagnosticAuthenticationFailed": "認証に失敗しました。設定した認証情報を確認してください。",+ "diagnosticNetworkUnreachable": "Longbridge サービスに接続できません。ネットワーク接続を確認して再試行してください。",+ "diagnosticBrokerError": "ブローカーが読み取り専用の検証リクエストを拒否しました。再試行するか、バックエンドのログを確認してください。"},"reports": {"badge": "レポート",@@ -151,14 +151,14 @@},"connection": {"reconnecting": "再接続しています…",- "disconnected": "接続が切断されました",- "reload": "Reload"+ "disconnected": "接続が切れました。再接続するにはページを再読み込みしてください。",+ "reload": "再読み込み"},"welcome": {"categories": {- "multiMarketBacktest": "マルチマーケットバックテスト",+ "multiMarketBacktest": "A株バックテスト","researchAnalysis": "リサーチ & 分析",- "swarmTeams": "Swarm チーム",+ "swarmTeams": "AI アナリストチーム","docWebResearch": "ドキュメント & Web リサーチ","tradeJournal": "トレードジャーナル","tradingConnectors": "トレーディングコネクタ",@@ -167,26 +167,26 @@},"examples": {"crossMarketPortfolio": "3銘柄の配分バランス",- "crossMarketPortfolioDesc": "A株ポートフォリオのリスクパリティ最適化",+ "crossMarketPortfolioDesc": "3つのA株に資金を配分し、各銘柄のリスクを均等にしてから、等ウェイト配分と比較","btcMacd": "A株 MACD 戦略","btcMacdDesc": "分足データによるA株MACD戦略バックテスト",- "usTechMaxDiv": "ブルーチップ最大分散",- "usTechMaxDivDesc": "ブルーチップ最大分散ポートフォリオ",+ "usTechMaxDiv": "優良株のリスクを分散",+ "usTechMaxDivDesc": "1銘柄にリスクが偏らないよう、最大分散化で5つの優良株にウェイトを配分","multiFactorAlpha": "マルチファクター Alpha モデル",- "multiFactorAlphaDesc": "300 銘柄に対する IC 重み付きファクター合成",- "optionsGreeks": "オプションのリスク指標(Greeks)",- "optionsGreeksDesc": "Black-Scholes 価格モデルに基づく Delta/Gamma/Theta/Vega 分析",+ "multiFactorAlphaDesc": "300銘柄を対象に4つの選銘シグナルを組み合わせ、過去のリターン予測力(IC)で加重",+ "optionsGreeks": "オプションのリスク確認(Greeks)",+ "optionsGreeksDesc": "オプションを評価し、株価・時間・ボラティリティの変化にどれだけ反応するか(Greeks)を確認","valueCommittee": "バリュー投資委員会","valueCommitteeDesc": "Buffett / Munger / Duan Yongping / Li Lu の4視点で1銘柄を討論","valueCommitteePrompt": "run_swarm で value_investing_committee プリセットを使い、Tencent (00700.HK) を分析してください: Buffett は moat と価格、Munger は反転思考、Duan Yongping は事業と経営陣、Li Lu は10年確度を評価し、議長が合意点と矛盾点を統合してください","bottleneckHunter": "サプライチェーン・ボトルネックハンター",- "bottleneckHunterDesc": "大きなトレンドの Layer 2/3 ボトルネックから隠れた勝者を探す",+ "bottleneckHunterDesc": "大きなトレンドに欠かせない小規模サプライヤーを見つけ、まだ割安かを確認","bottleneckHunterPrompt": "bottleneck-hunter スキルを使い、AI インフラ (光通信 / レーザー / InP 基板) の Layer 2/3 サプライチェーン・ボトルネック機会を探し、各ボトルネックを採点して、バリュエーションゲートを通過する候補企業を挙げてください","thesisTracker": "投資テーシス・トラッカー",- "thesisTrackerDesc": "保有銘柄に5文のテーシス、レッドライン、評価アンカーを作成",+ "thesisTrackerDesc": "保有理由を5文で整理し、売却判断につながるレッドラインも設定","thesisTrackerPrompt": "thesis-tracker スキルを使い、Kweichow Moutai (600519.SH) の投資テーシスを作ってください: 5文の中核テーシス、反証可能な仮説、レッドライン、評価アンカーを financial_rigor で検証してください","valuationCheck": "割高かどうかを検証(PE/PB/ROE)",- "valuationCheckDesc": "厳密な十進演算で PE / PB / ROE / 時価総額を検証 (浮動小数点誤差なし)",+ "valuationCheckDesc": "PE / PB / ROE / 時価総額を端数まで再計算し、3つの成長シナリオでストレステスト","valuationCheckPrompt": "financial_rigor ツールで Kweichow Moutai の評価を検証してください: 価格 1500、EPS 68.6、1株当たり純資産 180 から PE、PB、ROE を厳密に計算し、3年の3シナリオ評価 (成長率 12%/8%/0%、PE 22/18/14) も実行してください","investmentCommittee": "買いか売りか?委員会で討論","investmentCommitteeDesc": "マルチエージェント討論: ロング vs ショート、リスクレビュー、PM 決定",@@ -195,9 +195,9 @@"earningsReport": "決算報告 PDF を分析","earningsReportDesc": "PDF をアップロードして財務に関する質問をする","macroResearch": "Web リサーチ: マクロ見通し",- "macroResearchDesc": "マクロ分析のために最新の Web ソースを読む",+ "macroResearchDesc": "マクロ分析とA株市場の見通し","analyzeBrokerExport": "ブローカー出力を分析",- "analyzeBrokerExportDesc": "同花顺/东财/富途/汎用 CSV を解析 — 保有日数、勝率、損益比、時間別分布",+ "analyzeBrokerExportDesc": "同花順・Eastmoney・Futu などの CSV を読み込み、保有日数、勝率、損益比、時間帯別パターンを分析","diagnoseBehavior": "行動バイアスを診断","diagnoseBehaviorDesc": "処分効果、過剰取引、モメンタム追従、アンカリング — 重大度と数値エビデンス","checkConnector": "選択中のコネクタを確認",@@ -211,7 +211,7 @@"shadowDelta": "取り残している利益はいくら?","shadowDeltaDesc": "シャドウ戦略をバックテストし、実際損益との差分を要因分解","shadowReport": "シャドウレポートを生成",- "shadowReportDesc": "8 セクションの HTML/PDF — エクイティカーブ、市場別 Sharpe、要因分解ウォーターフォール",+ "shadowReportDesc": "共有可能な8部構成のレポート。口座価値の推移、リスク調整後リターン、利益の発生源を掲載","crossMarketPortfolioPrompt": "000001.SZ、600519.SH、000858.SZ でリスクパリティポートフォリオを構築し、2024年通年でバックテスト、等ウェイトベンチマークと比較","btcMacdPrompt": "000001.SZ の5分足でMACD戦略をバックテスト: 快線12、慢線26、シグナル9、直近30日","usTechMaxDivPrompt": "600519.SH、000858.SZ、601318.SH、000001.SZ、600036.SH の最大分散ポートフォリオを2024年通年でバックテスト",@@ -261,10 +261,10 @@"provider": "プロバイダー","refresh": "更新","modelName": "モデル名",- "baseUrl": "Base URL",+ "baseUrl": "ベース URL","apiAuthKey": "API 認証キー","loading": "読み込み中…",- "temperature": "Temperature",+ "temperature": "温度","timeoutSeconds": "タイムアウト(秒)","maxRetries": "最大リトライ回数","reasoningEffort": "推論強度",@@ -367,7 +367,7 @@"title": "QVeris ツールマーケットプレイス","subtitle": "無料の公開データを既定のまま使い、必要なときだけ QVeris の有料実行を有効にします。","enabled": "QVeris 有料ルートを有効化",- "baseUrl": "Base URL",+ "baseUrl": "ベース URL","apiKey": "API キー","apiKeyPlaceholder": "空欄で現在のキーを保持","mode": "モード",@@ -389,8 +389,8 @@"agent": {"connectionLostReconnect": "接続が切断されました。再接続しています…","connectionRestored": "接続が復元されました",- "agentWorking": "エージェントが作業中です…",- "reasoning": "推論中…",+ "agentWorking": "作業を始めています…",+ "reasoning": "じっくり考えています…","running": "実行中","newMessages": "新しいメッセージ","newResearchGoal": "新しいリサーチ目標",@@ -404,7 +404,7 @@"save": "保存","cancelGoal": "目標をキャンセル","describeGoal": "このセッションに添付するリサーチ目標を記述してください",- "placeholder": "例: 000001.SZ のデュアル MA クロスオーバー戦略を作成し、2024 年をバックテストする",+ "placeholder": "例: 000001.SZ で単純な移動平均戦略を2024年について検証する","send": "送信","messageInputLabel": "エージェントへのメッセージ","inputHint": "Enter で送信 · Shift+Enter で改行",@@ -423,8 +423,8 @@"researchGoalUpdated": "リサーチ目標を更新しました","failedToUpdateGoal": "目標の更新に失敗しました。","failedToLoadGoal": "目標の読み込みに失敗しました。",- "cancelRequestSent": "キャンセルリクエストを送信しました",- "cancelFailed": "キャンセルに失敗しました",+ "cancelRequestSent": "停止しています…",+ "cancelFailed": "停止できませんでした。もう一度お試しください。","connectorHalted": "コネクタランタイムが停止しました","failedToHaltConnector": "コネクタランタイムの停止に失敗しました。","cancelledFromUI": "Web UI からキャンセルされました。",@@ -450,7 +450,27 @@"goalModeChip": "リサーチ目標","continueGoalMessage": "リサーチ目標を続行: {{goal}}","loadEarlier": "以前のメッセージを読み込む",- "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use."+ "authRequired": "リモート API へのアクセスには API キーが必要です。設定で追加するか、ローカルのみで使用する場合はバックエンドを localhost で実行してください。",+ "followUpPlaceholder": "この実行について質問する — 例:なぜドローダウンがこれほど深いのですか?",+ "continuePrompt": "停止したところから続行してください。",+ "doneMarker": "実行完了",+ "backgroundRunComplete": "別のセッションで実行が完了しました。",+ "activity": {+ "verbs": {+ "readingMarketData": "市場データを読み込み中",+ "writingStrategy": "戦略を作成中",+ "runningBacktest": "バックテストを実行中",+ "validatingNumbers": "数値を再確認中",+ "working": "処理中"+ },+ "done": "完了",+ "stopped": "あなたが停止しました",+ "timeout": "{{elapsed}} 経過したため待機を停止しました — 実行はまだ完了処理中の可能性があります",+ "failed": "失敗",+ "steps": "{{count}} ステップ",+ "continue": "続行",+ "reattach": "再接続"+ }},"runDetail": {"title": "実行詳細",@@ -465,7 +485,7 @@"downloadTradesCsv": "トレード CSV をダウンロード","downloadMetricsCsv": "メトリクス CSV をダウンロード","noChartData": "チャートデータがありません",- "noChartDataDesc": "バックテストエンジンが価格データを生成していない可能性があります。artifacts/ ディレクトリを確認してください。",+ "noChartDataDesc": "この実行では価格データが保存されなかったため、チャートは表示できません。下の指標は引き続き有効です。","symbol": "シンボル","showOnly": "のみ表示","addSymbol": "シンボルを追加",@@ -500,7 +520,9 @@"noValidationPayload": "検証ペイロードは記録されていません。","noArtifactChecksums": "成果物チェックサムは記録されていません。","noCodeFiles": "コードファイルがありません。",- "fullReport": "完全なレポート →"+ "fullReport": "完全なレポート →",+ "unknown": "不明",+ "noneRecorded": "記録なし"},"compare": {"title": "戦略比較",@@ -535,7 +557,7 @@"correlation": {"title": "相関行列","assetCodes": "アセットコード",- "assetCodesHint": "カンマ区切りのティッカーシンボル(例: BTC-USDT,ETH-USDT,AAPL,SPY)",+ "assetCodesHint": "カンマ区切りのティッカーシンボル(例: 000001.SZ,600519.SH,000858.SZ)","windowDays": "ウィンドウ(日)","method": "手法","compute": "計算",@@ -552,13 +574,13 @@"regimeExitThreshold": "終了しきい値"},"alphaZoo": {- "title": "Alpha Zoo",+ "title": "Alpha ファクターライブラリ","prebuiltAlpha": "5 つの Zoo にまたがる {{count}} 個の事前構築クォント Alpha","prebuiltAlphaLoading": "5 つの Zoo にまたがる事前構築クォント Alpha","browseDesc": "Qlib、Kakushadze 101、GTJA 191、学術的アノマリー文献、および PIT セーフなファンダメンタルズから、フォーミュラ駆動のクロスセクションシグナルを参照できます。任意の Alpha をクリックして式とソースコードを読むか、ベンチを実行して特定のユニバースと期間で Zoo 全体をスコアリングできます。","search": "検索","searchPlaceholder": "ID またはニックネームで絞り込み…",- "zoo": "Zoo",+ "zoo": "ファクターライブラリ","allZoos": "すべての Zoo","theme": "テーマ","allThemes": "すべてのテーマ",@@ -630,7 +652,7 @@"predictiveHalfLifeTitle": "予測半減期: シグナルのエッジが減衰するまでの取引日数","id": "ID","icSampleCount": "IC サンプル数",- "alpha": "Alpha",+ "alpha": "アルファ","alphaComparisonRanking": "Alpha 比較ランキング","skippedPre": "スキップ:","zooCardTitle": {@@ -680,7 +702,16 @@"icMean": "IC 平均","icPositiveRatio": "IC > 0 比率","icCount": "サンプル数"- }+ },+ "failedToLoadAlphas": "アルファ一覧の読み込みに失敗しました",+ "selectAlphaForCompare": "{{id}} を比較対象に選択",+ "failedToLoadAlpha": "アルファの読み込みに失敗しました",+ "failedToStartBench": "ベンチマークテストを開始できませんでした",+ "singleAssetHint": "{{message}} 有意なクロスセクション IC を得るには、`sp500` または `csi300` をお試しください。",+ "benchStreamError": "ベンチマークテストのストリームエラー",+ "job": "ジョブ {{id}}…",+ "compareStreamError": "比較ストリームエラー",+ "failedToStartComparison": "比較を開始できませんでした"},"validation": {"noData": "検証データがありません。",@@ -697,7 +728,7 @@"ciIncludes0": "CI に 0 を含む","bootstrapDesc": "日次リターンを {{n}} 回リサンプリングして {{pct}} 信頼区間を推定します。","observedSharpe": "観測 Sharpe",- "ci": "{{pct}} CI",+ "ci": "{{pct}} 信頼区間","medianSharpe": "Sharpe 中央値","probSharpePositive": "P(Sharpe > 0)","walkForward": "ウォークフォワード分析",@@ -750,12 +781,12 @@},"swarmStatus": {"agents": "{{done}}/{{total}} エージェント",- "layer": "レイヤー {{current}}/{{total}}",+ "layer": "第 {{current}} ラウンド(全 {{total}} ラウンド)","agent": "エージェント","status": "ステータス","tool": "ツール","time": "時間",- "iters": "反復",+ "iters": "パス","output": "出力","waitingForEvents": "エージェントイベントを待機中...","teamStarting": "チームを起動中です。数秒で最初の進捗が届きます…",@@ -787,18 +818,18 @@"confirmTitle": "マンデートのコミットを確認","confirmDescription": "コミットすると、以下の上限でエージェントに取引権限が即座に付与されます。","confirmButton": "確認してコミット",- "maxPerOrder": "≤{{amount}}/order",- "expiresOn": "expires {{date}}",- "accountSummary": "{{broker}} · {{type}} account · funded by {{fundedBy}}",- "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}"+ "maxPerOrder": "1注文あたり {{amount}} 以下",+ "expiresOn": "有効期限: {{date}}",+ "accountSummary": "{{broker}}・{{type}}口座・資金提供元: {{fundedBy}}",+ "adjustRequestMessage": "マンデート案「{{label}}」(選択肢 {{ordinal}})への調整依頼: {{text}}"},"messageBubble": {"copied": "コピーしました","copy": "コピー",- "timeoutHint": "Timed out. Simplify the strategy or use fewer assets.",- "apiFailedHint": "API request failed. Try again shortly.",- "executionFailedHint": "Execution failed. Try again.",- "retry": "Try again"+ "timeoutHint": "タイムアウトしました。戦略を簡略化するか、銘柄数を減らしてください。",+ "apiFailedHint": "API リクエストに失敗しました。しばらくしてから再試行してください。",+ "executionFailedHint": "実行に失敗しました。もう一度お試しください。",+ "retry": "再試行"},"pineViewer": {"pineScript": "Pine Script v6",@@ -819,7 +850,7 @@"featureAgent": "AI エージェント","featureAgentDesc": "ReAct 推論による自然言語の戦略生成","featureBacktest": "内蔵バックテスト",- "featureBacktestDesc": "A株、米国/HK、暗号資産をカバーする 7 つのデータソース",+ "featureBacktestDesc": "A株のクオンツ分析に対応する複数のデータソース","featureStreaming": "リアルタイムストリーミング","featureStreamingDesc": "エージェントの思考、ツール呼び出し、反復を観察","featureReplay": "戦略リプレイ",@@ -835,24 +866,24 @@"step4Desc": "上限を明示したトレーディングマンデートを任意で承認 — 確認なしに注文が入ることはありません。"},"errorBoundary": {- "somethingWrong": "問題が発生しました"+ "somethingWrong": "問題が発生しました。ページを再読み込みして続行してください。"},"charts": {- "noPriceData": "価格データがありません",- "noCorrelationData": "相関データがありません",- "noEquityData": "エクイティデータがありません"+ "noPriceData": "このシンボルにはまだ価格データがありません",+ "noCorrelationData": "比較するシンボルを2つ以上選択してください",+ "noEquityData": "口座価値の推移はまだありません。先にバックテストを実行してください"},"toolProgress": {"step": "ステップ {{step}} · {{tool}}",- "toolsRunning": "実行中のツール: {{count}}",- "toolsCompleted": "完了したツール: {{count}}",+ "toolsRunning": "{{count}} 件を同時に処理中",+ "toolsCompleted": "{{count}} ステップ完了","more": "… ほか {{count}} 件","etaSeconds": "残り約 {{seconds}} 秒","earlier": "ほか {{count}} 件(完了済み)"},"swarm": {"assemblingTeam": "チームを編成中…",- "preparingLayers": "実行レイヤーを準備中…",+ "preparingLayers": "実行する順番を調整しています…","agentProgress": "スウォームエージェントの進捗","status": {"waiting": "待機中",@@ -880,107 +911,107 @@"good": "良好","poor": "要注意","gloss": {- "total_return": "How much the strategy gained or lost over the full test period.",- "annual_return": "The strategy's return scaled to a typical one-year period.",- "sharpe": "Return earned per unit of total risk, where higher is generally better.",- "max_drawdown": "The largest peak-to-trough loss during the test period.",- "win_rate": "The share of completed trades that made a profit.",- "trade_count": "The number of trades completed during the test period.",- "calmar": "Annual return divided by maximum drawdown, balancing growth against worst loss.",- "sortino": "Return earned per unit of downside risk, where higher is generally better.",- "profit_loss_ratio": "The average winning trade compared with the average losing trade.",- "max_consecutive_loss": "The longest run of losing trades in a row.",- "benchmark_return": "The return of the comparison benchmark over the same period.",- "excess_return": "How much the strategy outperformed or underperformed its benchmark.",- "information_ratio": "Excess return earned per unit of tracking error against the benchmark.",- "final_value": "The portfolio value at the end of the test period.",- "avg_holding_days": "The average number of days each position stayed open."+ "total_return": "テスト期間全体で戦略がどれだけ利益または損失を出したかを示します。",+ "annual_return": "戦略のリターンを標準的な1年間に換算した値です。",+ "sharpe": "総リスク1単位あたりのリターンで、一般に高いほど良好です。",+ "max_drawdown": "テスト期間中にピークからボトムまで下落した最大幅です。",+ "win_rate": "完了した取引のうち利益が出た取引の割合です。",+ "trade_count": "テスト期間中に完了した取引の件数です。",+ "calmar": "年率リターンを最大ドローダウンで割った値で、成長と最大損失のバランスを示します。",+ "sortino": "下方リスク1単位あたりのリターンで、一般に高いほど良好です。",+ "profit_loss_ratio": "平均的な勝ち取引の利益と、平均的な負け取引の損失を比較した値です。",+ "max_consecutive_loss": "損失取引が連続した最長回数です。",+ "benchmark_return": "同じ期間における比較対象ベンチマークのリターンです。",+ "excess_return": "戦略がベンチマークをどれだけ上回った、または下回ったかを示します。",+ "information_ratio": "ベンチマークに対するトラッキングエラー1単位あたりの超過リターンです。",+ "final_value": "テスト期間終了時のポートフォリオ価値です。",+ "avg_holding_days": "各ポジションを保有していた平均日数です。"}},"tools": {- "add_goal_evidence": "Add goal evidence",- "alpha_bench": "Benchmark alpha factors",- "alpha_compare": "Compare alpha factors",- "alpha_zoo": "Browse alpha library",- "analyze_image": "Analyze the image",- "analyze_trade_journal": "Analyze trade journal",- "background_run": "Start background task",- "backtest": "Run the backtest",- "bash": "Run command",- "cancel_background": "Cancel background task",- "check_background": "Check background task",- "compact": "Summarize conversation",- "create_hypothesis": "Create research hypothesis",- "delete_skill": "Delete custom skill",- "edit_file": "Edit code",- "extract_shadow_strategy": "Extract shadow strategy",- "factor_analysis": "Analyze factors",- "financial_rigor": "Verify financial analysis",- "generate_backtest_config": "Generate backtest config",- "get_block_trades": "Fetch block trades",- "get_dragon_tiger": "Fetch dragon-tiger list",- "get_financial_statements": "Fetch financial statements",- "get_fund_flow": "Fetch fund flow",- "get_fundamentals": "Fetch fundamentals",- "get_lockup_expiry": "Fetch lockup expiries",- "get_macro_series": "Fetch macro series",- "get_margin_trading": "Fetch margin trading",- "get_market_data": "Fetch market data",- "get_northbound_flow": "Fetch northbound flow",- "get_options_chain": "Fetch options chain",- "get_research_goal": "View research goal",- "get_research_reports": "Fetch research reports",- "get_sec_filings": "Fetch SEC filings",- "get_sector_info": "Fetch sector data",- "get_shareholder_count": "Fetch shareholder count",- "get_stock_news": "Fetch stock news",- "get_stock_profile": "Fetch stock profile",- "iwencai_search": "Search iWenCai",- "link_autopilot_backtest": "Link autopilot backtest",- "link_backtest": "Link hypothesis backtest",- "load_skill": "Load strategy knowledge",- "options_pricing": "Price options",- "patch_skill": "Update custom skill",- "pattern": "Detect chart patterns",- "portfolio_risk_xray": "X-ray portfolio risk",- "propose_mandate_profiles": "Propose trading mandates",- "qveris_execute": "Execute QVeris action",- "qveris_inspect": "Inspect QVeris action",- "qveris_search": "Search QVeris",- "read_document": "Read document",- "read_file": "Read file",- "read_url": "Read webpage",- "remember": "Remember this",- "render_shadow_report": "Create shadow report",- "report_audit": "Audit research report",- "run_research_autopilot": "Run research autopilot",- "run_shadow_backtest": "Run shadow backtest",- "run_swarm": "Convene the team",- "save_skill": "Save custom skill",- "scaffold_signal_engine": "Build signal engine",- "scan_shadow_signals": "Scan shadow signals",- "screen_market": "Screen market",- "sdm_decay_scan": "Scan strategy decay",- "sdm_register": "Register strategy",- "sdm_status": "Check strategy status",- "search_hypotheses": "Search hypotheses",- "search_symbol": "Search symbols",- "session_search": "Search past sessions",- "skill_file": "Read skill file",- "start_research_goal": "Start research goal",- "trading_account": "View broker account",- "trading_cancel_order": "Cancel broker order",- "trading_check": "Check broker connection",- "trading_connections": "List broker connections",- "trading_history": "View trade history",- "trading_orders": "View broker orders",- "trading_place_order": "Place broker order",- "trading_positions": "View broker positions",- "trading_quote": "Fetch broker quote",- "trading_select_connection": "Select broker connection",- "update_hypothesis": "Update research hypothesis",- "update_research_goal_status": "Update goal status",- "web_search": "Search the web",- "write_file": "Generate code"+ "add_goal_evidence": "目標にエビデンスを追加",+ "alpha_bench": "アルファファクターをベンチマーク",+ "alpha_compare": "アルファファクターを比較",+ "alpha_zoo": "アルファライブラリを閲覧",+ "analyze_image": "画像を分析",+ "analyze_trade_journal": "トレードジャーナルを分析",+ "background_run": "バックグラウンドタスクを開始",+ "backtest": "バックテストを実行",+ "bash": "コマンドを実行",+ "cancel_background": "バックグラウンドタスクをキャンセル",+ "check_background": "バックグラウンドタスクを確認",+ "compact": "会話を要約",+ "create_hypothesis": "リサーチ仮説を作成",+ "delete_skill": "カスタムスキルを削除",+ "edit_file": "コードを編集",+ "extract_shadow_strategy": "シャドウ戦略を抽出",+ "factor_analysis": "ファクターを分析",+ "financial_rigor": "財務分析を検証",+ "generate_backtest_config": "バックテスト設定を生成",+ "get_block_trades": "大口取引を取得",+ "get_dragon_tiger": "龍虎榜を取得",+ "get_financial_statements": "財務諸表を取得",+ "get_fund_flow": "資金フローを取得",+ "get_fundamentals": "ファンダメンタルズを取得",+ "get_lockup_expiry": "ロックアップ解除予定を取得",+ "get_macro_series": "マクロ時系列を取得",+ "get_margin_trading": "信用取引データを取得",+ "get_market_data": "市場データを取得",+ "get_northbound_flow": "北向き資金フローを取得",+ "get_options_chain": "オプションチェーンを取得",+ "get_research_goal": "リサーチ目標を表示",+ "get_research_reports": "リサーチレポートを取得",+ "get_sec_filings": "SEC 提出書類を取得",+ "get_sector_info": "セクターデータを取得",+ "get_shareholder_count": "株主数を取得",+ "get_stock_news": "銘柄ニュースを取得",+ "get_stock_profile": "銘柄情報を取得",+ "iwencai_search": "iWenCai を検索",+ "link_autopilot_backtest": "自動リサーチにバックテストを関連付け",+ "link_backtest": "仮説にバックテストを関連付け",+ "load_skill": "戦略知識を読み込む",+ "options_pricing": "オプションを評価",+ "patch_skill": "カスタムスキルを更新",+ "pattern": "チャートパターンを検出",+ "portfolio_risk_xray": "ポートフォリオリスクを精査",+ "propose_mandate_profiles": "取引マンデートを提案",+ "qveris_execute": "QVeris アクションを実行",+ "qveris_inspect": "QVeris アクションを確認",+ "qveris_search": "QVeris を検索",+ "read_document": "ドキュメントを読む",+ "read_file": "ファイルを読む",+ "read_url": "Web ページを読む",+ "remember": "記憶に保存",+ "render_shadow_report": "シャドウレポートを作成",+ "report_audit": "リサーチレポートを監査",+ "run_research_autopilot": "自動リサーチを実行",+ "run_shadow_backtest": "シャドウバックテストを実行",+ "run_swarm": "チームを招集",+ "save_skill": "カスタムスキルを保存",+ "scaffold_signal_engine": "シグナルエンジンを構築",+ "scan_shadow_signals": "シャドウシグナルをスキャン",+ "screen_market": "市場をスクリーニング",+ "sdm_decay_scan": "戦略の劣化をスキャン",+ "sdm_register": "戦略を登録",+ "sdm_status": "戦略の状態を確認",+ "search_hypotheses": "仮説を検索",+ "search_symbol": "シンボルを検索",+ "session_search": "過去のセッションを検索",+ "skill_file": "スキルファイルを読む",+ "start_research_goal": "リサーチ目標を開始",+ "trading_account": "ブローカー口座を表示",+ "trading_cancel_order": "ブローカー注文をキャンセル",+ "trading_check": "ブローカー接続を確認",+ "trading_connections": "ブローカー接続を一覧表示",+ "trading_history": "取引履歴を表示",+ "trading_orders": "ブローカー注文を表示",+ "trading_place_order": "ブローカーに注文",+ "trading_positions": "ブローカーのポジションを表示",+ "trading_quote": "ブローカーのクォートを取得",+ "trading_select_connection": "ブローカー接続を選択",+ "update_hypothesis": "リサーチ仮説を更新",+ "update_research_goal_status": "目標の状態を更新",+ "web_search": "Web を検索",+ "write_file": "コードを生成"}}diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 2a35e349f..038766834 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -1,18 +1,18 @@{"app": {- "version": "v0.1.11"+ "version": "v0.1.12"},"layout": {"home": "홈","agent": "에이전트","runtime": "런타임","reports": "리포트",- "alphaZoo": "Alpha Zoo",+ "alphaZoo": "알파 라이브러리","settings": "설정","correlation": "상관 행렬","sessions": "세션","newChat": "새 채팅",- "noSessions": "세션이 없습니다",+ "noSessions": "아직 채팅이 없습니다. +를 눌러 시작하세요","confirm": "확인","cancel": "취소","rename": "이름 변경",@@ -60,7 +60,7 @@"profileType": "프로필 유형","recognized": "인식됨","unknown": "알 수 없음",- "mandate": "Mandate",+ "mandate": "운용 권한","account": "계좌","unrecorded": "기록 없음","expiry": "만료",@@ -83,42 +83,42 @@"leverageSuffix": "배 레버리지","never": "없음","ago": "전",- "notConfigured": "Not configured",- "readyToVerify": "Ready to verify",- "connectedReadOnly": "Connected · Read-only",- "connectionFailed": "Connection failed",- "verifyConnection": "Verify connection",- "retry": "Retry",- "credentialSource": "Credential source",+ "notConfigured": "설정되지 않음",+ "readyToVerify": "검증 가능",+ "connectedReadOnly": "연결됨 · 읽기 전용",+ "connectionFailed": "연결 실패",+ "verifyConnection": "연결 검증",+ "retry": "다시 시도",+ "credentialSource": "인증 정보 출처","sdk": "SDK",- "configDeclared": "Config-declared",- "connectorStatusUnavailable": "Status unavailable",- "connectedAccessUnknown": "Connected · Access unknown",- "missingLongbridgeVariables": "Missing configuration. Configure these variables in agent/.env and recreate the service:",- "sdkConnectorProfile": "Direct SDK connector · read-only profile",- "connectionDetails": "Connection details",- "environment": "Environment",- "environmentIdentity": "Declared environment",- "capabilities": "Capabilities",- "capabilityAccount": "Account",- "capabilityPositions": "positions",- "capabilityOpenOrders": "open orders",- "capabilityQuotes": "quotes",- "capabilityHistory": "history",- "readOnly": "read-only",- "accessUnknown": "access unknown",- "diagnostics": "Diagnostics",- "lastChecked": "Last checked",- "errorCode": "Error code",- "installed": "Installed",- "notInstalled": "Not installed",- "connectorVerifyFailed": "Connection verification failed.",- "diagnosticCredentialsPartial": "Credentials are incomplete. Configure all required variables and recreate the service.",- "diagnosticCredentialsConflict": "Credential sources conflict. Keep one complete source, then retry.",- "diagnosticSdkMissing": "The Longbridge SDK is not installed in the backend service.",- "diagnosticAuthenticationFailed": "Authentication failed. Check the configured credentials.",- "diagnosticNetworkUnreachable": "The Longbridge service is unreachable. Check network access and retry.",- "diagnosticBrokerError": "The broker rejected the read-only verification request. Retry or check backend logs."+ "configDeclared": "설정 파일에 선언됨",+ "connectorStatusUnavailable": "상태를 확인할 수 없음",+ "connectedAccessUnknown": "연결됨 · 접근 권한 불명",+ "missingLongbridgeVariables": "설정이 누락되었습니다. agent/.env에 다음 변수를 설정하고 서비스를 다시 생성하세요:",+ "sdkConnectorProfile": "SDK 직접 연결 · 읽기 전용 프로필",+ "connectionDetails": "연결 세부 정보",+ "environment": "환경",+ "environmentIdentity": "설정에 선언된 환경",+ "capabilities": "사용 가능 기능",+ "capabilityAccount": "계정",+ "capabilityPositions": "포지션",+ "capabilityOpenOrders": "미체결 주문",+ "capabilityQuotes": "시세",+ "capabilityHistory": "내역",+ "readOnly": "읽기 전용",+ "accessUnknown": "접근 권한 불명",+ "diagnostics": "진단",+ "lastChecked": "마지막 확인",+ "errorCode": "오류 코드",+ "installed": "설치됨",+ "notInstalled": "설치되지 않음",+ "connectorVerifyFailed": "연결 검증에 실패했습니다.",+ "diagnosticCredentialsPartial": "인증 정보가 불완전합니다. 필수 변수를 모두 설정하고 서비스를 다시 생성하세요.",+ "diagnosticCredentialsConflict": "인증 정보 출처가 충돌합니다. 완전한 출처 하나만 남긴 뒤 다시 시도하세요.",+ "diagnosticSdkMissing": "백엔드 서비스에 Longbridge SDK가 설치되어 있지 않습니다.",+ "diagnosticAuthenticationFailed": "인증에 실패했습니다. 설정된 인증 정보를 확인하세요.",+ "diagnosticNetworkUnreachable": "Longbridge 서비스에 연결할 수 없습니다. 네트워크 연결을 확인하고 다시 시도하세요.",+ "diagnosticBrokerError": "브로커가 읽기 전용 검증 요청을 거부했습니다. 다시 시도하거나 백엔드 로그를 확인하세요."},"reports": {"badge": "리포트",@@ -151,14 +151,14 @@},"connection": {"reconnecting": "다시 연결하는 중…",- "disconnected": "연결이 끊겼습니다",- "reload": "Reload"+ "disconnected": "연결이 끊겼습니다. 다시 연결하려면 페이지를 새로고침하세요.",+ "reload": "새로고침"},"welcome": {"categories": {- "multiMarketBacktest": "멀티 마켓 백테스트",+ "multiMarketBacktest": "A주 백테스트","researchAnalysis": "리서치 & 분석",- "swarmTeams": "Swarm 팀",+ "swarmTeams": "AI 애널리스트 팀","docWebResearch": "문서 & 웹 리서치","tradeJournal": "매매 일지","tradingConnectors": "트레이딩 커넥터",@@ -167,26 +167,26 @@},"examples": {"crossMarketPortfolio": "3개 종목 포트폴리오 배분",- "crossMarketPortfolioDesc": "A주 포트폴리오 리스크 패리티 최적화",+ "crossMarketPortfolioDesc": "3개 A주에 자금을 배분해 각 종목의 위험을 같게 맞춘 뒤 동일 비중 포트폴리오와 비교","btcMacd": "A주 MACD 전략","btcMacdDesc": "분 단위 데이터 기반 A주 MACD 전략 백테스트",- "usTechMaxDiv": "블루칩 최대 분산",- "usTechMaxDivDesc": "블루칩 최대 분산 포트폴리오",+ "usTechMaxDiv": "우량주 위험 분산",+ "usTechMaxDivDesc": "한 종목에 위험이 쏠리지 않도록 최대분산 최적화로 5개 우량주의 비중을 배분","multiFactorAlpha": "멀티 팩터 Alpha 모델",- "multiFactorAlphaDesc": "300개 종목에 대한 IC 가중 팩터 합성",- "optionsGreeks": "옵션 리스크 지표(Greeks)",- "optionsGreeksDesc": "Black-Scholes 가격 모델, Delta/Gamma/Theta/Vega 분석",+ "multiFactorAlphaDesc": "300개 종목에서 4개 종목선정 신호를 결합하고 과거 수익률 예측력(IC)에 따라 가중",+ "optionsGreeks": "옵션 위험 점검(Greeks)",+ "optionsGreeksDesc": "옵션 가격을 계산하고 주가·시간·변동성 변화에 얼마나 민감한지(Greeks) 확인","valueCommittee": "가치투자 위원회","valueCommitteeDesc": "Buffett / Munger / Duan Yongping / Li Lu 네 관점으로 한 종목 토론","valueCommitteePrompt": "run_swarm으로 value_investing_committee 프리셋을 사용해 Tencent (00700.HK)를 분석하세요: Buffett은 moat와 가격, Munger는 역발상, Duan Yongping은 사업과 경영진, Li Lu는 10년 확실성을 평가하고 의장이 합의점과 모순을 종합하세요","bottleneckHunter": "공급망 병목 헌터",- "bottleneckHunterDesc": "슈퍼 트렌드의 Layer 2/3 병목에서 숨은 승자를 찾기",+ "bottleneckHunterDesc": "큰 흐름에 꼭 필요한 소규모 공급업체를 찾고 아직 저평가되어 있는지 확인","bottleneckHunterPrompt": "bottleneck-hunter 스킬을 사용해 AI 인프라(광통신 / 레이저 / InP 기판)의 Layer 2/3 공급망 병목 기회를 찾고, 각 병목을 점수화한 뒤 밸류에이션 게이트를 통과하는 후보 기업을 나열하세요","thesisTracker": "투자 테제 트래커",- "thesisTrackerDesc": "보유 종목에 대해 5문장 테제 + 레드라인 + 밸류에이션 앵커 작성",+ "thesisTrackerDesc": "보유 이유를 5문장으로 정리하고 매도를 결정할 레드라인도 설정","thesisTrackerPrompt": "thesis-tracker 스킬로 Kweichow Moutai (600519.SH)의 투자 테제를 작성하세요: 5문장 핵심 테제, 반증 가능한 가정, 레드라인, 밸류에이션 앵커를 financial_rigor로 검증하세요","valuationCheck": "고평가 여부 점검(PE/PB/ROE)",- "valuationCheckDesc": "정확한 십진 연산으로 PE / PB / ROE / 시가총액 검증 (부동소수점 오차 없음)",+ "valuationCheckDesc": "PE / PB / ROE / 시가총액을 세부 단위까지 다시 계산하고 3가지 성장 시나리오로 스트레스 테스트","valuationCheckPrompt": "financial_rigor 도구로 Kweichow Moutai의 밸류에이션을 검증하세요: 가격 1500, EPS 68.6, 주당순자산 180으로 PE, PB, ROE를 정확히 계산하고, 3년 3개 시나리오(성장률 12%/8%/0%, PE 22/18/14)도 계산하세요","investmentCommittee": "매수냐 매도냐, 위원회 토론","investmentCommitteeDesc": "멀티 에이전트 토론: 롱 vs 숏, 리스크 리뷰, PM 결정",@@ -195,9 +195,9 @@"earningsReport": "실적 보고서 PDF 분석","earningsReportDesc": "PDF를 업로드하고 재무 관련 질문을 하세요","macroResearch": "웹 리서치: 매크로 전망",- "macroResearchDesc": "매크로 분석을 위해 최신 웹 소스를 읽기",+ "macroResearchDesc": "거시경제 분석과 A주 시장 전망","analyzeBrokerExport": "내 브로커 내보내기 분석",- "analyzeBrokerExportDesc": "동화순/동차/푸도우/범용 CSV 파싱 — 보유일수, 승률, 손익비, 시간대별 분포",+ "analyzeBrokerExportDesc": "Tonghuashun·Eastmoney·Futu 및 일반 CSV를 읽어 보유일, 승률, 손익비, 시간대별 패턴 분석","diagnoseBehavior": "내 행동 편향 진단","diagnoseBehaviorDesc": "처분 효과, 과매매, 모멘텀 추격, 닻 고정 — 심각도 + 수치 증거","checkConnector": "선택한 커넥터 확인",@@ -211,10 +211,10 @@"shadowDelta": "놓치고 있는 수익은 얼마일까?","shadowDeltaDesc": "섀도우 전략을 백테스트하고 실제 PnL과의 차이를 귀인 분석","shadowReport": "섀도우 리포트 생성",- "shadowReportDesc": "8개 섹션 HTML/PDF — 자산 곡선, 시장별 Sharpe, 귀인 워터폴",+ "shadowReportDesc": "공유 가능한 8개 섹션 보고서로 계정 가치 추이, 위험조정 수익률, 수익 발생 원인을 제공","crossMarketPortfolioPrompt": "000001.SZ, 600519.SH, 000858.SZ로 리스크 패리티 포트폴리오를 구축하고 2024년 전체 백테스트하여 등가중 벤치마크와 비교","btcMacdPrompt": "000001.SZ 5분봉으로 MACD 전략 백테스트: 단기선12, 장기선26, 시그널9, 최근 30일",- "usTechMaxDivPrompt": "600519.SH, 600858.SZ, 601318.SH, 000001.SZ, 600036.SH의 최대 분산 포트폴리오를 2024년 전체 백테스트",+ "usTechMaxDivPrompt": "600519.SH, 000858.SZ, 601318.SH, 000001.SZ, 600036.SH의 최대 분산 포트폴리오를 2024년 전체 백테스트","multiFactorAlphaPrompt": "CSI 300 구성 종목에서 모멘텀, 반전, 거래량, 변동성을 활용한 다중 요인 Alpha 모델을 IC 가중 요인 합성으로 구축하고 2023-2024년 백테스트","optionsGreeksPrompt": "Black-Scholes로 옵션 Greeks 계산: 현물=100, 행사가=105, 무위험 이자율=3%, 변동성=25%, 만기=90일, Delta/Gamma/Theta/Vega 분석","investmentCommitteePrompt": "[Swarm 팀 모드] investment_committee 프리셋을 사용하여 현재 시장 환경에서 600519.SH를 롱할지 숏할지 평가",@@ -261,10 +261,10 @@"provider": "프로바이더","refresh": "새로 고침","modelName": "모델 이름",- "baseUrl": "Base URL",+ "baseUrl": "기본 URL","apiAuthKey": "API 인증 키","loading": "불러오는 중…",- "temperature": "Temperature",+ "temperature": "온도","timeoutSeconds": "타임아웃(초)","maxRetries": "최대 재시도 횟수","reasoningEffort": "추론 강도",@@ -367,7 +367,7 @@"title": "QVeris 도구 마켓플레이스","subtitle": "무료 공개 데이터 경로를 기본으로 두고, 필요할 때만 QVeris 유료 실행을 켭니다.","enabled": "QVeris 유료 경로 활성화",- "baseUrl": "Base URL",+ "baseUrl": "기본 URL","apiKey": "API 키","apiKeyPlaceholder": "비우면 현재 키 유지","mode": "모드",@@ -389,8 +389,8 @@"agent": {"connectionLostReconnect": "연결이 끊겼습니다. 재연결 중…","connectionRestored": "연결이 복원되었습니다",- "agentWorking": "에이전트가 작업 중입니다…",- "reasoning": "추론 중…",+ "agentWorking": "작업을 시작하고 있습니다…",+ "reasoning": "차근차근 검토하고 있습니다…","running": "실행 중","newMessages": "새 메시지","newResearchGoal": "새 리서치 목표",@@ -404,7 +404,7 @@"save": "저장","cancelGoal": "목표 취소","describeGoal": "이 세션에 첨부할 리서치 목표를 설명하세요",- "placeholder": "예: 000001.SZ에 대한 듀얼 MA 크로스오버 전략을 만들고 2024년 백테스트 수행",+ "placeholder": "예: 000001.SZ의 단순 이동평균 전략을 2024년 구간에서 테스트","send": "보내기","messageInputLabel": "에이전트에게 보낼 메시지","inputHint": "Enter로 전송 · Shift+Enter로 줄바꿈",@@ -423,8 +423,8 @@"researchGoalUpdated": "리서치 목표가 업데이트되었습니다","failedToUpdateGoal": "목표 업데이트에 실패했습니다.","failedToLoadGoal": "목표 불러오기에 실패했습니다.",- "cancelRequestSent": "취소 요청을 보냈습니다",- "cancelFailed": "취소 실패",+ "cancelRequestSent": "중지하는 중…",+ "cancelFailed": "중지하지 못했습니다. 다시 시도해 주세요.","connectorHalted": "커넥터 런타임이 정지되었습니다","failedToHaltConnector": "커넥터 런타임 정지에 실패했습니다.","cancelledFromUI": "Web UI에서 취소되었습니다.",@@ -450,7 +450,27 @@"goalModeChip": "리서치 목표","continueGoalMessage": "리서치 목표 계속: {{goal}}","loadEarlier": "이전 메시지 불러오기",- "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use."+ "authRequired": "원격 API에 접근하려면 API 키가 필요합니다. 설정에서 추가하거나, 로컬에서만 사용할 경우 백엔드를 localhost에서 실행하세요.",+ "followUpPlaceholder": "이 실행에 대해 질문하세요 — 예: 낙폭이 왜 이렇게 큰가요?",+ "continuePrompt": "중단한 지점부터 계속하세요.",+ "doneMarker": "실행 완료",+ "backgroundRunComplete": "다른 세션의 실행이 완료되었습니다.",+ "activity": {+ "verbs": {+ "readingMarketData": "시장 데이터 불러오는 중",+ "writingStrategy": "전략 작성 중",+ "runningBacktest": "백테스트 실행 중",+ "validatingNumbers": "수치 재확인 중",+ "working": "처리 중"+ },+ "done": "완료",+ "stopped": "사용자가 중지함",+ "timeout": "{{elapsed}} 후 대기를 중단했습니다 — 실행은 아직 마무리 중일 수 있습니다",+ "failed": "실패",+ "steps": "{{count}}단계",+ "continue": "계속",+ "reattach": "다시 연결"+ }},"runDetail": {"title": "실행 상세",@@ -465,7 +485,7 @@"downloadTradesCsv": "거래 CSV 다운로드","downloadMetricsCsv": "지표 CSV 다운로드","noChartData": "차트 데이터가 없습니다",- "noChartDataDesc": "백테스트 엔진이 가격 데이터를 생성하지 않았을 수 있습니다. artifacts/ 디렉터리를 확인하세요.",+ "noChartDataDesc": "이 실행에서는 가격 데이터가 저장되지 않아 차트를 표시할 수 없습니다. 아래 지표는 여전히 유효합니다.","symbol": "심볼","showOnly": "만 표시","addSymbol": "심볼 추가",@@ -500,7 +520,9 @@"noValidationPayload": "기록된 검증 페이로드가 없습니다.","noArtifactChecksums": "기록된 아티팩트 체크섬이 없습니다.","noCodeFiles": "코드 파일이 없습니다.",- "fullReport": "전체 리포트 →"+ "fullReport": "전체 리포트 →",+ "unknown": "알 수 없음",+ "noneRecorded": "기록 없음"},"compare": {"title": "전략 비교",@@ -535,7 +557,7 @@"correlation": {"title": "상관 행렬","assetCodes": "자산 코드",- "assetCodesHint": "쉼표로 구분된 티커 심볼(예: BTC-USDT,ETH-USDT,AAPL,SPY)",+ "assetCodesHint": "쉼표로 구분된 티커 심볼(예: 000001.SZ,600519.SH,000858.SZ)","windowDays": "윈도우(일)","method": "방법","compute": "계산",@@ -552,13 +574,13 @@"regimeExitThreshold": "이탈 임계값"},"alphaZoo": {- "title": "Alpha Zoo",+ "title": "알파 팩터 라이브러리","prebuiltAlpha": "5개 Zoo에 걸친 {{count}}개의 사전 구축 퀀트 Alpha","prebuiltAlphaLoading": "5개 Zoo에 걸친 사전 구축 퀀트 Alpha","browseDesc": "Qlib, Kakushadze 101, GTJA 191, 학술 이상 현상 문헌 및 PIT-safe 펀더멘털에서 포뮬러 기반의 횡단면 시그널을 살펴보세요. Alpha를 클릭하여 공식과 소스 코드를 확인하거나, 벤치를 실행하여 특정 유니버스와 기간에 대해 Zoo 전체를 스코어링할 수 있습니다.","search": "검색","searchPlaceholder": "ID 또는 별명으로 필터…",- "zoo": "Zoo",+ "zoo": "팩터 라이브러리","allZoos": "모든 Zoo","theme": "테마","allThemes": "모든 테마",@@ -630,7 +652,7 @@"predictiveHalfLifeTitle": "예측 반감기: 시그널의 엣지가 감소하기까지의 거래일 수","id": "ID","icSampleCount": "IC 샘플 수",- "alpha": "Alpha",+ "alpha": "알파","alphaComparisonRanking": "Alpha 비교 랭킹","skippedPre": "건너뜀:","zooCardTitle": {@@ -680,7 +702,16 @@"icMean": "IC 평균","icPositiveRatio": "IC > 0 비율","icCount": "샘플 수"- }+ },+ "failedToLoadAlphas": "알파 목록을 불러오지 못했습니다",+ "selectAlphaForCompare": "비교할 {{id}} 선택",+ "failedToLoadAlpha": "알파를 불러오지 못했습니다",+ "failedToStartBench": "벤치마크 테스트를 시작하지 못했습니다",+ "singleAssetHint": "{{message}} 유의미한 횡단면 IC를 얻으려면 `sp500` 또는 `csi300`을 사용해 보세요.",+ "benchStreamError": "벤치마크 테스트 스트림 오류",+ "job": "작업 {{id}}…",+ "compareStreamError": "비교 스트림 오류",+ "failedToStartComparison": "비교를 시작하지 못했습니다"},"validation": {"noData": "검증 데이터가 없습니다.",@@ -697,7 +728,7 @@"ciIncludes0": "CI에 0 포함","bootstrapDesc": "일별 수익률을 {{n}}번 리샘플링하여 {{pct}} 신뢰구간을 추정합니다.","observedSharpe": "관측 Sharpe",- "ci": "{{pct}} CI",+ "ci": "{{pct}} 신뢰구간","medianSharpe": "Sharpe 중앙값","probSharpePositive": "P(Sharpe > 0)","walkForward": "워크포워드 분석",@@ -750,12 +781,12 @@},"swarmStatus": {"agents": "{{done}}/{{total}} 에이전트",- "layer": "레이어 {{current}}/{{total}}",+ "layer": "{{total}}개 라운드 중 {{current}}번째","agent": "에이전트","status": "상태","tool": "도구","time": "시간",- "iters": "반복",+ "iters": "패스","output": "출력","waitingForEvents": "에이전트 이벤트 대기 중...","teamStarting": "팀을 시작하는 중입니다. 몇 초 후 첫 진행 상황이 도착합니다…",@@ -787,18 +818,18 @@"confirmTitle": "mandate 커밋 확인","confirmDescription": "커밋하면 아래 한도로 에이전트에게 즉시 거래 권한이 부여됩니다.","confirmButton": "확인 후 커밋",- "maxPerOrder": "≤{{amount}}/order",- "expiresOn": "expires {{date}}",- "accountSummary": "{{broker}} · {{type}} account · funded by {{fundedBy}}",- "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}"+ "maxPerOrder": "주문당 {{amount}} 이하",+ "expiresOn": "{{date}} 만료",+ "accountSummary": "{{broker}} · {{type}} 계정 · 자금 제공: {{fundedBy}}",+ "adjustRequestMessage": "운용 권한 제안 \"{{label}}\"(옵션 {{ordinal}})에 대한 조정 요청: {{text}}"},"messageBubble": {"copied": "복사됨","copy": "복사",- "timeoutHint": "Timed out. Simplify the strategy or use fewer assets.",- "apiFailedHint": "API request failed. Try again shortly.",- "executionFailedHint": "Execution failed. Try again.",- "retry": "Try again"+ "timeoutHint": "시간이 초과되었습니다. 전략을 단순화하거나 자산 수를 줄여 주세요.",+ "apiFailedHint": "API 요청에 실패했습니다. 잠시 후 다시 시도해 주세요.",+ "executionFailedHint": "실행에 실패했습니다. 다시 시도해 주세요.",+ "retry": "다시 시도"},"pineViewer": {"pineScript": "Pine Script v6",@@ -819,7 +850,7 @@"featureAgent": "AI 에이전트","featureAgentDesc": "ReAct 추론 기반의 자연어 전략 생성","featureBacktest": "내장 백테스트",- "featureBacktestDesc": "A주, 미국/HK, 암호화폐를 아우르는 7개 데이터 소스",+ "featureBacktestDesc": "A주 퀀트 분석을 지원하는 다양한 데이터 소스","featureStreaming": "실시간 스트리밍","featureStreamingDesc": "에이전트의 사고, 도구 호출, 반복 과정을 지켜보세요","featureReplay": "전략 리플레이",@@ -835,24 +866,24 @@"step4Desc": "한도가 명시된 거래 mandate를 선택적으로 승인하세요 — 확인 없이는 어떤 주문도 실행되지 않습니다."},"errorBoundary": {- "somethingWrong": "문제가 발생했습니다"+ "somethingWrong": "문제가 발생했습니다. 계속하려면 페이지를 새로고침하세요."},"charts": {- "noPriceData": "가격 데이터 없음",- "noCorrelationData": "상관 데이터 없음",- "noEquityData": "자산 데이터 없음"+ "noPriceData": "이 종목에는 아직 가격 데이터가 없습니다",+ "noCorrelationData": "비교할 종목을 두 개 이상 선택하세요",+ "noEquityData": "계정 가치 곡선이 아직 없습니다. 먼저 백테스트를 실행하세요"},"toolProgress": {"step": "단계 {{step}} · {{tool}}",- "toolsRunning": "실행 중인 도구: {{count}}",- "toolsCompleted": "완료된 도구: {{count}}",+ "toolsRunning": "{{count}}개 작업을 동시에 처리 중",+ "toolsCompleted": "{{count}}단계 완료","more": "… 외 {{count}}개","etaSeconds": "약 {{seconds}}초 남음","earlier": "이전 {{count}}개"},"swarm": {"assemblingTeam": "팀 구성 중…",- "preparingLayers": "실행 레이어 준비 중…",+ "preparingLayers": "먼저 진행할 순서를 정하는 중…","agentProgress": "스웜 에이전트 진행 상황","status": {"waiting": "대기 중",@@ -880,107 +911,107 @@"good": "양호","poor": "미흡","gloss": {- "total_return": "How much the strategy gained or lost over the full test period.",- "annual_return": "The strategy's return scaled to a typical one-year period.",- "sharpe": "Return earned per unit of total risk, where higher is generally better.",- "max_drawdown": "The largest peak-to-trough loss during the test period.",- "win_rate": "The share of completed trades that made a profit.",- "trade_count": "The number of trades completed during the test period.",- "calmar": "Annual return divided by maximum drawdown, balancing growth against worst loss.",- "sortino": "Return earned per unit of downside risk, where higher is generally better.",- "profit_loss_ratio": "The average winning trade compared with the average losing trade.",- "max_consecutive_loss": "The longest run of losing trades in a row.",- "benchmark_return": "The return of the comparison benchmark over the same period.",- "excess_return": "How much the strategy outperformed or underperformed its benchmark.",- "information_ratio": "Excess return earned per unit of tracking error against the benchmark.",- "final_value": "The portfolio value at the end of the test period.",- "avg_holding_days": "The average number of days each position stayed open."+ "total_return": "전체 테스트 기간 동안 전략에서 발생한 이익 또는 손실입니다.",+ "annual_return": "전략 수익률을 일반적인 1년 기간으로 환산한 값입니다.",+ "sharpe": "전체 위험 한 단위당 얻은 수익으로, 일반적으로 높을수록 좋습니다.",+ "max_drawdown": "테스트 기간에 고점에서 저점까지 하락한 최대 폭입니다.",+ "win_rate": "완료된 거래 중 수익을 낸 거래의 비율입니다.",+ "trade_count": "테스트 기간에 완료된 거래 수입니다.",+ "calmar": "연환산 수익률을 최대 낙폭으로 나눈 값으로, 성장과 최악의 손실 간 균형을 보여줍니다.",+ "sortino": "하방 위험 한 단위당 얻은 수익으로, 일반적으로 높을수록 좋습니다.",+ "profit_loss_ratio": "평균 수익 거래의 이익과 평균 손실 거래의 손실을 비교한 값입니다.",+ "max_consecutive_loss": "손실 거래가 연속으로 이어진 최장 횟수입니다.",+ "benchmark_return": "같은 기간의 비교 벤치마크 수익률입니다.",+ "excess_return": "전략이 벤치마크를 얼마나 상회하거나 하회했는지 보여줍니다.",+ "information_ratio": "벤치마크 대비 추적오차 한 단위당 얻은 초과수익입니다.",+ "final_value": "테스트 기간 종료 시점의 포트폴리오 가치입니다.",+ "avg_holding_days": "각 포지션을 유지한 평균 일수입니다."}},"tools": {- "add_goal_evidence": "Add goal evidence",- "alpha_bench": "Benchmark alpha factors",- "alpha_compare": "Compare alpha factors",- "alpha_zoo": "Browse alpha library",- "analyze_image": "Analyze the image",- "analyze_trade_journal": "Analyze trade journal",- "background_run": "Start background task",- "backtest": "Run the backtest",- "bash": "Run command",- "cancel_background": "Cancel background task",- "check_background": "Check background task",- "compact": "Summarize conversation",- "create_hypothesis": "Create research hypothesis",- "delete_skill": "Delete custom skill",- "edit_file": "Edit code",- "extract_shadow_strategy": "Extract shadow strategy",- "factor_analysis": "Analyze factors",- "financial_rigor": "Verify financial analysis",- "generate_backtest_config": "Generate backtest config",- "get_block_trades": "Fetch block trades",- "get_dragon_tiger": "Fetch dragon-tiger list",- "get_financial_statements": "Fetch financial statements",- "get_fund_flow": "Fetch fund flow",- "get_fundamentals": "Fetch fundamentals",- "get_lockup_expiry": "Fetch lockup expiries",- "get_macro_series": "Fetch macro series",- "get_margin_trading": "Fetch margin trading",- "get_market_data": "Fetch market data",- "get_northbound_flow": "Fetch northbound flow",- "get_options_chain": "Fetch options chain",- "get_research_goal": "View research goal",- "get_research_reports": "Fetch research reports",- "get_sec_filings": "Fetch SEC filings",- "get_sector_info": "Fetch sector data",- "get_shareholder_count": "Fetch shareholder count",- "get_stock_news": "Fetch stock news",- "get_stock_profile": "Fetch stock profile",- "iwencai_search": "Search iWenCai",- "link_autopilot_backtest": "Link autopilot backtest",- "link_backtest": "Link hypothesis backtest",- "load_skill": "Load strategy knowledge",- "options_pricing": "Price options",- "patch_skill": "Update custom skill",- "pattern": "Detect chart patterns",- "portfolio_risk_xray": "X-ray portfolio risk",- "propose_mandate_profiles": "Propose trading mandates",- "qveris_execute": "Execute QVeris action",- "qveris_inspect": "Inspect QVeris action",- "qveris_search": "Search QVeris",- "read_document": "Read document",- "read_file": "Read file",- "read_url": "Read webpage",- "remember": "Remember this",- "render_shadow_report": "Create shadow report",- "report_audit": "Audit research report",- "run_research_autopilot": "Run research autopilot",- "run_shadow_backtest": "Run shadow backtest",- "run_swarm": "Convene the team",- "save_skill": "Save custom skill",- "scaffold_signal_engine": "Build signal engine",- "scan_shadow_signals": "Scan shadow signals",- "screen_market": "Screen market",- "sdm_decay_scan": "Scan strategy decay",- "sdm_register": "Register strategy",- "sdm_status": "Check strategy status",- "search_hypotheses": "Search hypotheses",- "search_symbol": "Search symbols",- "session_search": "Search past sessions",- "skill_file": "Read skill file",- "start_research_goal": "Start research goal",- "trading_account": "View broker account",- "trading_cancel_order": "Cancel broker order",- "trading_check": "Check broker connection",- "trading_connections": "List broker connections",- "trading_history": "View trade history",- "trading_orders": "View broker orders",- "trading_place_order": "Place broker order",- "trading_positions": "View broker positions",- "trading_quote": "Fetch broker quote",- "trading_select_connection": "Select broker connection",- "update_hypothesis": "Update research hypothesis",- "update_research_goal_status": "Update goal status",- "web_search": "Search the web",- "write_file": "Generate code"+ "add_goal_evidence": "목표에 증거 추가",+ "alpha_bench": "알파 팩터 벤치마크",+ "alpha_compare": "알파 팩터 비교",+ "alpha_zoo": "알파 라이브러리 탐색",+ "analyze_image": "이미지 분석",+ "analyze_trade_journal": "매매 일지 분석",+ "background_run": "백그라운드 작업 시작",+ "backtest": "백테스트 실행",+ "bash": "명령 실행",+ "cancel_background": "백그라운드 작업 취소",+ "check_background": "백그라운드 작업 확인",+ "compact": "대화 요약",+ "create_hypothesis": "리서치 가설 생성",+ "delete_skill": "사용자 스킬 삭제",+ "edit_file": "코드 편집",+ "extract_shadow_strategy": "섀도우 전략 추출",+ "factor_analysis": "팩터 분석",+ "financial_rigor": "재무 분석 검증",+ "generate_backtest_config": "백테스트 설정 생성",+ "get_block_trades": "대량매매 조회",+ "get_dragon_tiger": "용호방 조회",+ "get_financial_statements": "재무제표 조회",+ "get_fund_flow": "자금 흐름 조회",+ "get_fundamentals": "펀더멘털 조회",+ "get_lockup_expiry": "보호예수 해제 일정 조회",+ "get_macro_series": "거시경제 시계열 조회",+ "get_margin_trading": "신용거래 데이터 조회",+ "get_market_data": "시장 데이터 조회",+ "get_northbound_flow": "북향 자금 흐름 조회",+ "get_options_chain": "옵션 체인 조회",+ "get_research_goal": "리서치 목표 보기",+ "get_research_reports": "리서치 보고서 조회",+ "get_sec_filings": "SEC 공시 조회",+ "get_sector_info": "섹터 데이터 조회",+ "get_shareholder_count": "주주 수 조회",+ "get_stock_news": "종목 뉴스 조회",+ "get_stock_profile": "종목 정보 조회",+ "iwencai_search": "iWenCai 검색",+ "link_autopilot_backtest": "자동 리서치에 백테스트 연결",+ "link_backtest": "가설에 백테스트 연결",+ "load_skill": "전략 지식 불러오기",+ "options_pricing": "옵션 가격 계산",+ "patch_skill": "사용자 스킬 업데이트",+ "pattern": "차트 패턴 감지",+ "portfolio_risk_xray": "포트폴리오 위험 정밀 분석",+ "propose_mandate_profiles": "거래 운용 권한 제안",+ "qveris_execute": "QVeris 작업 실행",+ "qveris_inspect": "QVeris 작업 점검",+ "qveris_search": "QVeris 검색",+ "read_document": "문서 읽기",+ "read_file": "파일 읽기",+ "read_url": "웹페이지 읽기",+ "remember": "기억에 저장",+ "render_shadow_report": "섀도우 보고서 생성",+ "report_audit": "리서치 보고서 감사",+ "run_research_autopilot": "자동 리서치 실행",+ "run_shadow_backtest": "섀도우 백테스트 실행",+ "run_swarm": "팀 소집",+ "save_skill": "사용자 스킬 저장",+ "scaffold_signal_engine": "신호 엔진 구축",+ "scan_shadow_signals": "섀도우 신호 스캔",+ "screen_market": "시장 종목 선별",+ "sdm_decay_scan": "전략 성능 저하 스캔",+ "sdm_register": "전략 등록",+ "sdm_status": "전략 상태 확인",+ "search_hypotheses": "가설 검색",+ "search_symbol": "종목 코드 검색",+ "session_search": "과거 세션 검색",+ "skill_file": "스킬 파일 읽기",+ "start_research_goal": "리서치 목표 시작",+ "trading_account": "브로커 계정 보기",+ "trading_cancel_order": "브로커 주문 취소",+ "trading_check": "브로커 연결 확인",+ "trading_connections": "브로커 연결 목록",+ "trading_history": "거래 내역 보기",+ "trading_orders": "브로커 주문 보기",+ "trading_place_order": "브로커 주문 제출",+ "trading_positions": "브로커 포지션 보기",+ "trading_quote": "브로커 시세 조회",+ "trading_select_connection": "브로커 연결 선택",+ "update_hypothesis": "리서치 가설 업데이트",+ "update_research_goal_status": "목표 상태 업데이트",+ "web_search": "웹 검색",+ "write_file": "코드 생성"}}diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 087e1e0a7..b8d4eda3c 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -450,7 +450,27 @@"goalModeChip": "研究目标","continueGoalMessage": "继续研究目标:{{goal}}","loadEarlier": "加载更早的消息",- "authRequired": "远程 API 访问需要 API 密钥。请在设置中添加密钥,或在 localhost 上运行后端以仅限本地使用。"+ "authRequired": "远程 API 访问需要 API 密钥。请在设置中添加密钥,或在 localhost 上运行后端以仅限本地使用。",+ "followUpPlaceholder": "追问本次运行——例如,为什么回撤这么深?",+ "continuePrompt": "从刚才停止的地方继续。",+ "doneMarker": "运行完成",+ "backgroundRunComplete": "另一个会话中的运行已完成。",+ "activity": {+ "verbs": {+ "readingMarketData": "正在读取市场数据",+ "writingStrategy": "正在编写策略",+ "runningBacktest": "正在运行回测",+ "validatingNumbers": "正在复核数据",+ "working": "正在处理"+ },+ "done": "完成",+ "stopped": "已由你停止",+ "timeout": "等待 {{elapsed}} 后已停止——运行可能仍在后台完成",+ "failed": "失败",+ "steps": "{{count}} 个步骤",+ "continue": "继续",+ "reattach": "重新连接"+ }},"runDetail": {"title": "运行详情",@@ -500,7 +520,9 @@"noValidationPayload": "暂无验证数据记录。","noArtifactChecksums": "暂无制品校验和记录。","noCodeFiles": "暂无代码文件。",- "fullReport": "完整报告 →"+ "fullReport": "完整报告 →",+ "unknown": "未知",+ "noneRecorded": "未记录"},"compare": {"title": "策略对比",@@ -680,7 +702,16 @@"icMean": "IC 均值","icPositiveRatio": "IC > 0 期占比","icCount": "样本数量"- }+ },+ "failedToLoadAlphas": "加载 Alpha 列表失败",+ "selectAlphaForCompare": "选择 {{id}} 用于对比",+ "failedToLoadAlpha": "加载 Alpha 失败",+ "failedToStartBench": "启动基准测试失败",+ "singleAssetHint": "{{message}} 请尝试使用 `sp500` 或 `csi300`,以获得有意义的横截面 IC。",+ "benchStreamError": "基准测试数据流错误",+ "job": "任务 {{id}}…",+ "compareStreamError": "对比数据流错误",+ "failedToStartComparison": "启动对比失败"},"validation": {"noData": "暂无验证数据。",diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 36ad75c80..e41321a22 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -1,15 +1,16 @@import { useTranslation } from 'react-i18next';-import { useEffect, useRef, useState, useMemo, useCallback, type FormEvent } from "react";+import { useEffect, useRef, useState, useMemo, useCallback } from "react";import { useSearchParams } from "react-router";-import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target, ChevronDown, Pencil, Check, Play, OctagonX, Activity, Ban, CheckCircle2, Landmark } from "lucide-react";+import { ArrowDown } from "lucide-react";import { toast } from "sonner";import {useAgentStore,+ type AgentActivity,type AgentMessageMeta,type StoredAgentMessage,} from "@/stores/agent";import { useSSE } from "@/hooks/useSSE";-import { ApiError, AUTH_REQUIRED_MESSAGE, api, isAuthRequiredError, type GoalSnapshot, type MandateProposal, type MandateCommitted, type LiveAction, type LiveHalted, type LiveStatus } from "@/lib/api";+import { ApiError, AUTH_REQUIRED_MESSAGE, api, isAuthRequiredError, type GoalSnapshot, type MandateProposal, type MandateCommitted, type LiveAction, type LiveHalted } from "@/lib/api";import { isReportWorthyRun } from "@/lib/runReports";import type { AgentMessage, SwarmRunStatus, ToolCallEntry } from "@/types/agent";import { AgentAvatar } from "@/components/chat/AgentAvatar";@@ -17,10 +18,20 @@ import { WelcomeScreen } from "@/components/chat/WelcomeScreen";import { MarkdownContent, MessageBubble } from "@/components/chat/MessageBubble";import { ThinkingTimeline } from "@/components/chat/ThinkingTimeline";import { ConversationTimeline } from "@/components/chat/ConversationTimeline";-import { ToolProgressIndicator } from "@/components/chat/ToolProgressIndicator";+import { ActivityLine } from "@/components/chat/ActivityLine";import { MandateProposalCard } from "@/components/chat/MandateProposalCard";-import { RunnerStatus } from "@/components/chat/RunnerStatus";import { SwarmStatusCard } from "@/components/chat/SwarmStatusCard";+import {+ Composer,+ type ComposerAttachment,+ type ComposerHandle,+} from "@/components/chat/Composer";+import { GoalPanel } from "@/components/chat/GoalPanel";+import {+ LiveActionChip,+ LiveRuntimePanel,+ type LiveRuntimePanelHandle,+} from "@/components/chat/LiveRuntimePanel";import {applySwarmEvent,buildSwarmStatusFromStarted,@@ -78,14 +89,8 @@ function toolProgressKey(callId: string | undefined, tool: string): string {// i18n hook for Agent component — used inside the component below// (declared at module scope for helper usage is fine since t() reads from i18n singleton)-/** Poll cadence for the shared `GET /live/status` snapshot. */-const LIVE_STATUS_POLL_INTERVAL_MS = 15_000;const STREAM_FLUSH_INTERVAL_MS = 80;const TIMELINE_WINDOW_SIZE = 160;-const CONNECTOR_CHECK_PROMPT =- "List my trading connector profiles, show which one is selected, then check that selected connector. If it is not ready, tell me exactly what setup step is missing. Do not place or modify orders.";-const CONNECTOR_PORTFOLIO_PROMPT =- "Use the selected trading connector profile to summarize my account, positions, concentration, cash, and portfolio risk. Do not place or modify orders.";const SWARM_PROMPT_PREFIX ="[Swarm Team Mode] Use the swarm tool to assemble the best specialist team for this task. Auto-select the most appropriate preset.\n\n";const GOAL_KICKOFF_PREFIX = [@@ -148,6 +153,7 @@ interface ProposalItem {kind: "proposal";timestamp: number;proposal: MandateProposal;+ committed: MandateCommitted | null;}interface LiveActionItem {kind: "live_action";@@ -156,104 +162,14 @@ interface LiveActionItem {}type LiveItem = ProposalItem | LiveActionItem;-function normalizeBrokerScope(broker: string | null | undefined): string | null {- const normalized = broker?.trim().toLowerCase();- return normalized || null;-}--function isGlobalLiveHalt(halt: LiveHalted | null): boolean {- return halt != null && normalizeBrokerScope(halt.broker) == null;-}--function haltScopeStillActive(halt: LiveHalted, status: LiveStatus): boolean {- const broker = normalizeBrokerScope(halt.broker);- if (!broker) return status.global_halted;- return status.global_halted || status.brokers.some((item) => (- normalizeBrokerScope(item.auth.broker) === broker && item.halted- ));-}--function liveActionStyle(kind: string): { icon: typeof Activity; tone: string } {- switch (kind) {- case "order_rejected":- case "breach":- return { icon: Ban, tone: "border-amber-500/40 bg-amber-500/5 text-amber-600 dark:text-amber-400" };- case "halt_tripped":- return { icon: OctagonX, tone: "border-destructive/40 bg-destructive/5 text-destructive" };- case "mandate_committed":- case "halt_cleared":- return { icon: CheckCircle2, tone: "border-emerald-500/40 bg-emerald-500/5 text-emerald-600 dark:text-emerald-400" };- default:- return { icon: Activity, tone: "border-sky-500/40 bg-sky-500/5 text-sky-600 dark:text-sky-400" };- }-}--function liveActionLabel(action: LiveAction): string {- return action.kind.replace(/_/g, " ");-}--function LiveActionChip({ action }: { action: LiveAction }) {- const { t } = useTranslation();- const { icon: Icon, tone } = liveActionStyle(action.kind);- return (- <div className="flex gap-3">- <AgentAvatar />- <div className="flex-1 min-w-0">- <div className={["inline-flex max-w-full flex-wrap items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs", tone].join(" ")}>- <Icon className="h-3 w-3 shrink-0" />- <span className="shrink-0 font-medium uppercase tracking-wide text-[10px]">{t("agent.runtimeBadge")}</span>- <span className="shrink-0 font-medium">{liveActionLabel(action)}</span>- {action.intent_normalized && (- <span className="truncate text-foreground/80">· {action.intent_normalized}</span>- )}- {action.outcome && (- <span className="shrink-0 font-mono text-[10px] text-muted-foreground">· {action.outcome}</span>- )}- {action.remote_tool && (- <span className="shrink-0 font-mono text-[10px] text-muted-foreground">· {action.remote_tool}</span>- )}- {action.error && <span className="truncate text-destructive">· {action.error}</span>}- </div>- </div>- </div>- );-}-function isCriterionStatusMet(status: string): boolean {return !["", "pending", "open", "unsatisfied"].includes(status.toLowerCase());}-function getGoalProgress(snapshot: GoalSnapshot | null): {- met: number;- total: number;- label: string;- metLabel: string;- evidenceTotal: number;-} {- const total = snapshot?.criteria.length ?? 0;- const met = snapshot?.criteria.filter((item) => criterionCovered(snapshot, item)).length ?? 0;- const evidenceTotal = snapshot?.evidence_count ?? 0;- return {- met,- total,- label: total > 0 ? `${met}/${total}` : "",- metLabel: total > 0 ? `${met}/${total} met` : "",- evidenceTotal,- };-}--function statusLabel(status: string): string {- return status.replace(/_/g, " ");-}-function isTerminalGoalStatus(status: string): boolean {return ["complete", "cancelled", "blocked", "superseded", "usage_limited"].includes(status);}-function criterionIndexLabel(index: number): string {- return String(index + 1);-}-function criterionEvidenceCount(snapshot: GoalSnapshot, criterionId: string): number {return snapshot.evidence.filter((item) => item.criterion_id === criterionId).length;}@@ -262,12 +178,6 @@ function criterionCovered(snapshot: GoalSnapshot, criterion: GoalSnapshot["critereturn isCriterionStatusMet(criterion.status) || criterionEvidenceCount(snapshot, criterion.criterion_id) > 0;}-function latestGoalEvidence(snapshot: GoalSnapshot) {- return [...snapshot.evidence]- .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())- .slice(0, 2);-}-function goalKickoffPrompt(objective: string): string {return `${GOAL_KICKOFF_PREFIX}${objective}`;}@@ -289,12 +199,11 @@ function goalContinuePrompt(snapshot: GoalSnapshot): string {/* ---------- Component ---------- */export function Agent() {const { t } = useTranslation();- const [input, setInput] = useState("");const [searchParams, setSearchParams] = useSearchParams();const listRef = useRef<HTMLDivElement>(null);- const inputRef = useRef<HTMLTextAreaElement>(null);- const isComposingRef = useRef(false);- const lastCompositionEndRef = useRef(0);+ const composerRef = useRef<ComposerHandle>(null);+ const liveRuntimeRef = useRef<LiveRuntimePanelHandle>(null);+ const goalOpenRequestRef = useRef(0);const sseSessionRef = useRef<string | null>(null);const prevSseStatusRef = useRef<string>("disconnected");const genRef = useRef(0);@@ -316,44 +225,23 @@ export function Agent() {const replayCheckTimerRef = useRef(0);const smoothScrollingRef = useRef(false);const smoothScrollTimerRef = useRef(0);+ const titleBeforeCompletionRef = useRef<string | null>(null);+ const completedAttemptIdsRef = useRef<Set<string>>(new Set());- const [attachment, setAttachment] = useState<{ filename: string; filePath: string } | null>(null);- const [uploading, setUploading] = useState(false);- const [showUploadMenu, setShowUploadMenu] = useState(false);- const uploadMenuRef = useRef<HTMLDivElement>(null);- const fileInputRef = useRef<HTMLInputElement>(null);const [swarmPreset, setSwarmPreset] = useState<{ name: string; title: string } | null>(null);const [goalComposerActive, setGoalComposerActive] = useState(false);- const [goalDetailsOpen, setGoalDetailsOpen] = useState(false);const [goalSnapshot, setGoalSnapshot] = useState<GoalSnapshot | null>(null);- const [goalEditActive, setGoalEditActive] = useState(false);- const [goalEditValue, setGoalEditValue] = useState("");/* Connector runtime channel state (SPEC Consent §1/§4/§5) */const [liveItems, setLiveItems] = useState<LiveItem[]>([]);- const [committedMandates, setCommittedMandates] = useState<Record<string, MandateCommitted>>({});- const [liveHalted, setLiveHalted] = useState<LiveHalted | null>(null);- const [halting, setHalting] = useState(false);- /* Bumped to force an immediate live-status re-poll on a live event- * (commit / halt / resume / runner-affecting action) rather than waiting a tick. */- const [liveStatusRefresh, setLiveStatusRefresh] = useState(0);- /* Shared `GET /live/status` snapshot. Owned here (single poller) and passed down- * to RunnerStatus, so the global kill switch can be shown whenever connector runtime- * could be active out-of-band (CLI/another session), not only off in-session SSE- * items (audit M2: always-available global halt — SPEC Consent §4). */- const [liveStatus, setLiveStatus] = useState<LiveStatus | null>(null);- const [reasoningActive, setReasoningActive] = useState(false);const [visibleRowCount, setVisibleRowCount] = useState(TIMELINE_WINDOW_SIZE);const visibleRowsSessionRef = useRef<string | null>(null);- /* The status endpoint is not wired on every backend; a 404/501 hides the panel- * and removes status from the kill-switch visibility condition. */- const [liveStatusUnavailable, setLiveStatusUnavailable] = useState(false);const messages = useAgentStore(s => s.messages);const streamingText = useAgentStore(s => s.streamingText);const status = useAgentStore(s => s.status);const sessionId = useAgentStore(s => s.sessionId);- const toolCalls = useAgentStore(s => s.toolCalls);+ const activity = useAgentStore(s => s.activity);const swarmRuns = useAgentStore(s => s.swarmRuns);const sessionLoading = useAgentStore(s => s.sessionLoading);const previousStatusRef = useRef(status);@@ -411,7 +299,6 @@ export function Agent() {const pendingReasoning = pendingReasoningRef.current;pendingTextRef.current = "";pendingReasoningRef.current = null;- if (pendingReasoning !== null) setReasoningActive(pendingReasoning);if (pendingText) act().appendDelta(pendingText);if (pendingText || pendingReasoning !== null) scrollToBottom();return pendingText;@@ -436,26 +323,83 @@ export function Agent() {const clearStreamingView = useCallback(() => {cancelPendingStreamFlush();- setReasoningActive(false);act().clearStreaming();}, [cancelPendingStreamFlush]);- const resetComposerInput = useCallback(() => {- setInput("");- if (inputRef.current) inputRef.current.style.height = "auto";+ const archiveActivity = useCallback((+ terminalState: "stopped" | "timeout" | "failed" | "done",+ endedAt = Date.now(),+ ): AgentActivity | null => {+ const store = act();+ store.setActivityState(terminalState, endedAt);+ const finished = act().activity;+ if (!finished) return null;+ const [activityMessage] = buildToolTimelineMessages(finished.steps, {+ activity: finished,+ idPrefix: "live_",+ });+ useAgentStore.setState((state) => ({+ messages: [+ ...state.messages.filter(+ (message) => message.meta?.activity?.attemptId !== finished.attemptId,+ ),+ activityMessage,+ ],+ activity: null,+ toolCalls: [],+ }));+ return finished;}, []);- const fillComposer = useCallback((prompt: string) => {- setInput(prompt);- requestAnimationFrame(() => {- const composer = inputRef.current;- if (!composer) return;- composer.focus({ preventScroll: true });- composer.style.height = "auto";- composer.style.height = `${composer.scrollHeight}px`;+ const persistPartialAnswer = useCallback((+ attempt: AgentActivity | null,+ content: string,+ ) => {+ if (!attempt || !content.trim()) return;+ act().addMessage({+ id: `partial_${attempt.attemptId}`,+ type: "answer",+ content,+ meta: { partialAttemptId: attempt.attemptId },+ timestamp: Date.now(),});}, []);+ const markBackgroundCompletion = useCallback((+ completedSessionId: string,+ attemptId?: string,+ ) => {+ if (attemptId && completedAttemptIdsRef.current.has(attemptId)) return;+ if (attemptId) completedAttemptIdsRef.current.add(attemptId);+ if (document.hidden) {+ titleBeforeCompletionRef.current ??= document.title;+ document.title = `● ${t("agent.doneMarker" as never)}`;+ }+ if (act().sessionId !== completedSessionId) {+ toast.success(t("agent.backgroundRunComplete" as never));+ }+ }, [t]);++ useEffect(() => {+ const restoreTitle = () => {+ if (document.hidden || titleBeforeCompletionRef.current === null) return;+ document.title = titleBeforeCompletionRef.current;+ titleBeforeCompletionRef.current = null;+ };+ document.addEventListener("visibilitychange", restoreTitle);+ return () => {+ document.removeEventListener("visibilitychange", restoreTitle);+ if (titleBeforeCompletionRef.current !== null) {+ document.title = titleBeforeCompletionRef.current;+ titleBeforeCompletionRef.current = null;+ }+ };+ }, []);++ const fillComposer = useCallback((prompt: string) => {+ composerRef.current?.fill(prompt);+ }, []);+useEffect(() => {const previous = previousStatusRef.current;previousStatusRef.current = status;@@ -467,12 +411,11 @@ export function Agent() {if (active &&active !== document.body &&- active !== inputRef.current &&!active.closest("[data-agent-composer]")) {return;}- inputRef.current?.focus({ preventScroll: true });+ composerRef.current?.focus();});}}, [status]);@@ -522,10 +465,9 @@ export function Agent() {const loadGoalSnapshot = useCallback(async (sid?: string | null) => {const targetSession = sid || act().sessionId;+ goalOpenRequestRef.current = 0;if (!targetSession) {setGoalSnapshot(null);- setGoalDetailsOpen(false);- setGoalEditActive(false);return;}try {@@ -536,8 +478,6 @@ export function Agent() {if (act().sessionId !== targetSession) return;if (error instanceof ApiError && error.status === 404) {setGoalSnapshot(null);- setGoalDetailsOpen(false);- setGoalEditActive(false);} else {toast.error(error instanceof Error ? error.message : t('agent.failedToLoadGoal'));}@@ -558,6 +498,9 @@ export function Agent() {? buildToolTimelineMessages(m.tool_trail ?? [], {fallbackTimestamp: ts,idPrefix: `${m.message_id}_`,+ attemptId: m.linked_attempt_id || `${m.message_id}_attempt`,+ state: meta?.status === "failed" ? "failed" : "done",+ endedAt: ts,}): [];agentMsgs.push(...toolTimeline);@@ -639,10 +582,12 @@ export function Agent() {(message) => message.role === "assistant" && message.linked_attempt_id === attemptId,);if (completed) {+ act().clearStreamingSession(sid);+ markBackgroundCompletion(sid, attemptId);if (act().sessionId !== sid) return true;clearStreamingView();act().setStatus("idle");- useAgentStore.setState({ toolCalls: [] });+ useAgentStore.setState({ toolCalls: [], activity: null });await refreshSessionMessages(sid);return true;}@@ -652,7 +597,7 @@ export function Agent() {await new Promise<void>((resolve) => window.setTimeout(resolve, 800));}return false;- }, [clearStreamingView, refreshSessionMessages]);+ }, [clearStreamingView, markBackgroundCompletion, refreshSessionMessages]);const setupSSE = useCallback((sid: string) => {if (sseSessionRef.current === sid) return;@@ -663,22 +608,52 @@ export function Agent() {sseSessionRef.current = sid;const touch = () => { lastEventRef.current = Date.now(); };+ const identifyActivity = (+ data: Record<string, unknown>,+ state: "thinking" | "working" | "responding",+ ): boolean => {+ const store = act();+ const attemptId = String(data.attempt_id || "");+ if (attemptId && store.messages.some((message) => (+ message.meta?.activity?.attemptId === attemptId+ && ["stopped", "timeout"].includes(message.meta.activity.state)+ ))) {+ return false;+ }+ const current = store.activity;+ if (!current) {+ store.startActivity(attemptId || `pending-${Date.now()}`);+ } else if (+ attemptId &&+ current.attemptId !== attemptId &&+ current.attemptId.startsWith("pending-")+ ) {+ store.setActivityAttemptId(attemptId);+ } else if (attemptId && current.attemptId !== attemptId) {+ store.startActivity(attemptId);+ }+ act().setActivityState(state);+ return true;+ };connect(api.sseUrl(sid, { replay: "active" }), {text_delta: (d) => {touch();replayAttemptSeenRef.current = true;+ if (!identifyActivity(d, "responding")) return;if (act().status !== "streaming") act().setStatus("streaming");queueStreamUpdate(String(d.delta || ""), false);},- reasoning_delta: () => {+ reasoning_delta: (d) => {touch();replayAttemptSeenRef.current = true;+ if (!identifyActivity(d, "thinking")) return;queueStreamUpdate("", true);if (act().status !== "streaming") act().setStatus("streaming");},- stream_reset: () => {+ stream_reset: (d) => {touch();+ if (!identifyActivity(d, "thinking")) return;clearStreamingView();if (act().status !== "streaming") act().setStatus("streaming");scrollToBottom();@@ -688,6 +663,7 @@ export function Agent() {tool_call: (d) => {touch();replayAttemptSeenRef.current = true;+ if (!identifyActivity(d, "working")) return;queueStreamUpdate("", false);const toolName = String(d.tool || "");const callId = eventCallId(d);@@ -726,6 +702,7 @@ export function Agent() {tool_heartbeat: (d) => {touch();replayAttemptSeenRef.current = true;+ if (!identifyActivity(d, "working")) return;// Keep streaming state alive during long-running tools (swarm, backtest)if (act().status !== "streaming") act().setStatus("streaming");const toolName = String(d.tool || "");@@ -790,17 +767,19 @@ export function Agent() {scrollToBottom();},- "attempt.created": () => {+ "attempt.created": (d) => {touch();replayAttemptSeenRef.current = true;+ if (!identifyActivity(d, "thinking")) return;// Backend has created a new attempt — ensure streaming state is active// even if we connected mid-stream (SSE replay / page reload).if (act().status !== "streaming") act().setStatus("streaming");},- "attempt.started": () => {+ "attempt.started": (d) => {touch();replayAttemptSeenRef.current = true;+ if (!identifyActivity(d, "thinking")) return;// Backend has begun executing the attempt. Re-affirm streaming state// so the UI shows a working indicator for reconnects and fresh loads.if (act().status !== "streaming") act().setStatus("streaming");@@ -808,19 +787,40 @@ export function Agent() {"attempt.completed": async (d) => {touch();+ const attemptId = String(d.attempt_id || "");+ markBackgroundCompletion(sid, attemptId);+ if (act().sessionId !== sid) {+ act().clearStreamingSession(sid);+ return;+ }+ if (attemptId && act().messages.some(+ (message) => (+ message.meta?.activity?.attemptId === attemptId+ && message.meta.activity.state === "done"+ ),+ )) {+ clearStreamingView();+ act().setStatus("idle");+ return;+ }const streamedAnswer = act().streamingText + pendingTextRef.current;flushPendingStreamUpdate();- setReasoningActive(false);- const s = act();- // Build ThinkingTimeline summary from accumulated toolCalls- const completedTools = s.toolCalls;- if (completedTools.length > 0) {- for (const message of buildToolTimelineMessages(completedTools)) {- s.addMessage(message);- }+ if (!act().activity) {+ act().startActivity(attemptId || `completed-${Date.now()}`);+ } else if (attemptId && act().activity?.attemptId !== attemptId) {+ act().setActivityAttemptId(attemptId);}-- // Clear streaming text (don't create thinking message)+ const s = act();+ const completedTools = s.activity?.steps ?? s.toolCalls;+ const completedActivity = archiveActivity("done");+ const completedAttemptId = completedActivity?.attemptId || attemptId;+ useAgentStore.setState((state) => ({+ messages: state.messages.filter(+ (message) => message.meta?.partialAttemptId !== completedAttemptId,+ ),+ }));++ // Clear streaming text after freezing the durable activity summary.s.clearStreaming();// Add final answer@@ -842,7 +842,6 @@ export function Agent() {// The transcript is already complete. Drop transient state before the// optional report fetch so answer/tool progress never overlap.s.setStatus("idle");- useAgentStore.setState({ toolCalls: [] });scrollToBottom();// Show RunCompleteCard when the turn produced backtest metrics or a shadow report@@ -878,12 +877,39 @@ export function Agent() {"attempt.failed": (d) => {touch();+ const attemptId = String(d.attempt_id || "");+ if (act().sessionId !== sid) {+ act().clearStreamingSession(sid);+ return;+ }+ const archived = act().messages.find(+ (message) => message.meta?.activity?.attemptId === attemptId,+ )?.meta?.activity;+ if (archived?.state === "stopped") {+ act().setStatus("idle");+ return;+ }+ if (!act().activity && archived) {+ useAgentStore.setState((state) => ({+ messages: state.messages.map((message) => (+ message.meta?.activity?.attemptId === attemptId+ ? {+ ...message,+ meta: {+ ...message.meta,+ activity: { ...archived, state: "failed", endedAt: Date.now() },+ },+ }+ : message+ )),+ }));+ } else {+ if (!act().activity) act().startActivity(attemptId || `failed-${Date.now()}`);+ archiveActivity("failed");+ }clearStreamingView();act().addMessage({ id: "", type: "error", content: String(d.error || "Execution failed"), timestamp: Date.now() });act().setStatus("idle");- // Clear stale toolCalls so the next turn's running indicator doesn't- // briefly show the previous turn's progress before fresh events land.- useAgentStore.setState({ toolCalls: [] });scrollToBottom();},@@ -940,8 +966,6 @@ export function Agent() {const goal = (d.goal as GoalSnapshot["goal"] | undefined) ?? snapshot?.goal;if (goal && isTerminalGoalStatus(goal.status)) {setGoalSnapshot(null);- setGoalDetailsOpen(false);- setGoalEditActive(false);return;}if (snapshot) {@@ -955,7 +979,10 @@ export function Agent() {touch();const proposal = d as unknown as MandateProposal;if (!proposal.proposal_id || !Array.isArray(proposal.profiles)) return;- setLiveItems((items) => [...items, { kind: "proposal", timestamp: Date.now(), proposal }]);+ setLiveItems((items) => [+ ...items,+ { kind: "proposal", timestamp: Date.now(), proposal, committed: null },+ ]);scrollToBottom();},@@ -963,9 +990,13 @@ export function Agent() {touch();const committed = d as unknown as MandateCommitted;if (!committed.proposal_id) return;- setCommittedMandates((prev) => ({ ...prev, [committed.proposal_id as string]: committed }));+ setLiveItems((items) => items.map((item) => (+ item.kind === "proposal" && item.proposal.proposal_id === committed.proposal_id+ ? { ...item, committed }+ : item+ )));// A fresh mandate may bring up the runner; refresh the runtime panel now.- setLiveStatusRefresh((n) => n + 1);+ liveRuntimeRef.current?.handleMandateCommitted();scrollToBottom();},@@ -975,8 +1006,7 @@ export function Agent() {// Preemptive kill switch: the server has cancelled resting orders and may have// flattened positions (SPEC §7.5 #6). Reflect the halted state across surfaces;// the RunnerStatus panel re-polls so its per-broker rows show "halted".- setLiveHalted(halted);- setLiveStatusRefresh((n) => n + 1);+ liveRuntimeRef.current?.handleHalted(halted);toast.warning(t('agent.connectorHalted'));},@@ -985,8 +1015,7 @@ export function Agent() {// Kill switch cleared via a privileged surface action (SPEC Consent §4);// clear the halted banner and re-poll runtime status.void d;- setLiveHalted(null);- setLiveStatusRefresh((n) => n + 1);+ liveRuntimeRef.current?.handleResumed();toast.success(t('agent.connectionRestored'));},@@ -995,12 +1024,7 @@ export function Agent() {const action = d as unknown as LiveAction;if (!action.kind) return;setLiveItems((items) => [...items, { kind: "live_action", timestamp: Date.now(), action }]);- if (action.kind === "halt_tripped") setLiveHalted({ broker: action.broker, reason: action.intent_normalized });- if (action.kind === "halt_cleared") setLiveHalted(null);- // Mandate-affecting / runner-affecting actions should refresh the runtime panel.- if (["mandate_committed", "halt_tripped", "halt_cleared"].includes(action.kind)) {- setLiveStatusRefresh((n) => n + 1);- }+ liveRuntimeRef.current?.handleLiveAction(action);scrollToBottom();},@@ -1008,12 +1032,14 @@ export function Agent() {reconnect: (d) => { act().setSseStatus("reconnecting", Number(d.attempt ?? 0)); },});}, [+ archiveActivity,cancelPendingStreamFlush,clearStreamingView,connect,disconnect,flushPendingStreamUpdate,loadGoalSnapshot,+ markBackgroundCompletion,queueStreamUpdate,scrollToBottom,]);@@ -1027,9 +1053,7 @@ export function Agent() {doDisconnect();// Live-channel timeline items are per-session; clear on switch.setLiveItems([]);- setCommittedMandates({});- setLiveHalted(null);- setLiveStatusRefresh((n) => n + 1);+ liveRuntimeRef.current?.resetSession();if (curSid && curMsgs.length > 0) cacheSession(curSid, curMsgs);// Atomic switch: cache hit = instant, cache miss = show loading skeleton@@ -1061,50 +1085,15 @@ export function Agent() {genRef.current += 1;doDisconnect();setLiveItems([]);- setCommittedMandates({});- setLiveHalted(null);- setLiveStatusRefresh((n) => n + 1);+ liveRuntimeRef.current?.resetSession();if (curSid && curMsgs.length > 0) cacheSession(curSid, curMsgs);reset();}}, [urlSessionId, doDisconnect, loadSessionMessages, setupSSE, forceScrollToBottom]);- /* Single shared poller for `GET /live/status`. RunnerStatus consumes this snapshot- * as a prop rather than polling independently, and the global kill switch reads it- * to stay available whenever connector runtime activity could be active out-of-band. */- const refreshLiveStatus = useCallback(async () => {- try {- const next = await api.getLiveStatus();- setLiveStatus(next);- setLiveHalted((current) => (- current && !haltScopeStillActive(current, next) ? null : current- ));- setLiveStatusUnavailable(false);- } catch (error) {- // A 404/501 means the runtime endpoint is not wired on this backend; treat the- // status source as unavailable. Any other failure keeps the last snapshot.- if (error instanceof ApiError && (error.status === 404 || error.status === 501)) {- setLiveStatus(null);- setLiveStatusUnavailable(true);- }- }- }, []);-- useEffect(() => {- refreshLiveStatus();- const timer = setInterval(refreshLiveStatus, LIVE_STATUS_POLL_INTERVAL_MS);- return () => clearInterval(timer);- }, [refreshLiveStatus]);-- // Force an immediate re-poll when a live event bumps refreshKey (commit/halt/resume).- useEffect(() => {- if (liveStatusRefresh > 0) refreshLiveStatus();- }, [liveStatusRefresh, refreshLiveStatus]);-useEffect(() => {if (!sessionId) {setGoalSnapshot(null);- setGoalDetailsOpen(false);return;}if (pendingGoalSessionRef.current === sessionId) {@@ -1137,19 +1126,23 @@ export function Agent() {// Arm the clock at the start of every streaming turn. Without this, a turn// whose very first event never arrives (e.g. the LLM provider hangs before// emitting a single token) left lastEventRef at its 0 / stale value, so the- // guard below short-circuited and the UI hung on "Agent is working…"+ // guard below short-circuited and the activity line stayed live forever.// forever. touch() refreshes this on every real event; the no-op heartbeat// deliberately does not, so a connection that only keep-alives still trips.lastEventRef.current = Date.now();const timer = setInterval(() => {if (lastEventRef.current && Date.now() - lastEventRef.current > sseTimeoutMsRef.current && act().status === "streaming") {- clearStreamingView();+ flushPendingStreamUpdate();+ const partialAnswer = act().streamingText;+ const timedOutActivity = archiveActivity("timeout");+ act().clearStreaming();+ persistPartialAnswer(timedOutActivity, partialAnswer);act().setStatus("idle");toast.warning(t('agent.executionTimedOut'));}}, 10_000);return () => clearInterval(timer);- }, [clearStreamingView, status]);+ }, [archiveActivity, flushPendingStreamUpdate, persistPartialAnswer, status, t]);const ensureGoalSession = useCallback(async (title: string): Promise<string> => {let sid = act().sessionId;@@ -1163,19 +1156,20 @@ export function Agent() {return sid;}, [setSearchParams, setupSSE]);- const runPrompt = useCallback(async (prompt: string) => {+ const runPrompt = useCallback(async (+ prompt: string,+ attachment: ComposerAttachment | null = null,+ ) => {if (!prompt.trim() || status === "streaming") return;clearStreamingView();if (goalComposerActive) {- resetComposerInput();- inputRef.current?.focus();try {const sid = await ensureGoalSession(prompt);const snapshot = await api.createGoal(sid, { objective: prompt });+ goalOpenRequestRef.current += 1;setGoalSnapshot(snapshot);setGoalComposerActive(false);- setGoalDetailsOpen(true);toast.success(t('agent.researchGoalAttached'));const kickoff = goalKickoffPrompt(prompt);act().addMessage({@@ -1185,14 +1179,21 @@ export function Agent() {meta: { goalMode: true, requestText: kickoff },timestamp: Date.now(),});+ act().startActivity(`pending-${Date.now()}`);act().setStatus("streaming");forceScrollToBottom();setupSSE(sid);const sent = await api.sendMessage(sid, kickoff);+ if (act().activity?.attemptId.startsWith("pending-")) {+ act().setActivityAttemptId(sent.attempt_id);+ }void syncCompletedAttempt(sid, sent.attempt_id);} catch (error) {+ if (act().activity) archiveActivity("failed");act().setStatus("idle");- toast.error(error instanceof Error ? error.message : t('agent.failedToStartGoal'));+ const message = error instanceof Error ? error.message : t('agent.failedToStartGoal');+ toast.error(message);+ act().addMessage({ id: "", type: "error", content: message, timestamp: Date.now() });}return;}@@ -1211,10 +1212,8 @@ export function Agent() {if (attachment) {messageMeta.attachment = { filename: attachment.filename };finalPrompt = `[Uploaded file: ${attachment.filename}, path: ${attachment.filePath}]\n\n${finalPrompt}`;- setAttachment(null);}messageMeta.requestText = finalPrompt;- resetComposerInput();act().addMessage({id: "",type: "user",@@ -1222,9 +1221,9 @@ export function Agent() {meta: Object.keys(messageMeta).length > 0 ? messageMeta : undefined,timestamp: Date.now(),});+ act().startActivity(`pending-${Date.now()}`);act().setStatus("streaming");forceScrollToBottom();- inputRef.current?.focus();try {let sid = act().sessionId;@@ -1236,20 +1235,23 @@ export function Agent() {}setupSSE(sid);const sent = await api.sendMessage(sid, finalPrompt);+ if (act().activity?.attemptId.startsWith("pending-")) {+ act().setActivityAttemptId(sent.attempt_id);+ }void syncCompletedAttempt(sid, sent.attempt_id);} catch (error) {+ archiveActivity("failed");act().setStatus("error");const message = isAuthRequiredError(error) ? AUTH_REQUIRED_MESSAGE : t('agent.failedToSend');toast.error(message);act().addMessage({ id: "", type: "error", content: message, timestamp: Date.now() });}}, [- attachment,+ archiveActivity,clearStreamingView,ensureGoalSession,forceScrollToBottom,goalComposerActive,- resetComposerInput,setSearchParams,setupSSE,status,@@ -1258,87 +1260,52 @@ export function Agent() {t,]);- const handleSubmit = (e: FormEvent) => { e.preventDefault(); runPrompt(input.trim()); };+ const submitComposerPrompt = useCallback((prompt: string) => {+ composerRef.current?.submit(prompt);+ }, []);- const handleCancel = async () => {- cancelPendingStreamFlush();- setReasoningActive(false);+ const handleCancel = useCallback(async () => {if (!sessionId) {+ flushPendingStreamUpdate();+ const partialAnswer = act().streamingText;+ const stoppedActivity = archiveActivity("stopped");+ act().clearStreaming();+ persistPartialAnswer(stoppedActivity, partialAnswer);act().setStatus("idle");return;}try {await api.cancelSession(sessionId);- act().setStatus("idle");+ flushPendingStreamUpdate();+ const partialAnswer = act().streamingText;+ const stoppedActivity = archiveActivity("stopped");act().clearStreaming();- useAgentStore.setState({ toolCalls: [] });+ persistPartialAnswer(stoppedActivity, partialAnswer);+ act().setStatus("idle");toast.info(t('agent.cancelRequestSent'));} catch {+ // The attempt is still live. Preserve its activity, buffered text and+ // streaming status so a failed cancel request does not strand the turn.toast.error(t('agent.cancelFailed'));}- };-- const handleHaltLive = useCallback(async () => {- if (halting) return;- setHalting(true);- try {- // The kill switch is global and must fire even with no active chat session- // (e.g. a runner started from the CLI / another session). The backend scopes- // the SSE broadcast by session_id when present; an empty string is a valid- // global trip.- await api.haltLive(sessionId ?? undefined);- // Preemptive halt: the server trips the kill switch (cancel resting orders +- // optional flatten per SPEC §7.5 #6) and broadcasts live.halted. Reflect- // optimistically and re-poll the runtime panel so the runner shows stopped.- setLiveHalted((cur) => cur ?? { broker: null, by: "frontend", tripped_at: new Date().toISOString() });- setLiveStatusRefresh((n) => n + 1);- toast.success(t('agent.connectorHalted'));- } catch (error) {- toast.error(error instanceof Error ? error.message : t('agent.failedToHaltConnector'));- } finally {- setHalting(false);- }- }, [sessionId, halting]);-- const handleCancelGoal = useCallback(async () => {- if (!sessionId || !goalSnapshot) return;- try {- await api.updateGoalStatus(sessionId, {- goal_id: goalSnapshot.goal.goal_id,- expected_goal_id: goalSnapshot.goal.goal_id,- status: "cancelled",- recap: "Cancelled from Web UI.",- });- setGoalSnapshot(null);- setGoalDetailsOpen(false);- toast.success(t('agent.researchGoalCancelled'));- } catch (error) {- toast.error(error instanceof Error ? error.message : t('agent.failedToCancelGoal'));- }- }, [goalSnapshot, sessionId]);-- const handleStartGoalEdit = useCallback(() => {- if (!goalSnapshot) return;- setGoalEditValue(goalSnapshot.goal.objective);- setGoalEditActive(true);- }, [goalSnapshot]);+ }, [+ archiveActivity,+ flushPendingStreamUpdate,+ persistPartialAnswer,+ sessionId,+ t,+ ]);- const handleSaveGoalEdit = useCallback(async () => {- const objective = goalEditValue.trim();- if (!sessionId || !goalSnapshot || !objective) return;- try {- const response = await api.updateGoal(sessionId, {- goal_id: goalSnapshot.goal.goal_id,- expected_goal_id: goalSnapshot.goal.goal_id,- objective,- });- setGoalSnapshot(response.snapshot);- setGoalEditActive(false);- toast.success(t('agent.researchGoalUpdated'));- } catch (error) {- toast.error(error instanceof Error ? error.message : t('agent.failedToUpdateGoal'));- }- }, [goalEditValue, goalSnapshot, sessionId]);+ useEffect(() => {+ if (status !== "streaming") return;+ const cancelOnEscape = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || event.repeat) return;+ event.preventDefault();+ void handleCancel();+ };+ document.addEventListener("keydown", cancelOnEscape);+ return () => document.removeEventListener("keydown", cancelOnEscape);+ }, [handleCancel, status]);const handleContinueGoal = useCallback(async () => {if (!sessionId || !goalSnapshot || status === "streaming") return;@@ -1350,20 +1317,25 @@ export function Agent() {meta: { goalMode: true, requestText: prompt },timestamp: Date.now(),});+ act().startActivity(`pending-${Date.now()}`);act().setStatus("streaming");forceScrollToBottom();- inputRef.current?.focus();+ composerRef.current?.focus();try {setupSSE(sessionId);const sent = await api.sendMessage(sessionId, prompt);+ if (act().activity?.attemptId.startsWith("pending-")) {+ act().setActivityAttemptId(sent.attempt_id);+ }void syncCompletedAttempt(sessionId, sent.attempt_id);} catch (error) {+ archiveActivity("failed");act().setStatus("error");const message = isAuthRequiredError(error) ? AUTH_REQUIRED_MESSAGE : t('agent.failedToContinue');toast.error(message);act().addMessage({ id: "", type: "error", content: message, timestamp: Date.now() });}- }, [forceScrollToBottom, goalSnapshot, sessionId, setupSSE, status, syncCompletedAttempt, t]);+ }, [archiveActivity, forceScrollToBottom, goalSnapshot, sessionId, setupSSE, status, syncCompletedAttempt, t]);const handleRetry = useCallback((errorMsg: AgentMessage) => {if (status === "streaming") return;@@ -1379,10 +1351,58 @@ export function Agent() {}}if (!userContent) return;- runPrompt(userContent);- }, [runPrompt, status]);+ submitComposerPrompt(userContent);+ }, [status, submitComposerPrompt]);++ const handleContinueActivity = useCallback(() => {+ submitComposerPrompt(t("agent.continuePrompt" as never));+ }, [submitComposerPrompt, t]);++ const handleReattachActivity = useCallback((timedOut: AgentActivity) => {+ if (!sessionId || status === "streaming") return;+ useAgentStore.setState((state) => ({+ messages: state.messages.filter((message) => (+ message.meta?.activity?.attemptId !== timedOut.attemptId+ && message.meta?.partialAttemptId !== timedOut.attemptId+ )),+ activity: {+ ...timedOut,+ state: "thinking",+ steps: [],+ endedAt: undefined,+ },+ toolCalls: [],+ streamingText: "",+ }));+ act().setStatus("streaming");+ sseSessionRef.current = null;+ setupSSE(sessionId);+ forceScrollToBottom();+ }, [forceScrollToBottom, sessionId, setupSSE, status]);++ const handleGoalSnapshotChange = useCallback((snapshot: GoalSnapshot | null) => {+ setGoalSnapshot(snapshot);+ }, []);++ const handleStartGoal = useCallback(() => {+ setSwarmPreset(null);+ setGoalComposerActive(true);+ }, []);++ const handleCancelGoalComposer = useCallback(() => {+ setGoalComposerActive(false);+ }, []);++ const handleStartSwarm = useCallback(() => {+ setGoalComposerActive(false);+ setSwarmPreset({ name: "auto", title: "Agent Swarm" });+ }, []);- const handleExport = () => {+ const handleCancelSwarm = useCallback(() => {+ setSwarmPreset(null);+ }, []);++ const handleExport = useCallback(() => {if (messages.length === 0) return;const lines: string[] = [`# Chat Export`, ``, `Export time: ${new Date().toLocaleString()}`, ``];for (const msg of messages) {@@ -1409,54 +1429,21 @@ export function Agent() {a.download = `chat_${new Date().toISOString().slice(0, 10)}.md`;a.click();URL.revokeObjectURL(url);- };+ }, [messages, swarmRuns]);- const handleFileSelect = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- if (!file) return;- e.target.value = "";- const blockedExts = [- ".exe", ".msi", ".bat", ".cmd", ".com", ".scr", ".app", ".dmg",- ".so", ".dll", ".dylib",- ".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz",- ];- const lowered = file.name.toLowerCase();- if (blockedExts.some((ext) => lowered.endsWith(ext))) {- toast.error(t('agent.executablesNotAllowed'));- return;- }- if (file.size > 50 * 1024 * 1024) {- toast.error(t('agent.fileSizeExceeds'));- return;- }- setUploading(true);- setShowUploadMenu(false);- try {- const result = await api.uploadFile(file);- setAttachment({ filename: result.filename, filePath: result.file_path });- toast.success(t('agent.uploaded', { filename: result.filename }));- } catch (err) {- toast.error(t('agent.uploadFailed', { error: err instanceof Error ? err.message : 'Unknown error' }));- } finally {- setUploading(false);- }- }, []);-- useEffect(() => {- const handleClickOutside = (e: MouseEvent) => {- if (uploadMenuRef.current && !uploadMenuRef.current.contains(e.target as Node)) {- setShowUploadMenu(false);+ const groups = useMemo(() => groupMessages(messages), [messages]);+ const hasCompletedTurn = useMemo(() => {+ let latestUserIndex = -1;+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ if (messages[index].type === "user") {+ latestUserIndex = index;+ break;}- };- if (showUploadMenu) {- document.addEventListener("mousedown", handleClickOutside);- return () => document.removeEventListener("mousedown", handleClickOutside);}- }, [showUploadMenu]);-- const groups = useMemo(() => groupMessages(messages), [messages]);- const goalProgress = useMemo(() => getGoalProgress(goalSnapshot), [goalSnapshot]);-+ return latestUserIndex >= 0 && messages+ .slice(latestUserIndex + 1)+ .some((message) => message.type === "answer" || message.type === "run_complete");+ }, [messages]);useEffect(() => {visibleRowsSessionRef.current = sessionId;setVisibleRowCount(TIMELINE_WINDOW_SIZE);@@ -1513,24 +1500,6 @@ export function Agent() {});}, [timelineRows.length]);- /* Whether connector runtime activity could be active *anywhere* — the global kill switch must be- * available whenever it could (audit M2 / SPEC Consent §4). Driven off both- * in-session SSE artifacts AND the shared `/live/status` snapshot, so a runner- * started from the CLI or another browser session still surfaces the halt button- * in a freshly-loaded web session. */- const liveStatusActive =- liveStatus != null &&- (liveStatus.global_halted ||- liveStatus.brokers.some((b) => b.auth.oauth_token_present || b.runner?.alive || b.mandate != null));- const liveActive =- liveItems.length > 0 ||- Object.keys(committedMandates).length > 0 ||- liveHalted != null ||- liveStatusActive;- /* The global kill switch reflects only a global halt from either an in-session SSE- * event or the polled status; broker-scoped halts stay on their broker row. */- const liveIsHalted = isGlobalLiveHalt(liveHalted) || (liveStatus?.global_halted ?? false);-return (<div className="flex flex-col flex-1 min-w-0 overflow-hidden h-full"><div@@ -1585,8 +1554,8 @@ export function Agent() {<div key={row.key} className={shouldAnimate ? "msg-enter" : undefined}><MandateProposalCardproposal={row.item.proposal}- committed={committedMandates[row.item.proposal.proposal_id] ?? null}- onAdjust={runPrompt}+ committed={row.item.committed}+ onAdjust={submitComposerPrompt}/></div>);@@ -1609,6 +1578,8 @@ export function Agent() {<ThinkingTimelinemessages={g.msgs}isLatest={isLastRow && status === "streaming"}+ onContinue={handleContinueActivity}+ onReattach={handleReattachActivity}/></div>);@@ -1640,41 +1611,19 @@ export function Agent() {{/* Streaming area - single stable wrapper to prevent insertBefore DOM race */}{status === "streaming" && (- <div className="flex gap-3 msg-enter" aria-live="polite">+ <div className="flex gap-3 msg-enter"><AgentAvatar />- <div className="flex-1 min-w-0 space-y-1.5">- {!reasoningActive && !streamingText && toolCalls.length === 0 && !Object.values(swarmRuns).some((run) => run.status === "running") && (- <div role="status" className="flex items-center gap-2 text-xs text-muted-foreground pt-1">- <Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />- <span>{t('agent.agentWorking')}</span>- </div>- )}- {reasoningActive && !streamingText && (- <div role="status" className="flex items-center gap-2 text-xs text-muted-foreground">- <Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />- <span>{t('agent.reasoning')}</span>- </div>- )}+ <div className="flex-1 min-w-0 space-y-2">+ {activity && <ActivityLine activity={activity} />}{streamingText && (- <MarkdownContent content={streamingText} streaming showCursor />- )}- {toolCalls.length > 0 && (- <ToolProgressIndicator toolCalls={toolCalls} />+ <div aria-live="polite" aria-atomic="false">+ <MarkdownContent content={streamingText} streaming showCursor />+ </div>)}</div></div>)}- {/* Persistent streaming pulse bar — always visible while agent is working */}- {status === "streaming" && (- <div className="flex items-center gap-2 px-1 pt-1">- <div className="h-0.5 flex-1 rounded-full bg-primary/20 overflow-hidden">- <div className="h-full w-1/3 bg-primary rounded-full animate-[pulse-slide_2s_ease-in-out_infinite]" />- </div>- <span className="text-[10px] text-muted-foreground shrink-0 tabular-nums">{t('agent.running')}</span>- </div>- )}-</div>{/* Scroll to bottom button */}@@ -1689,416 +1638,49 @@ export function Agent() {<ConversationTimeline messages={messages} containerRef={listRef} /></div>- <form+ <divdata-agent-composer- onSubmit={handleSubmit}className="border-t p-4 bg-background/80 backdrop-blur-sm">- <div className="max-w-3xl mx-auto space-y-2">- {/* Swarm preset badge */}- {swarmPreset && (- <div className="flex items-center gap-1">- <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">- <Users className="h-3 w-3" />- {swarmPreset.title}- <button type="button" onClick={() => setSwarmPreset(null)} className="hover:text-destructive transition-colors">- <X className="h-3 w-3" />- </button>- </span>- </div>- )}- {goalComposerActive && (- <div className="flex items-center gap-1">- <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">- <Target className="h-3 w-3" />- {t("agent.newResearchGoal")}- <button type="button" onClick={() => setGoalComposerActive(false)} className="hover:text-destructive transition-colors">- <X className="h-3 w-3" />- </button>- </span>- </div>- )}- {goalSnapshot && !goalComposerActive && (- <div className="grid gap-2">- <button- type="button"- onClick={() => setGoalDetailsOpen((open) => !open)}- className="inline-flex max-w-full items-center gap-1.5 justify-self-start rounded-lg bg-primary/10 px-2.5 py-1 text-left text-xs font-medium text-primary transition-colors hover:bg-primary/15"- title={goalSnapshot.goal.objective}- aria-label={t("agent.activeResearchGoal")}- aria-expanded={goalDetailsOpen}- >- <Target className="h-3 w-3 shrink-0" />- <span className="shrink-0">{t('agent.goal')}</span>- <span className="truncate text-muted-foreground">- {goalSnapshot.goal.ui_summary || goalSnapshot.goal.objective}- </span>- {goalProgress.metLabel && (- <span className="shrink-0 font-mono text-[11px] text-emerald-600 dark:text-emerald-400">- {goalProgress.metLabel}- </span>- )}- {goalProgress.evidenceTotal > 0 && (- <span className="shrink-0 rounded bg-background px-1 font-mono text-[10px] text-primary" title={t("agent.evidenceCollectedTitle")}>- {t("agent.evidenceCount", { count: goalProgress.evidenceTotal })}- </span>- )}- <ChevronDown- className={[- "h-3 w-3 shrink-0 transition-transform",- goalDetailsOpen ? "rotate-180" : "",- ].join(" ")}- aria-hidden="true"- />- </button>- {goalDetailsOpen && (- <div className="grid gap-3 rounded-xl border border-primary/20 bg-background/95 p-3 text-xs shadow-sm">- {goalEditActive ? (- <div className="grid gap-2">- <textarea- value={goalEditValue}- onChange={(event) => setGoalEditValue(event.target.value)}- rows={3}- aria-label={t("agent.editGoalObjectiveLabel")}- className="w-full rounded-lg border bg-background px-3 py-2 text-xs leading-relaxed text-foreground outline-none focus:ring-2 focus:ring-primary/30"- />- <div className="flex justify-end gap-2">- <button- type="button"- onClick={() => setGoalEditActive(false)}- className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground"- >- <X className="h-3 w-3" />- {t("agent.cancel")}- </button>- <button- type="button"- onClick={handleSaveGoalEdit}- disabled={!goalEditValue.trim()}- className="inline-flex items-center gap-1 rounded-lg bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground transition-opacity disabled:opacity-40"- >- <Check className="h-3 w-3" />- {t("agent.save")}- </button>- </div>- </div>- ) : (- <div className="rounded-lg border bg-muted/20 px-3 py-2 text-[11px] leading-relaxed text-muted-foreground">- {goalSnapshot.goal.objective}- </div>- )}- <div className="grid grid-cols-2 gap-2">- <div className="rounded-lg border bg-muted/20 p-2.5">- <div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">- {t("agent.criteria")}- </div>- <div className="mt-1 font-mono text-base font-semibold text-foreground">- {goalProgress.label || "0/0"}- </div>- </div>- <div className="rounded-lg border bg-muted/20 p-2.5">- <div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">- {t("agent.evidence")}- </div>- <div className="mt-1 font-mono text-base font-semibold text-foreground">- {goalProgress.evidenceTotal}- </div>- </div>- </div>- <div className="grid gap-1.5">- {goalSnapshot.criteria.map((criterion, index) => {- const evidenceCount = criterionEvidenceCount(goalSnapshot, criterion.criterion_id);- const displayStatus = criterionCovered(goalSnapshot, criterion) && !isCriterionStatusMet(criterion.status)- ? "covered"- : statusLabel(criterion.status);- return (- <div- key={criterion.criterion_id}- className="grid grid-cols-[1.25rem_minmax(0,1fr)_auto] items-start gap-2 rounded-lg border bg-muted/20 p-2"- >- <span className="flex h-5 w-5 items-center justify-center rounded-full bg-muted text-[10px] text-muted-foreground">- {criterionIndexLabel(index)}- </span>- <span className="min-w-0">- <span className="block truncate font-medium text-foreground">{criterion.text}</span>- <span className="block text-[11px] text-muted-foreground">- {displayStatus}- </span>- </span>- <span className="rounded-full border px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">- {evidenceCount} ev- </span>- </div>- );- })}- </div>- {goalSnapshot.evidence.length > 0 && (- <div className="grid gap-1.5 border-t pt-2">- <div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">- {t("agent.recentEvidence")}- </div>- {latestGoalEvidence(goalSnapshot).map((item) => (- <div key={item.evidence_id} className="rounded-lg bg-muted/20 px-2 py-1.5">- <div className="mb-0.5 flex items-center justify-between gap-2 text-[10px] text-muted-foreground">- <span className="truncate">{item.source_provider || "evidence"}</span>- <span>{statusLabel(item.verification_status)}</span>- </div>- <div className="line-clamp-2 text-[11px] leading-relaxed text-foreground">- {item.text}- </div>- </div>- ))}- </div>- )}- <div className="flex flex-wrap justify-end gap-2 border-t pt-2">- <button- type="button"- onClick={handleContinueGoal}- disabled={status === "streaming"}- className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"- >- <Play className="h-3 w-3" />- {t("agent.continue")}- </button>- <button- type="button"- onClick={handleStartGoalEdit}- disabled={goalEditActive}- className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"- >- <Pencil className="h-3 w-3" />- {t("agent.edit")}- </button>- <button- type="button"- onClick={handleCancelGoal}- className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-destructive/40 hover:text-destructive"- >- <X className="h-3 w-3" />- {t("agent.cancelGoal")}- </button>- </div>- </div>- )}- </div>- )}- {/* Persistent live runtime status panel — sits alongside the goal/mandate- badges (SPEC §7.5 + audit C2). Self-hides when no broker is configured. */}- <RunnerStatus- status={liveStatus}- unavailable={liveStatusUnavailable}- halted={liveIsHalted}- onRefresh={refreshLiveStatus}- />- {/* Attachment badge */}- {attachment && (- <div className="flex items-center gap-1">- <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">- <Paperclip className="h-3 w-3" />- {attachment.filename}- <button type="button" onClick={() => setAttachment(null)} className="hover:text-destructive transition-colors">- <X className="h-3 w-3" />- </button>- </span>- </div>- )}- {/* Uploading indicator */}- {uploading && (- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <Loader2 className="h-3 w-3 animate-spin" />- {t("agent.uploading")}- </div>- )}- {/* Persistent kill switch — distinct from the per-turn Stop button- above; disables all live order activity (SPEC Consent §4).- Given a top border + extra top padding so this safety-critical- control visually separates from the lighter decorative chips- (swarm/goal/attachment) stacked above it. */}- {liveActive && (- <div className="flex items-center gap-2 border-t border-border/60 pt-2">- {liveIsHalted ? (- <span className="inline-flex items-center gap-1.5 rounded-lg bg-destructive/10 px-2.5 py-1 text-xs font-medium text-destructive">- <OctagonX className="h-3 w-3" />- {t("agent.connectorHalted")}- </span>- ) : (- <button- type="button"- onClick={handleHaltLive}- disabled={halting}- className="inline-flex items-center gap-1.5 rounded-lg border border-destructive/40 bg-destructive/5 px-2.5 py-1 text-xs font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-40"- title={t("agent.haltConnectorTitle")}- >- {halting ? <Loader2 className="h-3 w-3 animate-spin" /> : <OctagonX className="h-3 w-3" />}- {t("agent.haltConnector")}- </button>- )}- </div>- )}- <div className="flex items-end gap-2 rounded-2xl border border-border/60 bg-background p-1.5 shadow-[0_1px_2px_rgba(0,0,0,0.03),0_8px_24px_-12px_rgba(0,0,0,0.12)] transition-shadow focus-within:ring-2 focus-within:ring-primary/25 dark:bg-card">- {/* "+" menu: PDF upload + Swarm presets */}- <div className="relative" ref={uploadMenuRef}>- <button- type="button"- onClick={() => setShowUploadMenu(prev => !prev)}- disabled={status === "streaming" || uploading}- className="w-10 h-10 rounded-full border flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40 shrink-0"- title={t("agent.moreOptions")}- >- <Plus className="h-4 w-4" />- </button>- {showUploadMenu && (- <div className="absolute bottom-full left-0 mb-2 w-52 rounded-xl border bg-background/95 backdrop-blur-sm shadow-lg py-1 z-50">- <button- type="button"- onClick={() => { fileInputRef.current?.click(); setShowUploadMenu(false); }}- className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"- >- <Paperclip className="h-4 w-4" />- {t("agent.uploadPdf")}- </button>- <div className="border-t my-1" />- <button- type="button"- onClick={() => {- setShowUploadMenu(false);- setSwarmPreset(null);- setGoalComposerActive(true);- inputRef.current?.focus();- }}- className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"- >- <Target className="h-4 w-4" />- {t("agent.researchGoal")}- </button>- <button- type="button"- onClick={() => {- setShowUploadMenu(false);- setGoalComposerActive(false);- setSwarmPreset({ name: "auto", title: "Agent Swarm" });- inputRef.current?.focus();- }}- className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"- >- <Users className="h-4 w-4" />- {t("agent.agentSwarm")}- </button>- <div className="border-t my-1" />- <button- type="button"- onClick={() => {- setShowUploadMenu(false);- void runPrompt(CONNECTOR_CHECK_PROMPT);- }}- className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"- >- <Landmark className="h-4 w-4" />- {t("agent.checkConnector")}- </button>- <button- type="button"- onClick={() => {- setShowUploadMenu(false);- void runPrompt(CONNECTOR_PORTFOLIO_PROMPT);- }}- className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"- >- <Landmark className="h-4 w-4" />- {t("agent.analyzePortfolio")}- </button>- </div>- )}- </div>- <input- ref={fileInputRef}- type="file"- accept=".pdf,.docx,.xlsx,.xls,.pptx,.csv,.tsv,.txt,.md,.log,.json,.yaml,.yml,.toml,.html,.xml,.rst,.png,.jpg,.jpeg,.gif,.bmp,.webp,.tiff"- onChange={handleFileSelect}- className="hidden"- />- <textarea- ref={inputRef}- value={input}- rows={1}- onChange={(e) => setInput(e.target.value)}- onCompositionStart={() => {- isComposingRef.current = true;- }}- onCompositionEnd={() => {- isComposingRef.current = false;- lastCompositionEndRef.current = Date.now();- }}- onInput={(e) => {- const el = e.target as HTMLTextAreaElement;- el.style.height = "auto";- el.style.height = el.scrollHeight + "px";- }}- onKeyDown={(e) => {- if (e.key === "Enter" && !e.shiftKey) {- const nativeEvent = e.nativeEvent as KeyboardEvent & { isComposing?: boolean };- const justFinishedComposing = Date.now() - lastCompositionEndRef.current < 80;- if (isComposingRef.current || nativeEvent.isComposing || nativeEvent.keyCode === 229) {- return;- }- if (justFinishedComposing) {- e.preventDefault();- return;- }- e.preventDefault();- runPrompt(input.trim());- }- }}- placeholder={- status === "streaming"- ? t("agent.agentWorking")- : goalComposerActive- ? t("agent.describeGoal")- : t("agent.placeholder")+ <div className="max-w-3xl mx-auto">+ <LiveRuntimePanel+ ref={liveRuntimeRef}+ sessionId={sessionId}+ hasLiveItems={liveItems.length > 0}+ >+ <Composer+ ref={composerRef}+ streaming={status === "streaming"}+ activityVerb={activity?.verb}+ hasCompletedTurn={hasCompletedTurn}+ showExport={sessionId != null}+ canExport={messages.length > 0}+ goalComposerActive={goalComposerActive}+ swarmPreset={swarmPreset}+ panels={+ goalSnapshot && !goalComposerActive ? (+ <GoalPanel+ key={goalSnapshot.goal.goal_id}+ snapshot={goalSnapshot}+ sessionId={sessionId}+ streaming={status === "streaming"}+ openRequest={goalOpenRequestRef.current}+ onSnapshotChange={handleGoalSnapshotChange}+ onContinue={handleContinueGoal}+ />+ ) : undefined}- aria-label={t("agent.messageInputLabel")}- aria-readonly={status === "streaming"}- className={[- "min-h-[52px] flex-1 resize-none overflow-y-auto bg-transparent px-3 py-3 text-sm outline-none max-h-32",- status === "streaming" ? "cursor-not-allowed text-muted-foreground/70" : "",- ].join(" ")}- readOnly={status === "streaming"}+ onSubmit={runPrompt}+ onCancel={handleCancel}+ onExport={handleExport}+ onStartGoal={handleStartGoal}+ onCancelGoal={handleCancelGoalComposer}+ onStartSwarm={handleStartSwarm}+ onCancelSwarm={handleCancelSwarm}/>- {sessionId && (- <button- type="button"- onClick={handleExport}- disabled={messages.length === 0}- className="h-10 px-3 rounded-xl border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 disabled:pointer-events-none"- title={t('agent.exportChat')}- >- <Download className="h-4 w-4" />- </button>- )}- {status === "streaming" ? (- <button- type="button"- onClick={handleCancel}- className="h-10 px-4 rounded-xl bg-destructive text-destructive-foreground text-sm font-medium hover:opacity-90 transition-opacity"- title={t('agent.stopGeneration')}- >- <Square className="h-4 w-4" />- </button>- ) : (- <button- type="submit"- disabled={goalComposerActive ? !input.trim() : (!input.trim() && !attachment)}- className="h-10 px-4 rounded-xl bg-primary text-primary-foreground text-sm font-medium disabled:opacity-40 hover:opacity-90 transition-opacity"- title={t("agent.send")}- aria-label={t("agent.send")}- >- <Send className="h-4 w-4" />- </button>- )}- </div>- <p className="px-1 text-[11px] text-muted-foreground">{t("agent.inputHint")}</p>+ </LiveRuntimePanel></div>- </form>+ </div></div>);}diff --git a/frontend/src/pages/AlphaZoo.tsx b/frontend/src/pages/AlphaZoo.tsxindex 80904fee4..b36cd3899 100644--- a/frontend/src/pages/AlphaZoo.tsx+++ b/frontend/src/pages/AlphaZoo.tsx@@ -46,8 +46,6 @@ import { useThemeDark } from "@/lib/theme-store";interface ZooCard {id: string;- title: string;- description: string;approxCount: number;}@@ -56,45 +54,30 @@ interface ZooCard {const ZOO_CARDS: ZooCard[] = [{id: "qlib158",- title: "Qlib 158",- description:- "Microsoft Qlib's full 158-feature library covering momentum, volatility, volume and rolling statistical signals.",approxCount: 154,},{id: "alpha101",- title: "Kakushadze 101 Formulaic Alphas",- description:- "The 101 formulaic alphas from Kakushadze (2015); short-horizon cross-sectional signals.",approxCount: 101,},{id: "gtja191",- title: "GTJA 191",- description:- "Guotai Junan Securities' 191 alphas; technical and microstructure signals tuned to China A-share markets.",approxCount: 191,},{id: "academic",- title: "Academic Anomalies",- description:- "Curated long-horizon anomalies from the academic literature (value, momentum, quality, low-vol, etc.).",approxCount: 10,},{id: "fundamental",- title: "PIT-Safe Fundamentals",- description:- "Quality and value factors computed from PIT-safe SEC company facts — earnings yield, ROE, gross profitability, asset growth (filed-date anchored).",approxCount: 4,},];const UNIVERSE_OPTIONS = [- { value: "csi300", label: "CSI 300 (China A)" },- { value: "sp500", label: "S&P 500 (US)" },- { value: "btc-usdt", label: "BTC-USDT (Crypto)" },+ { value: "csi300" },+ { value: "sp500" },+ { value: "btc-usdt" },];const PAGE_SIZE = 50;@@ -178,7 +161,7 @@ function BrowseView() {}).catch((err: unknown) => {if (!alive) return;- const msg = err instanceof Error ? err.message : "Failed to load alphas";+ const msg = err instanceof Error ? err.message : i18n.t("alphaZoo.failedToLoadAlphas" as any);toast.error(msg);setAlphas([]);setTotal(0);@@ -247,9 +230,9 @@ function BrowseView() {{z.approxCount}</span></div>- <h3 className="font-semibold text-sm leading-tight">{i18n.t("alphaZoo.zooCardTitle." + z.id as any, { defaultValue: z.title })}</h3>+ <h3 className="font-semibold text-sm leading-tight">{i18n.t("alphaZoo.zooCardTitle." + z.id as any)}</h3><p className="text-xs text-muted-foreground line-clamp-3">- {i18n.t("alphaZoo.zooCardDesc." + z.id as any, { defaultValue: z.description })}+ {i18n.t("alphaZoo.zooCardDesc." + z.id as any)}</p></button>);@@ -290,7 +273,7 @@ function BrowseView() {<option value="">{i18n.t("alphaZoo.allZoos")}</option>{ZOO_CARDS.map((z) => (<option key={z.id} value={z.id}>- {i18n.t("alphaZoo.zooCardTitle." + z.id as any, { defaultValue: z.title })}+ {i18n.t("alphaZoo.zooCardTitle." + z.id as any)}</option>))}</select>@@ -326,7 +309,7 @@ function BrowseView() {<option value="">{i18n.t("alphaZoo.allUniverses")}</option>{UNIVERSE_OPTIONS.map((u) => (<option key={u.value} value={u.value}>- {i18n.t("alphaZoo.universeOption." + u.value as any, { defaultValue: u.label })}+ {i18n.t("alphaZoo.universeOption." + u.value as any)}</option>))}</select>@@ -403,7 +386,7 @@ function BrowseView() {type="checkbox"checked={selected.has(a.id)}onChange={() => toggleSelected(a.id)}- aria-label={`Select ${a.id} for compare`}+ aria-label={i18n.t("alphaZoo.selectAlphaForCompare" as any, { id: a.id })}className="h-4 w-4 rounded border-input accent-primary cursor-pointer"/></td>@@ -478,7 +461,7 @@ function DetailView({ alphaId }: DetailProps) {}).catch((err: unknown) => {if (!alive) return;- const msg = err instanceof Error ? err.message : "Failed to load alpha";+ const msg = err instanceof Error ? err.message : i18n.t("alphaZoo.failedToLoadAlpha" as any);setError(msg);}).finally(() => {@@ -693,14 +676,12 @@ function BenchView() {setJobId(res.job_id);await attachStream(res.job_id);} catch (err: unknown) {- const msg = err instanceof Error ? err.message : "Failed to start bench";+ const msg = err instanceof Error ? err.message : i18n.t("alphaZoo.failedToStartBench" as any);// BTC-USDT is single-asset — surface inline rather than as a toast,// because the form is the action context and the message includes a// concrete suggestion for the user's next step.if (msg.toLowerCase().includes("single-asset")) {- setFormError(- `${msg} Try \`sp500\` or \`csi300\` for a meaningful cross-sectional IC.`,- );+ setFormError(i18n.t("alphaZoo.singleAssetHint" as any, { message: msg }));} else {toast.error(msg);}@@ -751,7 +732,7 @@ function BenchView() {sourceRef.current = null;return;}- let msg = "Bench stream error";+ let msg = i18n.t("alphaZoo.benchStreamError" as any);try {const data = JSON.parse((e as MessageEvent).data || "{}");if (typeof data.message === "string") msg = data.message;@@ -804,7 +785,7 @@ function BenchView() {>{ZOO_CARDS.map((z) => (<option key={z.id} value={z.id}>- {i18n.t("alphaZoo.zooCardTitle." + z.id as any, { defaultValue: z.title })}+ {i18n.t("alphaZoo.zooCardTitle." + z.id as any)}</option>))}</select>@@ -820,7 +801,7 @@ function BenchView() {>{UNIVERSE_OPTIONS.map((u) => (<option key={u.value} value={u.value}>- {i18n.t("alphaZoo.universeOption." + u.value as any, { defaultValue: u.label })}+ {i18n.t("alphaZoo.universeOption." + u.value as any)}</option>))}</select>@@ -906,7 +887,9 @@ function ProgressPanel({<div className="flex items-center justify-between text-xs text-muted-foreground"><span className="flex items-center gap-1.5"><Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />- {jobId ? `Job ${jobId.slice(0, 12)}…` : "Submitting…"}+ {jobId+ ? i18n.t("alphaZoo.job" as any, { id: jobId.slice(0, 12) })+ : i18n.t("alphaZoo.submitting")}</span>{progress && (<span className="font-mono tabular-nums">@@ -1106,10 +1089,10 @@ function CategoryBadge({ category }: { category: AlphaBenchTopRow["category"] })/* ---------- Compare view ---------- */const SORT_OPTIONS = [- { value: "ir", label: "IR (information ratio)" },- { value: "ic_mean", label: "IC mean" },- { value: "ic_positive_ratio", label: "IC > 0 ratio" },- { value: "ic_count", label: "Sample count" },+ { value: "ir" },+ { value: "ic_mean" },+ { value: "ic_positive_ratio" },+ { value: "ic_count" },];/** Split a free-text id list on commas / whitespace; dedupe, preserve order. */@@ -1197,7 +1180,7 @@ function CompareView() {sourceRef.current = null;return;}- let msg = "Compare stream error";+ let msg = i18n.t("alphaZoo.compareStreamError" as any);try {const data = JSON.parse((e as MessageEvent).data || "{}");if (typeof data.message === "string") msg = data.message;@@ -1215,7 +1198,7 @@ function CompareView() {e.preventDefault();if (status === "submitting" || status === "streaming") return;if (ids.length < 2) {- setFormError("Enter at least 2 distinct alpha ids to compare.");+ setFormError(i18n.t("alphaZoo.enterAtLeast2"));return;}setStatus("submitting");@@ -1235,7 +1218,7 @@ function CompareView() {await attachStream(res.job_id);} catch (err: unknown) {const msg =- err instanceof Error ? err.message : "Failed to start comparison";+ err instanceof Error ? err.message : i18n.t("alphaZoo.failedToStartComparison" as any);toast.error(msg);setStatus("error");}@@ -1295,7 +1278,7 @@ function CompareView() {>{UNIVERSE_OPTIONS.map((u) => (<option key={u.value} value={u.value}>- {i18n.t("alphaZoo.universeOption." + u.value as any, { defaultValue: u.label })}+ {i18n.t("alphaZoo.universeOption." + u.value as any)}</option>))}</select>@@ -1322,7 +1305,7 @@ function CompareView() {>{SORT_OPTIONS.map((s) => (<option key={s.value} value={s.value}>- {i18n.t("alphaZoo.sortOption." + (s.value === "ic_mean" ? "icMean" : s.value === "ic_positive_ratio" ? "icPositiveRatio" : s.value === "ic_count" ? "icCount" : s.value) as any, { defaultValue: s.label })}+ {i18n.t("alphaZoo.sortOption." + (s.value === "ic_mean" ? "icMean" : s.value === "ic_positive_ratio" ? "icPositiveRatio" : s.value === "ic_count" ? "icCount" : s.value) as any)}</option>))}</select>diff --git a/frontend/src/pages/Compare.tsx b/frontend/src/pages/Compare.tsxindex b89ce8e84..4606b772f 100644--- a/frontend/src/pages/Compare.tsx+++ b/frontend/src/pages/Compare.tsx@@ -360,8 +360,8 @@ export function Compare() {<EquityChartOverlayleftCurve={leftCurve}rightCurve={rightCurve}- leftLabel={leftRun ? truncatePrompt(leftRun.prompt, 20) || "Baseline" : "Baseline"}- rightLabel={rightRun ? truncatePrompt(rightRun.prompt, 20) || "Compare" : "Compare"}+ leftLabel={leftRun ? truncatePrompt(leftRun.prompt, 20) || t("compare.baseline") : t("compare.baseline")}+ rightLabel={rightRun ? truncatePrompt(rightRun.prompt, 20) || t("compare.compare") : t("compare.compare")}/></div>)}@@ -393,9 +393,7 @@ export function Compare() {<><span aria-hidden="true">{diff.glyph} </span><span className="sr-only">- {t(`compare.${diff.verdict}`, {- defaultValue: diff.verdict === "better" ? "Better" : "Worse",- })}+ {t(`compare.${diff.verdict}`)}{": "}</span></>diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex cae30efd4..4752af6f2 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -182,8 +182,7 @@ export function RunDetail() {<div className="p-8 space-y-2"><p className="text-red-500 font-medium">{i18n.t("runDetail.runNotFound")}</p><p className="text-sm text-muted-foreground">- {i18n.t("runDetail.runNotFoundDesc")}, or your browser may not have API access configured.- Check that the API authentication key is set in Settings if accessing remotely.+ {i18n.t("runDetail.runNotFoundDesc")}</p><buttononClick={() => navigate(-1)}@@ -393,9 +392,9 @@ function RunCardTab({ card }: { card: RunCard }) {return (<div className="p-4 space-y-4"><div className="grid gap-3 md:grid-cols-4">- <RunCardStat label={i18n.t("runDetail.schema")} value={card.schema_version || "unknown"} />+ <RunCardStat label={i18n.t("runDetail.schema")} value={card.schema_version || i18n.t("runDetail.unknown" as any)} /><RunCardStat label={i18n.t("runDetail.generated")} value={formatRunCardValue(card.generated_at)} />- <RunCardStat label={i18n.t("runDetail.dataSources")} value={dataSources.length ? dataSources.join(", ") : "None recorded"} />+ <RunCardStat label={i18n.t("runDetail.dataSources")} value={dataSources.length ? dataSources.join(", ") : i18n.t("runDetail.noneRecorded" as any)} /><RunCardStat label={i18n.t("runDetail.warnings")} value={String(warnings.length)} tone={warnings.length ? "warning" : "normal"} /></div>diff --git a/frontend/src/pages/__tests__/agentToolTimeline.test.ts b/frontend/src/pages/__tests__/agentToolTimeline.test.tsindex 8ace850f8..7b2f6699b 100644--- a/frontend/src/pages/__tests__/agentToolTimeline.test.ts+++ b/frontend/src/pages/__tests__/agentToolTimeline.test.ts@@ -1,7 +1,7 @@import { buildToolTimelineMessages } from "../agentToolTimeline";describe("buildToolTimelineMessages", () => {- it("rebuilds persisted tool calls and results with the live completion mapping", () => {+ it("rebuilds one durable activity object from a persisted tool trail", () => {expect(buildToolTimelineMessages([{@@ -23,35 +23,61 @@ describe("buildToolTimelineMessages", () => {{fallbackTimestamp: 1_785_342_500_000,idPrefix: "message-1_",+ attemptId: "attempt-1",+ endedAt: 1_785_342_500_000,},)).toEqual([{- id: "message-1_call-market-1_call",- type: "tool_call",+ id: "message-1_activity_attempt-1",+ type: "thinking",content: "",- tool: "get_market_data",- args: { symbol: "AAPL" },- status: "ok",+ meta: {+ activity: {+ attemptId: "attempt-1",+ state: "done",+ verb: "writingStrategy",+ steps: [+ {+ id: "call-market-1",+ tool: "get_market_data",+ arguments: { symbol: "AAPL" },+ status: "ok",+ preview: "AAPL 195.00",+ elapsed_ms: 125,+ timestamp: 1_785_342_400_000,+ },+ {+ id: "write_file#2",+ tool: "write_file",+ arguments: { path: "report.md" },+ status: "error",+ preview: undefined,+ elapsed_ms: undefined,+ timestamp: 1_785_342_400_000,+ },+ ],+ startedAt: 1_785_342_400_000,+ endedAt: 1_785_342_500_000,+ },+ },timestamp: 1_785_342_400_000,},- {- id: "message-1_call-market-1_result",- type: "tool_result",- content: "AAPL 195.00",- tool: "get_market_data",- status: "ok",- elapsed_ms: 125,- timestamp: 1_785_342_400_001,- },- {- id: "message-1_write_file#2_call",- type: "tool_call",- content: "",- tool: "write_file",- args: { path: "report.md" },- status: "error",- timestamp: 1_785_342_400_002,- },]);});++ it("keeps a zero-step attempt visible in history", () => {+ const [message] = buildToolTimelineMessages([], {+ fallbackTimestamp: 1000,+ attemptId: "attempt-empty",+ });++ expect(message.meta?.activity).toMatchObject({+ attemptId: "attempt-empty",+ state: "done",+ verb: "working",+ steps: [],+ startedAt: 1000,+ endedAt: 1000,+ });+ });});diff --git a/frontend/src/pages/agentToolTimeline.ts b/frontend/src/pages/agentToolTimeline.tsindex 66f77d872..92ab67913 100644--- a/frontend/src/pages/agentToolTimeline.ts+++ b/frontend/src/pages/agentToolTimeline.ts@@ -1,4 +1,9 @@-import type { StoredAgentMessage } from "@/stores/agent";+import {+ deriveActivityVerb,+ type ActivityState,+ type AgentActivity,+ type StoredAgentMessage,+} from "@/stores/agent";export interface ToolTimelineEntry {id?: string;@@ -14,48 +19,53 @@ export interface ToolTimelineEntry {interface ToolTimelineOptions {fallbackTimestamp?: number;idPrefix?: string;+ attemptId?: string;+ state?: ActivityState;+ endedAt?: number;+ activity?: AgentActivity;}-/** Convert consolidated tool records into the transcript timeline shape. */+/** Convert one attempt's consolidated tool records into its durable activity row. */export function buildToolTimelineMessages(entries: readonly ToolTimelineEntry[],options: ToolTimelineOptions = {},): StoredAgentMessage[] {const fallbackTimestamp = options.fallbackTimestamp ?? Date.now();const idPrefix = options.idPrefix ?? "";- const messages: StoredAgentMessage[] = [];- let previousTimestamp = Number.NEGATIVE_INFINITY;+ const steps = entries.map((entry, index) => ({+ id: entry.id || entry.call_id || `${entry.tool}#${index + 1}`,+ tool: entry.tool,+ arguments: entry.arguments ?? {},+ status: entry.status || "ok",+ preview: entry.preview,+ elapsed_ms: entry.elapsed_ms,+ timestamp: (+ typeof entry.timestamp === "number" && Number.isFinite(entry.timestamp)+ ? entry.timestamp+ : fallbackTimestamp + index+ ),+ }));+ const startedAt = steps.length > 0+ ? Math.min(...steps.map((step) => step.timestamp))+ : fallbackTimestamp;+ const inferredEnd = Math.max(+ fallbackTimestamp,+ startedAt + steps.reduce((sum, step) => sum + (step.elapsed_ms ?? 0), 0),+ );+ const activity: AgentActivity = options.activity ?? {+ attemptId: options.attemptId || `${idPrefix}attempt`,+ state: options.state ?? "done",+ verb: deriveActivityVerb(steps[steps.length - 1]?.tool),+ steps,+ startedAt,+ endedAt: options.endedAt ?? inferredEnd,+ };- entries.forEach((entry, index) => {- const candidateTimestamp = typeof entry.timestamp === "number" && Number.isFinite(entry.timestamp)- ? entry.timestamp- : fallbackTimestamp + index * 2;- const timestamp = Math.max(candidateTimestamp, previousTimestamp + 1);- const entryId = entry.id || entry.call_id || `${entry.tool}#${index + 1}`;- const status = entry.status || "ok";-- messages.push({- id: `${idPrefix}${entryId}_call`,- type: "tool_call",- content: "",- tool: entry.tool,- args: entry.arguments ?? {},- status,- timestamp,- });- if (entry.elapsed_ms != null) {- messages.push({- id: `${idPrefix}${entryId}_result`,- type: "tool_result",- content: entry.preview || "",- tool: entry.tool,- status,- elapsed_ms: entry.elapsed_ms,- timestamp: timestamp + 1,- });- }- previousTimestamp = entry.elapsed_ms != null ? timestamp + 1 : timestamp;- });-- return messages;+ return [{+ id: `${idPrefix}activity_${activity.attemptId}`,+ type: "thinking",+ content: "",+ meta: { activity },+ timestamp: activity.startedAt,+ }];}diff --git a/frontend/src/stores/__tests__/agent.test.ts b/frontend/src/stores/__tests__/agent.test.tsindex 4a845ce42..d518a1588 100644--- a/frontend/src/stores/__tests__/agent.test.ts+++ b/frontend/src/stores/__tests__/agent.test.ts@@ -16,6 +16,7 @@ describe("agent store — initial state", () => {expect(s.streamingText).toBe("");expect(s.streamingSessionId).toBeNull();expect(s.toolCalls).toEqual([]);+ expect(s.activity).toBeNull();expect(s.swarmRuns).toEqual({});expect(s.sseStatus).toBe("disconnected");expect(s.sseRetryAttempt).toBe(0);@@ -203,6 +204,66 @@ describe("tool calls", () => {"error",]);});++ it("live-updates one activity object from thinking through tool work", () => {+ const store = useAgentStore.getState();+ store.startActivity("attempt-1", 1000);+ expect(useAgentStore.getState().activity).toMatchObject({+ attemptId: "attempt-1",+ state: "thinking",+ verb: "working",+ steps: [],+ startedAt: 1000,+ });++ store.addToolCall(makeToolCall({+ id: "market-1",+ tool: "get_market_data",+ timestamp: 1100,+ }));+ expect(useAgentStore.getState().activity).toMatchObject({+ state: "working",+ verb: "readingMarketData",+ steps: [{ id: "market-1", status: "running" }],+ });++ store.updateToolCall("market-1", { status: "ok", elapsed_ms: 500 });+ expect(useAgentStore.getState().activity?.steps[0]).toMatchObject({+ status: "ok",+ elapsed_ms: 500,+ });+ });++ it("derives strategy, backtest, validation and fallback verbs", () => {+ const store = useAgentStore.getState();+ store.startActivity("attempt-map", 1000);+ const tools = [+ ["write_file", "writingStrategy"],+ ["run_backtest", "runningBacktest"],+ ["walk_forward_validation", "validatingNumbers"],+ ["run_swarm", "working"],+ ] as const;++ for (const [tool, verb] of tools) {+ store.addToolCall(makeToolCall({ id: tool, tool }));+ expect(useAgentStore.getState().activity?.verb).toBe(verb);+ }+ });++ it("freezes terminal activity timing and can replace a pending attempt id", () => {+ const store = useAgentStore.getState();+ store.startActivity("pending-1", 1000);+ store.setActivityAttemptId("attempt-final");+ store.setActivityState("responding", 1500);+ store.setActivityState("stopped", 4000);++ expect(useAgentStore.getState().activity).toMatchObject({+ attemptId: "attempt-final",+ state: "stopped",+ startedAt: 1000,+ endedAt: 4000,+ });+ });});describe("swarm status ordering", () => {@@ -326,6 +387,7 @@ describe("switchSession", () => {expect(s.sessionId).toBe("new-sess");expect(s.messages).toEqual([]);expect(s.toolCalls).toEqual([]);+ expect(s.activity).toBeNull();expect(s.swarmRuns).toEqual({});expect(s.streamingText).toBe("");expect(s.status).toBe("idle");@@ -373,6 +435,7 @@ describe("reset", () => {expect(s.sessionId).toBeNull();expect(s.streamingText).toBe("");expect(s.toolCalls).toEqual([]);+ expect(s.activity).toBeNull();expect(s.swarmRuns).toEqual({});expect(s.status).toBe("idle");expect(s.streamingSessionId).toBeNull();diff --git a/frontend/src/stores/__tests__/streaming_area.test.tsx b/frontend/src/stores/__tests__/streaming_area.test.tsxindex 1bec6658f..543aab688 100755--- a/frontend/src/stores/__tests__/streaming_area.test.tsx+++ b/frontend/src/stores/__tests__/streaming_area.test.tsx@@ -1,7 +1,6 @@import { describe, it, expect, beforeEach } from "vitest";import { render, screen, act } from "@testing-library/react";import { useAgentStore } from "@/stores/agent";-import type { AgentMessage } from "@/types/agent";/*** Extracted streaming area component matching Agent.tsx structure.@@ -10,10 +9,7 @@ import type { AgentMessage } from "@/types/agent";function StreamingArea() {const status = useAgentStore((s) => s.status);const streamingText = useAgentStore((s) => s.streamingText);- const toolCalls = useAgentStore((s) => s.toolCalls);- const messages = useAgentStore((s) => s.messages);-- const reasoningActive = streamingText.startsWith("Thinking:");+ const activity = useAgentStore((s) => s.activity);if (status !== "streaming") return null;@@ -22,14 +18,12 @@ function StreamingArea() {<div className="flex gap-3"><div data-testid="avatar">A</div><div className="flex-1 min-w-0 space-y-1.5">- {!reasoningActive && !streamingText && toolCalls.length === 0 && !messages.some((m: AgentMessage) => m.type === "swarm_status") && (- <div data-testid="placeholder">- <span>Agent working...</span>- </div>- )}- {reasoningActive && !streamingText && (- <div data-testid="reasoning">- <span>Reasoning...</span>+ {activity && (+ <div data-testid="activity-line">+ <span>{activity.state}</span>+ {activity.steps.map((step) => (+ <span key={step.id} data-testid={`tool-${step.id}`}>{step.tool}</span>+ ))}</div>)}{streamingText && (@@ -38,13 +32,6 @@ function StreamingArea() {<span data-testid="cursor" /></div>)}- {toolCalls.length > 0 && (- <div data-testid="tool-progress">- {toolCalls.map((tc) => (- <span key={tc.id} data-testid={`tool-${tc.id}`}>{tc.tool}</span>- ))}- </div>- )}</div></div></div>@@ -56,37 +43,37 @@ beforeEach(() => {});describe("StreamingArea — DOM stability during state transitions", () => {- it("renders placeholder when streaming starts with no content", () => {+ it("renders one activity line when streaming starts with no content", () => {act(() => {useAgentStore.getState().setSessionId("s1");+ useAgentStore.getState().startActivity("attempt-1");useAgentStore.getState().setStatus("streaming");});render(<StreamingArea />);expect(screen.getByTestId("streaming-wrapper")).toBeInTheDocument();- expect(screen.getByTestId("placeholder")).toBeInTheDocument();+ expect(screen.getByTestId("activity-line")).toHaveTextContent("thinking");});- it("wrapper stays in DOM when placeholder transitions to streaming text", () => {+ it("wrapper and activity line stay in DOM when text starts streaming", () => {act(() => {useAgentStore.getState().setSessionId("s1");+ useAgentStore.getState().startActivity("attempt-1");useAgentStore.getState().setStatus("streaming");});render(<StreamingArea />);const wrapper = screen.getByTestId("streaming-wrapper");+ const activityLine = screen.getByTestId("activity-line");- // Placeholder visible initially- expect(screen.getByTestId("placeholder")).toBeInTheDocument();-- // Transition: append delta → placeholder disappears, text appearsact(() => {+ useAgentStore.getState().setActivityState("responding");useAgentStore.getState().appendDelta("Hello");});- // Wrapper must still be the same DOM nodeexpect(screen.getByTestId("streaming-wrapper")).toBe(wrapper);- expect(screen.queryByTestId("placeholder")).not.toBeInTheDocument();+ expect(screen.getByTestId("activity-line")).toBe(activityLine);+ expect(screen.getByTestId("activity-line")).toHaveTextContent("responding");expect(screen.getByTestId("streaming-text")).toBeInTheDocument();expect(screen.getByTestId("streaming-text")).toHaveTextContent("Hello");});@@ -94,6 +81,7 @@ describe("StreamingArea — DOM stability during state transitions", () => {it("wrapper stays in DOM when text transitions to include tool calls", () => {act(() => {useAgentStore.getState().setSessionId("s1");+ useAgentStore.getState().startActivity("attempt-1");useAgentStore.getState().setStatus("streaming");useAgentStore.getState().appendDelta("Analyzing...");});@@ -113,7 +101,6 @@ describe("StreamingArea — DOM stability during state transitions", () => {expect(screen.getByTestId("streaming-wrapper")).toBe(wrapper);expect(screen.getByTestId("streaming-text")).toBeInTheDocument();- expect(screen.getByTestId("tool-progress")).toBeInTheDocument();expect(screen.getByTestId("tool-tc-1")).toHaveTextContent("run_backtest");});@@ -131,6 +118,7 @@ describe("StreamingArea — DOM stability during state transitions", () => {act(() => {useAgentStore.getState().setSessionId("s1");+ useAgentStore.getState().startActivity("attempt-1");useAgentStore.getState().setStatus("streaming");});@@ -178,6 +166,7 @@ describe("StreamingArea — DOM stability during state transitions", () => {it("wrapper unmounts cleanly when streaming ends", () => {act(() => {useAgentStore.getState().setSessionId("s1");+ useAgentStore.getState().startActivity("attempt-1");useAgentStore.getState().setStatus("streaming");useAgentStore.getState().appendDelta("text");});@@ -196,6 +185,7 @@ describe("StreamingArea — DOM stability during state transitions", () => {it("stream_reset clears text but keeps wrapper mounted", () => {act(() => {useAgentStore.getState().setSessionId("s1");+ useAgentStore.getState().startActivity("attempt-1");useAgentStore.getState().setStatus("streaming");useAgentStore.getState().appendDelta("partial");});@@ -209,6 +199,6 @@ describe("StreamingArea — DOM stability during state transitions", () => {expect(screen.getByTestId("streaming-wrapper")).toBe(wrapper);expect(screen.queryByTestId("streaming-text")).not.toBeInTheDocument();- expect(screen.getByTestId("placeholder")).toBeInTheDocument();+ expect(screen.getByTestId("activity-line")).toBeInTheDocument();});});diff --git a/frontend/src/stores/__tests__/streaming_dom.test.ts b/frontend/src/stores/__tests__/streaming_dom.test.tsindex ccaa79cc9..8ee23f71c 100755--- a/frontend/src/stores/__tests__/streaming_dom.test.ts+++ b/frontend/src/stores/__tests__/streaming_dom.test.ts@@ -28,12 +28,14 @@ describe("Streaming DOM stability", () => {// Transition 1: streaming starts, no content yet (placeholder)act(() => {store.setSessionId("test-session");+ store.startActivity("attempt-1");store.setStatus("streaming");});let state = useAgentStore.getState();expect(state.status).toBe("streaming");expect(state.streamingText).toBe("");+ expect(state.activity?.state).toBe("thinking");// Transition 2: reasoning startsact(() => {@@ -66,6 +68,11 @@ describe("Streaming DOM stability", () => {state = useAgentStore.getState();expect(state.toolCalls).toHaveLength(1);+ expect(state.activity).toMatchObject({+ state: "working",+ verb: "runningBacktest",+ steps: [{ id: "tc-1" }],+ });// Transition 5: tool completesact(() => {@@ -98,6 +105,7 @@ describe("Streaming DOM stability", () => {act(() => {store.setSessionId("test-session");+ store.startActivity("attempt-rapid");store.setStatus("streaming");});@@ -118,6 +126,7 @@ describe("Streaming DOM stability", () => {act(() => {store.setSessionId("test-session");+ store.startActivity("attempt-reset");store.setStatus("streaming");store.appendDelta("partial content");});@@ -137,6 +146,7 @@ describe("Streaming DOM stability", () => {act(() => {store.setSessionId("test-session");+ store.startActivity("attempt-tools");store.setStatus("streaming");});@@ -155,5 +165,6 @@ describe("Streaming DOM stability", () => {expect(state.streamingText).toBe("Analyzing data... Done.");expect(state.toolCalls).toHaveLength(2);expect(state.toolCalls.every((tc) => tc.status === "ok")).toBe(true);+ expect(state.activity?.steps.every((step) => step.status === "ok")).toBe(true);});});diff --git a/frontend/src/stores/agent.ts b/frontend/src/stores/agent.tsindex d64440a3f..5cea05895 100644--- a/frontend/src/stores/agent.ts+++ b/frontend/src/stores/agent.ts@@ -3,11 +3,53 @@ import type { AgentMessage, SwarmRunStatus, ToolCallEntry } from "@/types/agent"const SESSION_CACHE_MAX = 5;+export type ActivityState =+ | "thinking"+ | "working"+ | "responding"+ | "stopped"+ | "timeout"+ | "failed"+ | "done";++export type ActivityVerb =+ | "readingMarketData"+ | "writingStrategy"+ | "runningBacktest"+ | "validatingNumbers"+ | "working";++export interface AgentActivity {+ attemptId: string;+ state: ActivityState;+ verb: ActivityVerb;+ steps: ToolCallEntry[];+ startedAt: number;+ endedAt?: number;+}++const VALIDATION_TOOL = /(?:validate|validation|monte_carlo|bootstrap|walk_forward|stress_test|sanity_check)/;+const BACKTEST_TOOL = /backtest/;+const STRATEGY_TOOL = /(?:write|edit|patch|strategy|signal|scaffold|generate)/;+const MARKET_DATA_TOOL = /(?:market_data|search|read|fetch|ticker|quote|candle|orderbook|funding|open_interest|financial|filing|news|profile|screener|fred|iwencai|fund_flow|dragon|northbound|margin|block_trade|shareholder|lockup|sector|research|options_chain)/;++/** Map the latest tool stage to the user-facing activity verb key. */+export function deriveActivityVerb(tool: string | undefined): ActivityVerb {+ const normalized = (tool || "").toLowerCase();+ if (VALIDATION_TOOL.test(normalized)) return "validatingNumbers";+ if (BACKTEST_TOOL.test(normalized)) return "runningBacktest";+ if (STRATEGY_TOOL.test(normalized)) return "writingStrategy";+ if (MARKET_DATA_TOOL.test(normalized)) return "readingMarketData";+ return "working";+}+export interface AgentMessageMeta {attachment?: { filename: string };swarmMode?: boolean;goalMode?: boolean;requestText?: string;+ activity?: AgentActivity;+ partialAttemptId?: string;}export type StoredAgentMessage = AgentMessage & { meta?: AgentMessageMeta };@@ -26,6 +68,7 @@ interface AgentState {streamingSessionId: string | null;toolCalls: ToolCallEntry[];+ activity: AgentActivity | null;swarmRuns: Record<string, SwarmRunStatus>;sseStatus: "disconnected" | "connected" | "reconnecting";@@ -45,6 +88,10 @@ interface AgentState {update: Partial<ToolCallEntry>,) => void;updateOldestRunningToolCall: (tool: string, update: Partial<ToolCallEntry>) => void;+ startActivity: (attemptId: string, startedAt?: number) => void;+ setActivityAttemptId: (attemptId: string) => void;+ setActivityState: (state: ActivityState, at?: number) => void;+ clearActivity: () => void;upsertSwarmStatus: (status: SwarmRunStatus) => void;updateSwarmStatus: (runId: string, updater: (status: SwarmRunStatus) => SwarmRunStatus) => void;@@ -73,6 +120,7 @@ export const useAgentStore = create<AgentState>((set) => ({streamingText: "",streamingSessionId: null,toolCalls: [],+ activity: null,swarmRuns: {},sseStatus: "disconnected",sseRetryAttempt: 0,@@ -113,11 +161,27 @@ export const useAgentStore = create<AgentState>((set) => ({}),addToolCall: (entry) =>- set((s) => ({ toolCalls: [...s.toolCalls, entry] })),+ set((s) => {+ const toolCalls = [...s.toolCalls, entry];+ return {+ toolCalls,+ activity: s.activity ? {+ ...s.activity,+ state: "working",+ verb: deriveActivityVerb(entry.tool),+ steps: toolCalls,+ endedAt: undefined,+ } : null,+ };+ }),updateToolCall: (id, update) =>- set((s) => ({- toolCalls: s.toolCalls.map((tc) => tc.id === id ? { ...tc, ...update } : tc),- })),+ set((s) => {+ const toolCalls = s.toolCalls.map((tc) => tc.id === id ? { ...tc, ...update } : tc);+ return {+ toolCalls,+ activity: s.activity ? { ...s.activity, steps: toolCalls } : null,+ };+ }),updateRunningToolCall: (callId, tool, update) =>set((s) => {const idx = callId@@ -130,7 +194,10 @@ export const useAgentStore = create<AgentState>((set) => ({if (idx < 0) return {};const toolCalls = [...s.toolCalls];toolCalls[idx] = { ...toolCalls[idx], ...update };- return { toolCalls };+ return {+ toolCalls,+ activity: s.activity ? { ...s.activity, steps: toolCalls } : null,+ };}),updateOldestRunningToolCall: (tool, update) =>set((s) => {@@ -144,8 +211,39 @@ export const useAgentStore = create<AgentState>((set) => ({if (idx < 0) return {};const toolCalls = [...s.toolCalls];toolCalls[idx] = { ...toolCalls[idx], ...update };- return { toolCalls };+ return {+ toolCalls,+ activity: s.activity ? { ...s.activity, steps: toolCalls } : null,+ };+ }),+ startActivity: (attemptId, startedAt = Date.now()) =>+ set({+ activity: {+ attemptId,+ state: "thinking",+ verb: "working",+ steps: [],+ startedAt,+ },+ toolCalls: [],+ }),+ setActivityAttemptId: (attemptId) =>+ set((s) => ({+ activity: s.activity ? { ...s.activity, attemptId } : null,+ })),+ setActivityState: (state, at = Date.now()) =>+ set((s) => {+ if (!s.activity) return {};+ const terminal = ["stopped", "timeout", "failed", "done"].includes(state);+ return {+ activity: {+ ...s.activity,+ state,+ endedAt: terminal ? at : undefined,+ },+ };}),+ clearActivity: () => set({ activity: null }),upsertSwarmStatus: (swarmStatus) =>set((s) => {const idx = s.messages.findIndex((m) => m.type === "swarm_status" && m.swarmRunId === swarmStatus.runId);@@ -209,6 +307,7 @@ export const useAgentStore = create<AgentState>((set) => ({status: "idle",streamingText: "",toolCalls: [],+ activity: null,swarmRuns: msgs ? (_swarmSessionCache.get(sid) ?? {}) : {},sessionLoading: !msgs,// Preserve streamingSessionId so the sidebar spinner stays visible@@ -223,7 +322,7 @@ export const useAgentStore = create<AgentState>((set) => ({_id = 0;set({messages: [], status: "idle", streamingText: "",- sessionId: null, toolCalls: [], swarmRuns: {}, sessionLoading: false,+ sessionId: null, toolCalls: [], activity: null, swarmRuns: {}, sessionLoading: false,streamingSessionId: null,});},