"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(frontend): show grounding revision status while the answer is verified
Haozhe Wue6fc147e0242
diff --git a/frontend/src/hooks/__tests__/useSSE.test.ts b/frontend/src/hooks/__tests__/useSSE.test.tsindex 01eeab320..42960bd7a 100644--- a/frontend/src/hooks/__tests__/useSSE.test.ts+++ b/frontend/src/hooks/__tests__/useSSE.test.ts@@ -156,6 +156,26 @@ describe("useSSE — event handling", () => {expect(resetEvents).toEqual([{ reason: "provider_stream_retry" }]);});+ it("dispatches grounding status events", () => {+ const groundingEvents: unknown[] = [];+ const { result } = renderHook(() => useSSE());++ act(() =>+ result.current.connect("http://test/events", {+ grounding_status: (data) => groundingEvents.push(data),+ }),+ );++ act(() =>+ MockEventSource.latest.emit(+ "grounding_status",+ { stage: "revising", round: 1, issues: 2 },+ "evt-grounding",+ ),+ );+ expect(groundingEvents).toEqual([{ stage: "revising", round: 1, issues: 2 }]);+ });+it("falls back to message handler for known event types without specific handler", () => {const messages: unknown[] = [];const { result } = renderHook(() => useSSE());diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.tsindex 6f52a25fa..0979b2917 100644--- a/frontend/src/hooks/useSSE.ts+++ b/frontend/src/hooks/useSSE.ts@@ -85,7 +85,7 @@ export function useSSE(config?: SSEConfig) {// Only subscribe to event types the backend actually emitsconst knownTypes = ["text_delta", "reasoning_delta", "stream_reset", "thinking_done", "tool_call", "tool_result", "compact",- "tool_heartbeat", "tool_progress", "llm_usage",+ "tool_heartbeat", "tool_progress", "llm_usage", "grounding_status","swarm.started", "swarm.event","attempt.created", "attempt.started", "attempt.completed", "attempt.failed","attempt.cancelled",diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 709bb5bc9..bef6029d6 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -597,7 +597,8 @@"failed": "فشل","steps": "{{count}} خطوات","continue": "متابعة",- "reattach": "إعادة الاتصال"+ "reattach": "إعادة الاتصال",+ "checkingFigures": "جارٍ التحقق من الأرقام في هذه الإجابة (الجولة {{round}})…"},"resumeConnector": "استئناف الموصل","resumeConnectorTitle": "مسح مفتاح الإيقاف واستئناف نشاط الموصل",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex 0a36d8591..c5b6d120b 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -602,7 +602,8 @@"failed": "Fehlgeschlagen","steps": "{{count}} Schritte","continue": "Fortsetzen",- "reattach": "Erneut verbinden"+ "reattach": "Erneut verbinden",+ "checkingFigures": "Zahlen in dieser Antwort werden geprüft (Runde {{round}}) …"},"resumeConnector": "Connector fortsetzen","resumeConnectorTitle": "Kill-Switch löschen und Connector-Aktivität wieder aktivieren",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 0c96bd7f2..0bbef91c7 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -602,7 +602,8 @@"failed": "Failed","steps": "{{count}} steps","continue": "Continue",- "reattach": "Re-attach"+ "reattach": "Re-attach",+ "checkingFigures": "Checking the figures in this answer (round {{round}})…"},"resumeConnector": "Resume connector","resumeConnectorTitle": "Clear the kill switch and re-enable connector activity",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 83086b976..989ae85dd 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -602,7 +602,8 @@"failed": "Falló","steps": "{{count}} pasos","continue": "Continuar",- "reattach": "Reconectar"+ "reattach": "Reconectar",+ "checkingFigures": "Verificando las cifras de esta respuesta (ronda {{round}})…"},"resumeConnector": "Reanudar conector","resumeConnectorTitle": "Desactivar el interruptor de emergencia y reanudar la actividad del conector",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex cf7ed930e..b8d72d68a 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -597,7 +597,8 @@"failed": "失敗","steps": "{{count}} ステップ","continue": "続行",- "reattach": "再接続"+ "reattach": "再接続",+ "checkingFigures": "回答内の数値を確認中({{round}} 回目)…"},"resumeConnector": "コネクタを再開","resumeConnectorTitle": "キルスイッチを解除してコネクタ活動を再開",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex db5171f97..542b80ab9 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -597,7 +597,8 @@"failed": "실패","steps": "{{count}}단계","continue": "계속",- "reattach": "다시 연결"+ "reattach": "다시 연결",+ "checkingFigures": "답변 속 수치 확인 중({{round}}차)…"},"resumeConnector": "커넥터 재개","resumeConnectorTitle": "킬 스위치를 해제하고 커넥터 활동을 재개",diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex adad7b35f..cebfcf558 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -602,7 +602,8 @@"failed": "Falha","steps": "Etapas {{count}}","continue": "Continuar",- "reattach": "Anexe novamente"+ "reattach": "Anexe novamente",+ "checkingFigures": "Verificando os números desta resposta (rodada {{round}})…"},"resumeConnector": "Retomar conector","resumeConnectorTitle": "Limpe o kill switch e reative a atividade do conector",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex b578b8adc..69aed134b 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -597,7 +597,8 @@"failed": "失败","steps": "{{count}} 个步骤","continue": "继续",- "reattach": "重新连接"+ "reattach": "重新连接",+ "checkingFigures": "正在核对答案中的数字(第 {{round}} 轮)…"},"resumeConnector": "恢复连接器","resumeConnectorTitle": "清除熔断开关并恢复连接器活动",diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 0685429d2..06c905941 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -1,7 +1,7 @@import { useTranslation } from 'react-i18next';import { useEffect, useRef, useState, useMemo, useCallback } from "react";import { useSearchParams } from "react-router";-import { ArrowDown } from "lucide-react";+import { ArrowDown, ShieldCheck } from "lucide-react";import { toast } from "sonner";import {useAgentStore,@@ -95,6 +95,12 @@ interface RuntimeIdentity {reasoningEffort?: string;}+/** A final answer held back while the grounding gate re-checks a revised draft. */+interface GroundingRevision {+ attemptId: string;+ round: number;+}+function toolProgressKey(callId: string | undefined, tool: string): string {return callId ? `call:${callId}` : `tool:${tool}`;}@@ -249,6 +255,7 @@ export function Agent() {/* Connector runtime channel state (SPEC Consent §1/§4/§5) */const [liveItems, setLiveItems] = useState<LiveItem[]>([]);+ const [groundingRevision, setGroundingRevision] = useState<GroundingRevision | null>(null);const [visibleRowCount, setVisibleRowCount] = useState(TIMELINE_WINDOW_SIZE);const visibleRowsSessionRef = useRef<string | null>(null);const [llmSettings, setLlmSettings] = useState<LLMSettings | null>(null);@@ -737,6 +744,8 @@ export function Agent() {text_delta: (d) => {touch();replayAttemptSeenRef.current = true;+ // Answer text only streams once the grounding gate has released it.+ setGroundingRevision(null);if (!identifyActivity(d, "responding")) return;if (act().status !== "streaming") act().setStatus("streaming");queueStreamUpdate(String(d.delta || ""), false);@@ -759,6 +768,26 @@ export function Agent() {},thinking_done: () => { touch(); /* don't flush — keep streaming text visible */ },+ grounding_status: (d) => {+ touch();+ replayAttemptSeenRef.current = true;+ if (d.stage !== "revising") {+ // released_redacted: the cut answer (with its own footnote) follows+ // as text_delta; the status line has nothing left to say.+ setGroundingRevision(null);+ return;+ }+ if (typeof d.round !== "number" || d.round < 1) return;+ if (!identifyActivity(d, "thinking")) return;+ if (act().status !== "streaming") act().setStatus("streaming");+ const attemptId = act().activity?.attemptId;+ if (!attemptId) return;+ // Pinned to the attempt so a line from a run that ended without text+ // (timeout, cancel, failure) never resurfaces on the next attempt.+ setGroundingRevision({ attemptId, round: d.round });+ scrollToBottom();+ },+tool_call: (d) => {touch();replayAttemptSeenRef.current = true;@@ -886,6 +915,7 @@ export function Agent() {"attempt.completed": async (d) => {touch();+ setGroundingRevision(null);const attemptId = String(d.attempt_id || "");markBackgroundCompletion(sid, attemptId);if (act().sessionId !== sid) {@@ -1025,6 +1055,7 @@ export function Agent() {"attempt.failed": (d) => {touch();+ setGroundingRevision(null);const attemptId = String(d.attempt_id || "");if (act().sessionId !== sid) {act().clearStreamingSession(sid);@@ -1066,6 +1097,7 @@ export function Agent() {// to avoid showing an error bubble."attempt.cancelled": (d) => {touch();+ setGroundingRevision(null);const attemptId = String(d.attempt_id || "");if (act().sessionId !== sid) {act().clearStreamingSession(sid);@@ -1247,6 +1279,7 @@ export function Agent() {genRef.current = gen;doDisconnect();setRuntimeIdentity({});+ setGroundingRevision(null);// Live-channel timeline items are per-session; clear on switch.setLiveItems([]);liveRuntimeRef.current?.resetSession();@@ -1274,6 +1307,7 @@ export function Agent() {const gen = genRef.current + 1;genRef.current = gen;setRuntimeIdentity({});+ setGroundingRevision(null);const seed = curMsgs.length > 0 ? curMsgs : getCachedSession(urlSessionId);// switchSession() drops the live activity so replay can rebuild its// steps without duplicating them — but the attempt's start time is not@@ -1293,6 +1327,7 @@ export function Agent() {genRef.current += 1;doDisconnect();setRuntimeIdentity({});+ setGroundingRevision(null);setLiveItems([]);liveRuntimeRef.current?.resetSession();if (curSid && curMsgs.length > 0) cacheSession(curSid, curMsgs);@@ -1714,6 +1749,14 @@ export function Agent() {});}, [timelineRows.length]);+ const groundingRound = (+ status === "streaming"+ && groundingRevision+ && activity?.attemptId === groundingRevision.attemptId+ )+ ? groundingRevision.round+ : null;+return (<div className="flex flex-col flex-1 min-w-0 overflow-hidden h-full"><ModelRuntimeBar@@ -1844,6 +1887,16 @@ export function Agent() {<AgentAvatar /><div className="flex-1 min-w-0 space-y-2">{activity && <ActivityLine activity={activity} reasoningTail={reasoningTail} />}+ {groundingRound !== null && (+ <p+ role="status"+ aria-live="polite"+ className="flex items-center gap-2 px-3 text-xs text-muted-foreground"+ >+ <ShieldCheck className="h-3.5 w-3.5 shrink-0 text-muted-foreground/80" aria-hidden="true" />+ <span>{t("agent.activity.checkingFigures", { round: groundingRound })}</span>+ </p>+ )}{streamingText && (<div aria-live="polite" aria-atomic="false"><MarkdownContent content={streamingText} streaming showCursor />diff --git a/frontend/src/pages/__tests__/AgentGroundingStatus.test.tsx b/frontend/src/pages/__tests__/AgentGroundingStatus.test.tsxnew file mode 100644index 000000000..e3fa53f0d--- /dev/null+++ b/frontend/src/pages/__tests__/AgentGroundingStatus.test.tsx@@ -0,0 +1,156 @@+import { act, render, screen, waitFor } from "@testing-library/react";+import { createMemoryRouter, RouterProvider } from "react-router";+import { Agent } from "../Agent";+import { useAgentStore } from "@/stores/agent";++// While the grounding gate holds a rejected draft back, the answer text is+// buffered server-side and nothing streams for up to a few minutes. The+// backend announces that window with `grounding_status`; the chat shows one+// status line for it and drops the line the moment the answer text arrives.++const apiMock = vi.hoisted(() => ({+ getGoal: vi.fn(),+ getLLMSettings: vi.fn(),+ getRun: vi.fn(),+ getSessionMessages: vi.fn(),+ sseUrl: vi.fn((sid: string) => `/sessions/${sid}/events`),+}));++const sseMock = vi.hoisted(() => ({+ connect: vi.fn(),+ disconnect: vi.fn(),+ onStatusChange: vi.fn(),+}));++vi.mock("@/lib/api", async () => {+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");+ return { ...actual, api: apiMock };+});++vi.mock("@/hooks/useSSE", () => ({+ useSSE: () => sseMock,+}));++type Handlers = Record<string, (data: Record<string, unknown>) => void>;++function latestHandlers(): Handlers {+ const call = sseMock.connect.mock.calls.at(-1);+ if (!call) throw new Error("useSSE.connect was never called");+ return call[1] as Handlers;+}++const STATUS_TEXT = /Checking the figures in this answer/;++async function renderStreamingAttempt(attemptId: string): Promise<void> {+ const router = createMemoryRouter(+ [{ path: "/", element: <Agent /> }],+ { initialEntries: ["/?session=session-one"] },+ );+ render(<RouterProvider router={router} />);+ await waitFor(() => expect(sseMock.connect).toHaveBeenCalled());+ act(() => {+ latestHandlers()["attempt.started"]({ attempt_id: attemptId });+ });+ expect(useAgentStore.getState().status).toBe("streaming");+}++describe("Agent grounding status line", () => {+ beforeEach(() => {+ useAgentStore.getState().reset();+ sseMock.connect.mockClear();+ apiMock.getGoal.mockResolvedValue(null);+ apiMock.getRun.mockResolvedValue({});+ apiMock.getSessionMessages.mockResolvedValue([]);+ apiMock.getLLMSettings.mockResolvedValue({+ provider: "deepseek",+ model_name: "deepseek-v4-pro",+ base_url: "https://api.deepseek.com/v1",+ api_key_configured: true,+ api_key_required: true,+ temperature: 0,+ timeout_seconds: 120,+ max_retries: 2,+ reasoning_effort: "low",+ sse_timeout_seconds: 90,+ env_path: "agent/.env",+ providers: [],+ });+ Object.defineProperty(HTMLElement.prototype, "scrollTo", {+ configurable: true,+ value: vi.fn(),+ });+ });++ it("shows the revision round and clears it when the answer text arrives", async () => {+ await renderStreamingAttempt("attempt-1");+ expect(screen.queryByText(STATUS_TEXT)).not.toBeInTheDocument();++ act(() => {+ latestHandlers().grounding_status({+ attempt_id: "attempt-1",+ stage: "revising",+ round: 2,+ issues: 3,+ });+ });+ expect(+ screen.getByText("Checking the figures in this answer (round 2)…"),+ ).toBeInTheDocument();++ act(() => {+ latestHandlers().text_delta({ attempt_id: "attempt-1", delta: "Verified answer", iter: 6 });+ });+ expect(screen.queryByText(STATUS_TEXT)).not.toBeInTheDocument();+ });++ it("follows the round number of the latest revising event", async () => {+ await renderStreamingAttempt("attempt-1");++ act(() => {+ latestHandlers().grounding_status({ attempt_id: "attempt-1", stage: "revising", round: 1, issues: 1 });+ });+ expect(screen.getByText("Checking the figures in this answer (round 1)…")).toBeInTheDocument();++ act(() => {+ latestHandlers().grounding_status({ attempt_id: "attempt-1", stage: "revising", round: 3, issues: 1 });+ });+ expect(screen.getByText("Checking the figures in this answer (round 3)…")).toBeInTheDocument();+ expect(screen.getAllByText(STATUS_TEXT)).toHaveLength(1);+ });++ it("clears on released_redacted before the redacted answer streams", async () => {+ await renderStreamingAttempt("attempt-1");++ act(() => {+ latestHandlers().grounding_status({ attempt_id: "attempt-1", stage: "revising", round: 1, issues: 2 });+ });+ expect(screen.getByText(STATUS_TEXT)).toBeInTheDocument();++ act(() => {+ latestHandlers().grounding_status({ attempt_id: "attempt-1", stage: "released_redacted", removed: 2 });+ });+ expect(screen.queryByText(STATUS_TEXT)).not.toBeInTheDocument();+ expect(useAgentStore.getState().status).toBe("streaming");+ });++ it("does not carry a failed attempt's status line into the next attempt", async () => {+ await renderStreamingAttempt("attempt-1");++ act(() => {+ latestHandlers().grounding_status({ attempt_id: "attempt-1", stage: "revising", round: 1, issues: 2 });+ });+ expect(screen.getByText(STATUS_TEXT)).toBeInTheDocument();++ act(() => {+ latestHandlers()["attempt.failed"]({ attempt_id: "attempt-1", error: "provider down" });+ });+ expect(useAgentStore.getState().status).toBe("idle");+ expect(screen.queryByText(STATUS_TEXT)).not.toBeInTheDocument();++ act(() => {+ latestHandlers()["attempt.started"]({ attempt_id: "attempt-2" });+ });+ expect(useAgentStore.getState().status).toBe("streaming");+ expect(screen.queryByText(STATUS_TEXT)).not.toBeInTheDocument();+ });+});