Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): make GFS upload/proxy timeouts generous & runtime-configurable
Alfredo Lopeza2c9bf79e2c1
diff --git a/control-ui/app/control-api/[...path]/route.ts b/control-ui/app/control-api/[...path]/route.tsindex 2b2633be1..21b5c0e16 100644--- a/control-ui/app/control-api/[...path]/route.ts+++ b/control-ui/app/control-api/[...path]/route.ts@@ -4,7 +4,18 @@ export const runtime = 'nodejs'export const dynamic = 'force-dynamic'const CONTROL_API_INTERNAL_URL = process.env.CONTROL_API_INTERNAL_URL || 'http://127.0.0.1:8090'-const CONTROL_API_PROXY_TIMEOUT_MS = 30_000+const DEFAULT_CONTROL_API_PROXY_TIMEOUT_MS = 30_000++// Runtime-configurable server-side timeout (NOT NEXT_PUBLIC: read at request time in+// the control-ui pod, mirroring CONTROL_API_INTERNAL_URL above). GFS uploads send the+// file base64-encoded, so a ~10 MB payload over the Cloudflare tunnel can exceed the+// old fixed 30s. Set CONTROL_API_PROXY_TIMEOUT_MS (milliseconds) on the deployment to+// raise it; an absent, NaN, or non-positive value falls back to the default.+function resolveProxyTimeoutMs(): number {+ const raw = process.env.CONTROL_API_PROXY_TIMEOUT_MS+ const parsed = raw ? Number(raw) : Number.NaN+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_CONTROL_API_PROXY_TIMEOUT_MS+}const HOP_BY_HOP_HEADERS = new Set(['connection',@@ -56,11 +67,15 @@ async function proxyControlApi(const hasBody = req.method !== 'GET' && req.method !== 'HEAD'const rawBody = hasBody ? await req.arrayBuffer() : undefinedconst body = rawBody && rawBody.byteLength > 0 ? rawBody : undefined- const timeoutSignal = AbortSignal.timeout(CONTROL_API_PROXY_TIMEOUT_MS)- const signal =- typeof AbortSignal.any === 'function'+ // Only body-bearing methods (uploads/mutations) get the proxy timeout. GET/HEAD —+ // including long-lived SSE notification streams — rely solely on the client's own+ // abort signal, so this timeout can never cut a streaming response.+ const timeoutSignal = hasBody ? AbortSignal.timeout(resolveProxyTimeoutMs()) : undefined+ const signal = timeoutSignal+ ? typeof AbortSignal.any === 'function'? AbortSignal.any([timeoutSignal, req.signal]): timeoutSignal+ : req.signaltry {const upstream = await fetch(upstreamUrl, {diff --git a/control-ui/components/GfsBrowser.tsx b/control-ui/components/GfsBrowser.tsxindex 2fe5ea3bf..c31f88f5a 100644--- a/control-ui/components/GfsBrowser.tsx+++ b/control-ui/components/GfsBrowser.tsx@@ -8,7 +8,7 @@ import { IconFolder, IconServer } from '@components/Sidebar/icons'import { useToast } from '@components/Toast'import { IconChevronRight, IconDownload, IconPaperclip, IconUpload, IconX } from '@components/icons'import { Button, TextInput } from '@components/ui'-import { apiGet, apiSend, gfsDownload, isSilentApiError } from '@lib/api'+import { GFS_UPLOAD_TIMEOUT_MS, apiGet, apiSend, gfsDownload, isSilentApiError } from '@lib/api'import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'@@ -269,11 +269,18 @@ export function GfsBrowser(): React.JSX.Element {setUploading(true)try {const name = await normalizeGfsResourceName(file.name)- await apiSend('POST', `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(rid)}/children`, {- name,- kind: 'file',- contentBase64: await fileToEncodedData(file),- })+ await apiSend(+ 'POST',+ `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(rid)}/children`,+ {+ name,+ kind: 'file',+ contentBase64: await fileToEncodedData(file),+ },+ {},+ {},+ { timeoutMs: GFS_UPLOAD_TIMEOUT_MS }+ )showToast('File uploaded.', { tone: 'success' })setUploadCandidate(null)setUploadOpen(false)@@ -382,7 +389,10 @@ export function GfsBrowser(): React.JSX.Element {{contentBase64: await fileToEncodedData(file),ifMatch: child.version,- }+ },+ {},+ {},+ { timeoutMs: GFS_UPLOAD_TIMEOUT_MS })showToast('File replaced.', { tone: 'success' })if (selected?.resourceId === child.resourceId) setSelected(null)@@ -406,7 +416,10 @@ export function GfsBrowser(): React.JSX.Element {name,kind: 'file',contentBase64: await fileToEncodedData(file),- }+ },+ {},+ {},+ { timeoutMs: GFS_UPLOAD_TIMEOUT_MS })showToast('File uploaded.', { tone: 'success' })await refreshCurrent()diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsxindex 1fd5e2b72..4d093e78f 100644--- a/control-ui/components/__tests__/GfsBrowser.test.tsx+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx@@ -23,6 +23,7 @@ import { ToastProvider } from '../Toast'vi.mock('@lib/api', () => ({apiGet: vi.fn(),apiSend: vi.fn(),+ GFS_UPLOAD_TIMEOUT_MS: 300000,getAdminTeams: vi.fn(),getAdminUsers: vi.fn(),getGfsGrants: vi.fn(),@@ -281,7 +282,10 @@ describe('GfsBrowser', () => {name: fileName,kind: 'file',contentBase64: 'b3BlcmF0b3IgdXBsb2Fk',- }+ },+ {},+ {},+ { timeoutMs: 300000 }))})@@ -318,7 +322,10 @@ describe('GfsBrowser', () => {name: 'diagram.png',kind: 'file',contentBase64: 'b3BlcmF0b3IgaW1hZ2U=',- }+ },+ {},+ {},+ { timeoutMs: 300000 }))expect(mockApiSend).toHaveBeenCalledWith(@@ -328,7 +335,10 @@ describe('GfsBrowser', () => {name: 'notes.md',kind: 'file',contentBase64: 'IyBPcGVyYXRvciBub3Rlcw==',- }+ },+ {},+ {},+ { timeoutMs: 300000 })})@@ -558,10 +568,17 @@ describe('GfsBrowser', () => {})await waitFor(() =>- expect(mockApiSend).toHaveBeenCalledWith('PUT', '/api/v1/gfs/proxy/v1/resources/r2/content', {- contentBase64: 'cmVwbGFjZW1lbnQ=',- ifMatch: 0,- })+ expect(mockApiSend).toHaveBeenCalledWith(+ 'PUT',+ '/api/v1/gfs/proxy/v1/resources/r2/content',+ {+ contentBase64: 'cmVwbGFjZW1lbnQ=',+ ifMatch: 0,+ },+ {},+ {},+ { timeoutMs: 300000 }+ ))})diff --git a/control-ui/lib/__tests__/apiSendTimeout.test.ts b/control-ui/lib/__tests__/apiSendTimeout.test.tsnew file mode 100644index 000000000..e03ada8d6--- /dev/null+++ b/control-ui/lib/__tests__/apiSendTimeout.test.ts@@ -0,0 +1,60 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { GFS_UPLOAD_TIMEOUT_MS, apiSend } from '../api'++// apiSend arms an AbortController via window.setTimeout(fn, timeoutMs) inside+// fetchWithTimeout. GFS uploads send the file base64-encoded (~+33% size), so they+// pass a generous per-call timeoutMs to avoid the browser aborting the request+// mid-body on prod (Cloudflare tunnel), which surfaced as "Request timed out".++function jsonResponse(): Response {+ return {+ ok: true,+ status: 200,+ statusText: 'OK',+ json: async () => ({ ok: true }),+ text: async () => JSON.stringify({ ok: true }),+ headers: new Headers({ 'content-type': 'application/json' }),+ } as unknown as Response+}++let fetchMock: ReturnType<typeof vi.fn>++beforeEach(() => {+ fetchMock = vi.fn().mockResolvedValue(jsonResponse())+ vi.stubGlobal('fetch', fetchMock)+})++afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('apiSend request timeout', () => {+ it('defaults to the 30s request timeout when no override is given', async () => {+ const setTimeoutSpy = vi.spyOn(window, 'setTimeout')++ await apiSend('POST', '/api/v1/example', { a: 1 })++ expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 30000)+ })++ it('honours a per-call timeoutMs override (used by GFS uploads)', async () => {+ const setTimeoutSpy = vi.spyOn(window, 'setTimeout')++ await apiSend(+ 'POST',+ '/api/v1/gfs/proxy/v1/resources/r1/children',+ { name: 'deck.pdf', kind: 'file', contentBase64: 'AAAA' },+ {},+ {},+ { timeoutMs: GFS_UPLOAD_TIMEOUT_MS }+ )++ expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), GFS_UPLOAD_TIMEOUT_MS)+ })++ it('exposes a GFS upload ceiling well above the 30s default', () => {+ expect(GFS_UPLOAD_TIMEOUT_MS).toBe(300000)+ expect(GFS_UPLOAD_TIMEOUT_MS).toBeGreaterThan(30000)+ })+})diff --git a/control-ui/lib/__tests__/controlApiProxyRoute.test.ts b/control-ui/lib/__tests__/controlApiProxyRoute.test.tsindex 366465fb3..91d377cdd 100644--- a/control-ui/lib/__tests__/controlApiProxyRoute.test.ts+++ b/control-ui/lib/__tests__/controlApiProxyRoute.test.ts@@ -1,5 +1,5 @@import { NextRequest } from 'next/server'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { GET, POST } from '../../app/control-api/[...path]/route'describe('control-ui control-api proxy route', () => {@@ -110,4 +110,75 @@ describe('control-ui control-api proxy route', () => {error: 'control-api proxy request failed: connect ECONNREFUSED 127.0.0.1:8090',})})++ describe('proxy timeout is runtime-configurable via CONTROL_API_PROXY_TIMEOUT_MS', () => {+ const ENV_KEY = 'CONTROL_API_PROXY_TIMEOUT_MS'+ let savedEnv: string | undefined++ beforeEach(() => {+ savedEnv = process.env[ENV_KEY]+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}', { status: 200 }))+ })++ afterEach(() => {+ if (savedEnv === undefined) delete process.env[ENV_KEY]+ else process.env[ENV_KEY] = savedEnv+ })++ it('arms the abort timeout with the env value for body-bearing methods', async () => {+ process.env[ENV_KEY] = '300000'+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout')++ const req = new NextRequest(+ 'http://localhost:3000/control-api/api/v1/gfs/proxy/v1/resources/r1/children',+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'deck.pdf', kind: 'file', contentBase64: 'AAAA' }),+ }+ )++ await POST(req, {+ params: { path: ['api', 'v1', 'gfs', 'proxy', 'v1', 'resources', 'r1', 'children'] },+ })++ expect(timeoutSpy).toHaveBeenCalledWith(300000)+ })++ it('falls back to 30000ms when the env value is absent, NaN, or non-positive', async () => {+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout')++ for (const bad of [undefined, 'not-a-number', '0', '-5']) {+ timeoutSpy.mockClear()+ if (bad === undefined) delete process.env[ENV_KEY]+ else process.env[ENV_KEY] = bad++ const req = new NextRequest('http://localhost:3000/control-api/api/v1/admin/x', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ a: 1 }),+ })++ await POST(req, { params: { path: ['api', 'v1', 'admin', 'x'] } })++ expect(timeoutSpy).toHaveBeenCalledWith(30000)+ }+ })++ it('does not arm the proxy timeout for GET, so SSE streams are never cut', async () => {+ process.env[ENV_KEY] = '300000'+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout')++ const req = new NextRequest(+ 'http://localhost:3000/control-api/api/v1/admin/notifications/stream',+ { method: 'GET', headers: { Authorization: 'Bearer t' } }+ )++ await GET(req, {+ params: { path: ['api', 'v1', 'admin', 'notifications', 'stream'] },+ })++ expect(timeoutSpy).not.toHaveBeenCalled()+ })+ })})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex d0fdb7712..432b7ddb4 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -55,6 +55,15 @@ export type Metadata = {const API_BASE = process.env.NEXT_PUBLIC_CONTROL_API_BASE_URL || '/control-api'const ADMIN_TOKEN_STORAGE_KEY = 'controlUiAdminToken'const API_REQUEST_TIMEOUT_MS = 30000+// GFS uploads send the file base64-encoded inside a JSON body (~+33% over the raw+// bytes), so a 7.5 MB file crosses the wire as ~10 MB. On prod the Cloudflare tunnel+// plus control-api forwarding push that past the default 30s window, and the browser+// AbortController would cut the request mid-body — control-api then logs "request+// aborted" (400) and the user sees "Request timed out". Give GFS uploads a generous+// ceiling. This is a client (browser) constant: it cannot read a server runtime env+// without NEXT_PUBLIC (build-time) or a config endpoint (neither exists here). The+// server-side proxy has its own, runtime-configurable timeout.+export const GFS_UPLOAD_TIMEOUT_MS = 300000const inFlightGetRequests = new Map<string, Promise<unknown>>()let sessionEpoch = 0type ApiRequestOptions = {@@ -161,10 +170,11 @@ async function apiPublicPost<T>(path: string, body: unknown): Promise<T> {async function fetchWithTimeout(input: RequestInfo | URL,- init: RequestInit = {}+ init: RequestInit = {},+ timeoutMs: number = API_REQUEST_TIMEOUT_MS): Promise<Response> {const controller = new AbortController()- const timeoutId = window.setTimeout(() => controller.abort(), API_REQUEST_TIMEOUT_MS)+ const timeoutId = window.setTimeout(() => controller.abort(), timeoutMs)const signal = init.signal ? AbortSignal.any([init.signal, controller.signal]) : controller.signaltry {return await fetch(input, {@@ -249,17 +259,22 @@ export async function apiSend(path: string,body?: unknown,query: Record<string, string | undefined> = {},- extraHeaders: Record<string, string> = {}+ extraHeaders: Record<string, string> = {},+ options: { timeoutMs?: number } = {}) {- const res = await fetchWithTimeout(`${API_BASE}${path}${qs(query)}`, {- method,- headers: {- 'Content-Type': 'application/json',- ...authHeaders(),- ...extraHeaders,+ const res = await fetchWithTimeout(+ `${API_BASE}${path}${qs(query)}`,+ {+ method,+ headers: {+ 'Content-Type': 'application/json',+ ...authHeaders(),+ ...extraHeaders,+ },+ body: body ? JSON.stringify(body) : undefined,},- body: body ? JSON.stringify(body) : undefined,- })+ options.timeoutMs+ )if (!res.ok) {const text = await res.text()if (res.status === 401) {diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 098d97991..cd4eaedc4 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.386",+ "version": "0.1.387","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.386",+ "version": "0.1.387","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 8a33c37e1..d7bf8d57b 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.386",+ "version": "0.1.387","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/deploy/base/control-plane/control-ui.yaml b/deploy/base/control-plane/control-ui.yamlindex 039906ece..464e62cda 100644--- a/deploy/base/control-plane/control-ui.yaml+++ b/deploy/base/control-plane/control-ui.yaml@@ -30,6 +30,12 @@ spec:env:- name: CONTROL_API_INTERNAL_URLvalue: http://control-api.control-plane.svc.cluster.local:8090+ # Server-side control-ui proxy timeout in milliseconds (see+ # app/control-api/[...path]/route.ts). Raised above the 30s default so large+ # GFS uploads (file sent base64-encoded, ~+33%) are not cut mid-body over the+ # Cloudflare tunnel. Applies only to body-bearing methods; SSE streams unaffected.+ - name: CONTROL_API_PROXY_TIMEOUT_MS+ value: "300000"- name: CONTROL_UI_PUBLIC_TOKEN_CSRF_SECRETvalueFrom:secretKeyRef: