"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(frontend): structured API error details and dirty-form save gate
shadowinlifeaba9c897c853
diff --git a/frontend/src/components/settings/ChannelConfigPanel.tsx b/frontend/src/components/settings/ChannelConfigPanel.tsxindex 2a90262d9..03ca8e5f4 100644--- a/frontend/src/components/settings/ChannelConfigPanel.tsx+++ b/frontend/src/components/settings/ChannelConfigPanel.tsx@@ -19,6 +19,7 @@ import {type ChannelConfigEntry,type ChannelFieldHint,type ChannelPutBody,+ type ChannelTestBody,type ChannelTestResult,} from "@/lib/api";@@ -26,10 +27,6 @@ const fieldClass ="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-60";const labelClass = "text-sm font-medium";const hintClass = "text-xs text-muted-foreground";-// `errorFromResponse` collapses a structured `detail` object to its string-// form, so the HTTP status is the reliable signal and probing for a `code` is-// best-effort only.-const OPAQUE_DETAIL = "[object Object]";type FormValue = string | boolean | string[];@@ -42,18 +39,8 @@ interface ApiFailure {/** Read a failed request into status/code/message without trusting its shape. */function describeApiFailure(error: unknown): ApiFailure {const status = error instanceof ApiError ? error.status : null;- const rawMessage = error instanceof Error ? error.message : "";- const message = rawMessage === OPAQUE_DETAIL ? "" : rawMessage;- let code: string | null = null;- if (error && typeof error === "object") {- const carrier = error as { code?: unknown; detail?: unknown };- if (typeof carrier.code === "string") {- code = carrier.code;- } else if (carrier.detail && typeof carrier.detail === "object" && "code" in carrier.detail) {- const detailCode = (carrier.detail as { code?: unknown }).code;- if (typeof detailCode === "string") code = detailCode;- }- }+ const message = error instanceof Error ? error.message : "";+ const code = error instanceof ApiError && error.code ? error.code : null;return { status, code, message };}@@ -274,10 +261,11 @@ export function ChannelConfigPanel({try {// Pristine forms exercise the saved config (empty body); a dirty form// tests exactly what is on screen, including a typed-but-unsaved secret.- const result = await api.testChannel(- name,- isDirty ? { config: buildPatch() } : undefined,- );+ const body: ChannelTestBody = { config: buildPatch() };+ for (const field of entry.fields) {+ if (field.secret && clears[field.key]) body[`clear_${field.key}`] = true;+ }+ const result = await api.testChannel(name, isDirty ? body : undefined);setTestResult(result);if (result.ok) toast.success(t("settings.channels.config.testOk"));else toast.error(testCodeText[result.code]);@@ -547,7 +535,7 @@ export function ChannelConfigPanel({</button><buttontype="submit"- disabled={formDisabled}+ disabled={formDisabled || !isDirty}className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-70">{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}@@ -617,4 +605,4 @@ export function ChannelConfigPanel({) : null}</div>);-}\ No newline at end of file+}diff --git a/frontend/src/components/settings/ChannelSettings.tsx b/frontend/src/components/settings/ChannelSettings.tsxindex c31d07bb3..d296a01e2 100644--- a/frontend/src/components/settings/ChannelSettings.tsx+++ b/frontend/src/components/settings/ChannelSettings.tsx@@ -312,4 +312,4 @@ export function ChannelSettings() {)}</section>);-}\ No newline at end of file+}diff --git a/frontend/src/components/settings/__tests__/ChannelSettings.test.tsx b/frontend/src/components/settings/__tests__/ChannelSettings.test.tsxindex a87fd888b..f773733b3 100644--- a/frontend/src/components/settings/__tests__/ChannelSettings.test.tsx+++ b/frontend/src/components/settings/__tests__/ChannelSettings.test.tsx@@ -80,7 +80,7 @@ function dingtalkEntry(overrides: Record<string, unknown> = {}) {function channelsConfig(overrides: Record<string, unknown> = {}) {return {- config_path: "/home/user/.vibe-trading/agent.json",+ config_path: "~/.vibe-trading/agent.json",writable: true,runtime_running: false,channels: { dingtalk: dingtalkEntry() },@@ -215,7 +215,9 @@ describe("ChannelSettings config panel", () => {});it("offers Enable anyway when the enable transition is rejected with 422", async () => {- apiMock.putChannelConfig.mockRejectedValueOnce(new ApiError("invalid_credentials", 422));+ apiMock.putChannelConfig.mockRejectedValueOnce(+ new ApiError("HTTP 401: invalid appKey/appSecret", 422, "invalid_credentials"),+ );await renderExpanded();fireEvent.click(screen.getByRole("checkbox", { name: "Enable channel" }));@@ -224,7 +226,7 @@ describe("ChannelSettings config panel", () => {expect(screen.getByText("The provider rejected these credentials, so the channel was not enabled.",)).toBeInTheDocument();- expect(screen.getByText("Provider response: invalid_credentials")).toBeInTheDocument();+ expect(screen.getByText("Provider response: HTTP 401: invalid appKey/appSecret")).toBeInTheDocument();fireEvent.click(anyway);@@ -285,6 +287,34 @@ describe("ChannelSettings config panel", () => {expect((secondBody.config as Record<string, unknown>).client_secret).toBeUndefined();});+ it("disables Save until the form is dirty", async () => {+ await renderExpanded();++ const save = screen.getByRole("button", { name: "Save configuration" });+ expect(save).toBeDisabled();++ fireEvent.change(screen.getByPlaceholderText("Keep current (****abcd)"), {+ target: { value: "typed-secret" },+ });+ expect(save).toBeEnabled();+ });++ it("tests with a pending secret clear excluded", async () => {+ await renderExpanded();++ fireEvent.click(screen.getByRole("checkbox", { name: "Clear" }));+ fireEvent.click(screen.getByRole("button", { name: "Test connection" }));++ await waitFor(() => expect(apiMock.testChannel).toHaveBeenCalledTimes(1));+ const [name, body] = apiMock.testChannel.mock.calls[0] as [string, { config?: Record<string, unknown> }];+ expect(name).toBe("dingtalk");+ expect(body).toMatchObject({+ config: expect.objectContaining({ client_id: "ding_appkey" }),+ clear_client_secret: true,+ });+ expect(body.config?.client_secret).toBeUndefined();+ });+it("disables every control and explains a non-writable YAML config", async () => {apiMock.getChannelsConfig.mockResolvedValue(channelsConfig({ writable: false }));await renderExpanded();@@ -333,4 +363,4 @@ describe("ChannelSettings config panel", () => {expect(guideToggle).toHaveAttribute("aria-expanded", "false");expect(screen.queryByText(/Create an app in the DingTalk developer console/)).not.toBeInTheDocument();});-});\ No newline at end of file+});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex db067f727..7327c7554 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -10,11 +10,13 @@ const BASE = "";export class ApiError extends Error {status: number;+ code?: string;- constructor(message: string, status: number) {+ constructor(message: string, status: number, code?: string) {super(message);this.name = "ApiError";this.status = status;+ this.code = code;}}@@ -294,16 +296,25 @@ export interface PortfolioSettingsResponse {async function errorFromResponse(res: Response): Promise<ApiError> {let detail = `HTTP ${res.status}`;+ let code: string | undefined;try {const body = await res.json();// Options endpoints report errors under an `error` key// ({status:"error", error} / {ok:false, error}) rather than detail/message.- detail = body.detail || body.message || body.error || detail;+ const raw = body.detail ?? body.message ?? body.error;+ if (typeof raw === "string" && raw) {+ detail = raw;+ } else if (raw && typeof raw === "object") {+ const structured = raw as { code?: unknown; message?: unknown };+ if (typeof structured.code === "string" && structured.code) code = structured.code;+ if (typeof structured.message === "string" && structured.message) detail = structured.message;+ else if (code) detail = code;+ }} catch { /* ignore */ }if (res.status === 401 || res.status === 403) {detail = getAuthRequiredMessage();}- return new ApiError(detail, res.status);+ return new ApiError(detail, res.status, code);}async function request<T>(path: string, options?: RequestInit): Promise<T> {@@ -886,6 +897,7 @@ export interface ChannelConfigEntry {}export interface ChannelsConfigResponse {+ /** Display-only path (home-relative `~/...` or a bare basename), never absolute. */config_path: string;writable: boolean;runtime_running: boolean;@@ -907,9 +919,11 @@ export interface ChannelPutResult {applied: "hot_swapped" | "reset" | "deferred";}-export interface ChannelTestBody {+export type ChannelTestBody = {config?: Record<string, unknown>;-}+} & {+ [clearFlag: `clear_${string}`]: boolean | undefined;+};export interface ChannelTestResult {ok: boolean;