The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Surface API failures in a bottom error card with response bodies.
debajyoti-truefoundryc8b0a7e468e6
diff --git a/packages/frontend/src/ApiErrorCard.tsx b/packages/frontend/src/ApiErrorCard.tsxnew file mode 100644index 000000000..cb129224f--- /dev/null+++ b/packages/frontend/src/ApiErrorCard.tsx@@ -0,0 +1,74 @@+import { useSyncExternalStore } from 'react';+import {+ clearApiErrors,+ dismissApiError,+ getApiErrorsSnapshot,+ subscribeApiErrors,+ type ApiErrorRecord,+} from './apiErrors';++function formatTime(timestamp: number): string {+ return new Date(timestamp).toLocaleTimeString(undefined, { hour12: false });+}++function formatBody(body: string): string {+ if (body.length === 0) return '(empty response body)';+ try {+ return JSON.stringify(JSON.parse(body), null, 2);+ } catch {+ return body;+ }+}++function ApiErrorRow({ error }: { error: ApiErrorRecord }) {+ return (+ <details className="api-error-row">+ <summary>+ <span className="api-error-status">{error.status ?? 'NET'}</span>+ <span className="api-error-method">{error.method}</span>+ <span className="api-error-url" title={error.url}>+ {error.url}+ </span>+ <span className="api-error-time">{formatTime(error.timestamp)}</span>+ <button+ type="button"+ className="api-error-dismiss"+ aria-label="Dismiss error"+ onClick={event => {+ event.preventDefault();+ dismissApiError(error.id);+ }}+ >+ ×+ </button>+ </summary>+ {error.statusText ? <div className="api-error-statustext">{error.statusText}</div> : null}+ <pre className="api-error-body">{formatBody(error.body)}</pre>+ </details>+ );+}++/** Fixed card at the bottom of the viewport listing every failed API call. */+export function ApiErrorCard() {+ const errors = useSyncExternalStore(subscribeApiErrors, getApiErrorsSnapshot);+ if (errors.length === 0) return null;++ return (+ <div className="api-error-card" role="alert">+ <div className="api-error-card-header">+ <span>+ API errors ({errors.length}+ {errors.length === 1 ? '' : ', latest last'})+ </span>+ <button type="button" className="api-error-clear" onClick={clearApiErrors}>+ Clear all+ </button>+ </div>+ <div className="api-error-list">+ {errors.map(error => (+ <ApiErrorRow key={error.id} error={error} />+ ))}+ </div>+ </div>+ );+}diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsxindex 58c4ecd35..45adcee71 100644--- a/packages/frontend/src/App.tsx+++ b/packages/frontend/src/App.tsx@@ -5,6 +5,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';import { ThemeProvider } from 'tfy-web-components/components/theme/useTheme';import { AgentSessionClient } from 'truefoundry-gateway-sdk/agents';import { PrivateAgentSessionClient } from 'truefoundry-gateway-sdk/agents/private';+import { ApiErrorCard } from './ApiErrorCard';import { ServerCapabilitiesProvider } from './capabilities';import { getCapabilities, listModels, type ServerCapabilities } from './catalog';import { AppComposerShell } from './ComposerShell';@@ -103,6 +104,7 @@ function ChatApp({<div className="app-thread-body"><Thread /></div>+ <ApiErrorCard /></div></div></ErrorToasterProvider>@@ -165,12 +167,18 @@ export function App() {return (<div className="boot-screen" data-error="true">Failed to load application configuration: {bootError}+ <ApiErrorCard /></div>);}if (loading || defaultAgentSpec == null || capabilities == null) {- return <div className="boot-screen">Loading application…</div>;+ return (+ <div className="boot-screen">+ Loading application…+ <ApiErrorCard />+ </div>+ );}return <ChatApp defaultAgentSpec={defaultAgentSpec} capabilities={capabilities} />;diff --git a/packages/frontend/src/apiErrors.test.ts b/packages/frontend/src/apiErrors.test.tsnew file mode 100644index 000000000..9fd7a0d09--- /dev/null+++ b/packages/frontend/src/apiErrors.test.ts@@ -0,0 +1,58 @@+import assert from 'node:assert/strict';+import { beforeEach, describe, it } from 'node:test';+import { clearApiErrors, getApiErrorsSnapshot, installApiErrorInterceptor, subscribeApiErrors } from './apiErrors';++let stubbedResponse: () => Response | Promise<Response>;++globalThis.fetch = () => Promise.resolve(stubbedResponse());+installApiErrorInterceptor();++describe('api error interceptor', () => {+ beforeEach(() => {+ clearApiErrors();+ });++ it('records failed responses with status and body, and keeps the body readable', async () => {+ stubbedResponse = () =>+ new Response(JSON.stringify({ message: 'boom' }), { status: 500, statusText: 'Internal Server Error' });+ const response = await fetch('/v1/models', { method: 'POST' });++ const [record] = getApiErrorsSnapshot();+ assert.ok(record);+ assert.equal(record.method, 'POST');+ assert.equal(record.url, '/v1/models');+ assert.equal(record.status, 500);+ assert.equal(record.statusText, 'Internal Server Error');+ assert.equal(record.body, '{"message":"boom"}');+ assert.deepEqual(await response.json(), { message: 'boom' });+ });++ it('ignores successful responses', async () => {+ stubbedResponse = () => new Response('ok', { status: 200 });+ await fetch('/v1/models');+ assert.equal(getApiErrorsSnapshot().length, 0);+ });++ it('records network failures and rethrows', async () => {+ stubbedResponse = () => {+ throw new Error('connection refused');+ };+ await assert.rejects(fetch('/v1/skills'), /connection refused/);++ const [record] = getApiErrorsSnapshot();+ assert.ok(record);+ assert.equal(record.status, undefined);+ assert.equal(record.body, 'connection refused');+ });++ it('notifies subscribers on new errors', async () => {+ let notified = 0;+ const unsubscribe = subscribeApiErrors(() => {+ notified += 1;+ });+ stubbedResponse = () => new Response('nope', { status: 404 });+ await fetch('/missing');+ unsubscribe();+ assert.ok(notified >= 1);+ });+});diff --git a/packages/frontend/src/apiErrors.ts b/packages/frontend/src/apiErrors.tsnew file mode 100644index 000000000..5507cf1b4--- /dev/null+++ b/packages/frontend/src/apiErrors.ts@@ -0,0 +1,111 @@+/**+ * Global fetch interceptor + subscribable store for API errors.+ *+ * Both catalog.ts and the truefoundry-gateway-sdk clients resolve the global+ * `fetch` at request time, so patching it once at startup captures every API+ * failure (HTTP >= 400 and network errors) along with the response body.+ */++export interface ApiErrorRecord {+ id: number;+ timestamp: number;+ method: string;+ url: string;+ /** Absent for network-level failures that produced no response. */+ status?: number;+ statusText?: string;+ /** Error response body (or error message for network failures). */+ body: string;+}++const MAX_ERRORS = 50;+const MAX_BODY_CHARS = 10_000;++let nextId = 1;+let errors: readonly ApiErrorRecord[] = [];+const listeners = new Set<() => void>();++function emit(): void {+ for (const listener of listeners) listener();+}++function push(record: Omit<ApiErrorRecord, 'id' | 'timestamp'>): void {+ errors = [...errors.slice(-(MAX_ERRORS - 1)), { ...record, id: nextId++, timestamp: Date.now() }];+ emit();+}++export function subscribeApiErrors(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++export function getApiErrorsSnapshot(): readonly ApiErrorRecord[] {+ return errors;+}++export function dismissApiError(id: number): void {+ errors = errors.filter(error => error.id !== id);+ emit();+}++export function clearApiErrors(): void {+ if (errors.length === 0) return;+ errors = [];+ emit();+}++function requestMethod(input: RequestInfo | URL, init?: RequestInit): string {+ if (init?.method) return init.method.toUpperCase();+ if (input instanceof Request) return input.method.toUpperCase();+ return 'GET';+}++function requestUrl(input: RequestInfo | URL): string {+ if (input instanceof Request) return input.url;+ return input instanceof URL ? input.href : input;+}++async function readErrorBody(response: Response): Promise<string> {+ try {+ const text = await response.clone().text();+ return text.length > MAX_BODY_CHARS ? `${text.slice(0, MAX_BODY_CHARS)}… (truncated)` : text;+ } catch {+ return '(response body could not be read)';+ }+}++let installed = false;++/** Patch the global fetch once; must run before any API client is created. */+export function installApiErrorInterceptor(): void {+ if (installed) return;+ installed = true;+ const originalFetch = globalThis.fetch.bind(globalThis);+ globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {+ const method = requestMethod(input, init);+ const url = requestUrl(input);+ let response: Response;+ try {+ response = await originalFetch(input, init);+ } catch (error) {+ push({+ method,+ url,+ body: error instanceof Error ? error.message : String(error),+ });+ throw error;+ }+ if (response.status >= 400) {+ push({+ method,+ url,+ status: response.status,+ statusText: response.statusText,+ body: await readErrorBody(response),+ });+ }+ return response;+ };+}diff --git a/packages/frontend/src/index.css b/packages/frontend/src/index.cssindex ddff13648..88622af97 100644--- a/packages/frontend/src/index.css+++ b/packages/frontend/src/index.css@@ -106,6 +106,7 @@ textarea {}.app-main {+ position: relative;flex: 1;min-width: 0;display: flex;@@ -740,7 +741,170 @@ textarea {background: var(--accent);}+/* API error card: anchored to the bottom of the chat column (or boot screen),+ sized to the thread width so it lines up with the composer. */+.api-error-card {+ position: absolute;+ bottom: 0.75rem;+ inset-inline: 0;+ margin-inline: auto;+ z-index: 100;+ width: min(var(--thread-max-width), calc(100% - 2rem));+ max-height: 40vh;+ display: flex;+ flex-direction: column;+ border: 1px solid color-mix(in srgb, var(--destructive) 40%, transparent);+ border-radius: 0.8rem;+ background: color-mix(in srgb, var(--card) 92%, var(--destructive) 8%);+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);+ overflow: hidden;+}++.api-error-card-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ padding: 0.55rem 0.8rem;+ border-bottom: 1px solid var(--border);+ color: var(--destructive);+ font-size: 0.8rem;+ font-weight: 600;+}++.api-error-clear {+ border: 1px solid var(--border);+ background: transparent;+ color: var(--muted-foreground);+ border-radius: 0.45rem;+ padding: 0.2rem 0.55rem;+ font-size: 0.72rem;+ font-weight: 500;+ cursor: pointer;+ transition:+ background 140ms ease,+ color 140ms ease;+}++.api-error-clear:hover {+ background: var(--accent);+ color: var(--foreground);+}++.api-error-list {+ overflow: auto;+ display: flex;+ flex-direction: column;+ padding: 0.35rem 0.5rem 0.5rem;+ gap: 0.15rem;+ scrollbar-width: thin;+ scrollbar-color: rgba(255, 255, 255, 0.12) transparent;+}++.api-error-row summary {+ display: flex;+ align-items: center;+ gap: 0.55rem;+ padding: 0.4rem 0.45rem;+ border-radius: 0.5rem;+ cursor: pointer;+ list-style: none;+ font-size: 0.78rem;+}++.api-error-row summary::-webkit-details-marker {+ display: none;+}++.api-error-row summary:hover {+ background: color-mix(in srgb, var(--accent) 70%, transparent);+}++.api-error-status {+ flex-shrink: 0;+ min-width: 2.2rem;+ text-align: center;+ padding: 0.1rem 0.3rem;+ border-radius: 0.35rem;+ background: color-mix(in srgb, var(--destructive) 20%, transparent);+ color: var(--destructive);+ font-weight: 700;+ font-size: 0.72rem;+ font-variant-numeric: tabular-nums;+}++.api-error-method {+ flex-shrink: 0;+ color: var(--secondary-foreground);+ font-weight: 600;+ font-size: 0.72rem;+}++.api-error-url {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--foreground);+ font-family: ui-monospace, monospace;+ font-size: 0.74rem;+}++.api-error-time {+ flex-shrink: 0;+ color: var(--muted-foreground);+ font-size: 0.68rem;+ font-variant-numeric: tabular-nums;+}++.api-error-dismiss {+ flex-shrink: 0;+ width: 1.3rem;+ height: 1.3rem;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border: 0;+ border-radius: 0.35rem;+ background: transparent;+ color: var(--muted-foreground);+ font-size: 0.9rem;+ line-height: 1;+ cursor: pointer;+}++.api-error-dismiss:hover {+ background: var(--accent);+ color: var(--foreground);+}++.api-error-statustext {+ padding: 0.15rem 0.45rem 0;+ color: var(--muted-foreground);+ font-size: 0.72rem;+}++.api-error-body {+ margin: 0.3rem 0.45rem 0.45rem;+ padding: 0.55rem 0.65rem;+ max-height: 12rem;+ overflow: auto;+ border: 1px solid var(--border);+ border-radius: 0.5rem;+ background: rgba(0, 0, 0, 0.35);+ color: var(--secondary-foreground);+ font-family: ui-monospace, monospace;+ font-size: 0.72rem;+ line-height: 1.5;+ white-space: pre-wrap;+ word-break: break-word;+ scrollbar-width: thin;+ scrollbar-color: rgba(255, 255, 255, 0.12) transparent;+}+.boot-screen {+ position: relative;min-height: 100dvh;display: grid;place-items: center;diff --git a/packages/frontend/src/main.tsx b/packages/frontend/src/main.tsxindex 9591c3724..f3086fda4 100644--- a/packages/frontend/src/main.tsx+++ b/packages/frontend/src/main.tsx@@ -1,9 +1,12 @@import '@truefoundry/agent-ui-sdk/styles.css';import { StrictMode } from 'react';import { createRoot } from 'react-dom/client';+import { installApiErrorInterceptor } from './apiErrors';import { App } from './App';import './index.css';+installApiErrorInterceptor();+const root = document.getElementById('root');if (!root) {throw new Error('Root element #root not found');