diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 7b726230..7bfb0397 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -4501,6 +4501,7 @@ export default { }, error: { networkError: 'Network error, please check your connection', + requestTimeout: 'Request timed out. Large files or slow connections may need another try.', invalidCredentials: 'Invalid username or password', tokenRefreshFailed: 'Token refresh failed', pleaseRelogin: 'Please log in again', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 4ce7e273..0f7acefc 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -4501,6 +4501,7 @@ export default { }, error: { networkError: 'ネットワークエラーです。接続を確認してください', + requestTimeout: 'リクエストがタイムアウトしました。大きなファイルや低速な回線では再試行してください', invalidCredentials: 'ユーザ名またはパスワードが正しくありません', tokenRefreshFailed: 'トークンの更新に失敗しました', pleaseRelogin: '再度ログインしてください', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index b39ddb7f..75f4bdb3 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -2947,6 +2947,7 @@ export default { }, error: { networkError: '네트워크 오류, 연결을 확인해 주세요', + requestTimeout: '요청 시간이 초과되었습니다. 파일이 크거나 네트워크가 느린 경우 다시 시도해 주세요', invalidCredentials: '사용자 이름 또는 비밀번호가 올바르지 않습니다', tokenRefreshFailed: '토큰 갱신 실패', pleaseRelogin: '다시 로그인해 주세요', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 93062d93..149ce280 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -2947,6 +2947,7 @@ export default { }, error: { networkError: 'Ошибка сети, проверьте подключение', + requestTimeout: 'Время ожидания запроса истекло. Для больших файлов или медленного соединения повторите попытку', invalidCredentials: 'Неверное имя пользователя или пароль', tokenRefreshFailed: 'Не удалось обновить токен', pleaseRelogin: 'Пожалуйста, войдите снова', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 644ef8fb..ae7c21eb 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -2949,6 +2949,7 @@ export default { }, error: { networkError: '网络错误,请检查您的网络连接', + requestTimeout: '请求超时,文件较大或网络较慢时请稍后重试', invalidCredentials: '用户名或密码错误', tokenRefreshFailed: 'Token刷新失败', pleaseRelogin: '请重新登录', diff --git a/frontend/src/utils/request.ts b/frontend/src/utils/request.ts index f07ce8e1..06493827 100644 --- a/frontend/src/utils/request.ts +++ b/frontend/src/utils/request.ts @@ -4,6 +4,7 @@ import { generateRandomString, MAX_FILE_SIZE_MB, MAX_SKILL_BUNDLE_SIZE_MB } from import i18n from '@/i18n' import { getApiBaseUrl } from './api-base'; import { isSkillBundleUploadUrl } from './uploadLimit'; +import { isTimeoutError, uploadTimeoutMs } from './requestTimeouts'; import { forceReloginRedirect, isEmbedPage, @@ -135,7 +136,12 @@ instance.interceptors.response.use( const originalRequest = error.config; if (!error.response) { - return Promise.reject({ message: t('error.networkError') }); + // A timeout and an unreachable server both arrive without a response, but + // telling someone whose upload timed out to "check your connection" sends + // them after the wrong problem. + return Promise.reject({ + message: t(isTimeoutError(error) ? 'error.requestTimeout' : 'error.networkError'), + }); } // 文件下载失败时服务端仍返回 JSON;先还原错误信息,避免被 Blob 隐藏。 @@ -242,6 +248,11 @@ export function postUpload( config: any = {}, ): Promise> { return instance.post(url, data, { + // Uploads are bounded by transfer time, not by the 30s default that suits + // JSON calls. Derive the budget from the payload so a deployment raising + // MAX_FILE_SIZE_MB doesn't silently abort its own uploads; an explicit + // `config.timeout` still wins. + timeout: uploadTimeoutMs(data), ...config, headers: { "Content-Type": "multipart/form-data", diff --git a/frontend/src/utils/requestTimeouts.test.ts b/frontend/src/utils/requestTimeouts.test.ts new file mode 100644 index 00000000..a5ba142a --- /dev/null +++ b/frontend/src/utils/requestTimeouts.test.ts @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { + UPLOAD_TIMEOUT_FLOOR_MS, + isTimeoutError, + uploadPayloadBytes, + uploadTimeoutMs, +} from './requestTimeouts' + +const formDataWith = (...sizes: number[]) => { + const form = new FormData() + form.append('name', 'not-a-blob') + sizes.forEach((size, i) => form.append(`file${i}`, new Blob([new Uint8Array(size)]))) + return form +} + +test('payload size counts blobs and ignores plain fields', () => { + assert.equal(uploadPayloadBytes(formDataWith()), 0) + assert.equal(uploadPayloadBytes(formDataWith(1024)), 1024) + assert.equal(uploadPayloadBytes(formDataWith(1024, 2048)), 3072) +}) + +test('non-FormData payloads contribute no bytes', () => { + assert.equal(uploadPayloadBytes({ file: 'x' }), 0) + assert.equal(uploadPayloadBytes(undefined), 0) +}) + +test('small uploads still get the floor', () => { + assert.equal(uploadTimeoutMs(formDataWith(1024)), UPLOAD_TIMEOUT_FLOOR_MS) +}) + +test('large uploads scale past the floor', () => { + // 100MB at the budgeted 10MB/min is 10 minutes — comfortably past the 5min + // floor, and far past the 30s default that silently aborted these uploads. + const tenMinutes = 10 * 60 * 1000 + assert.equal(uploadTimeoutMs(formDataWith(100 * 1024 * 1024)), tenMinutes) + assert.ok(uploadTimeoutMs(formDataWith(200 * 1024 * 1024)) > tenMinutes) +}) + +test('timeouts are distinguished from unreachable-server failures', () => { + assert.equal(isTimeoutError({ code: 'ECONNABORTED', message: 'timeout of 30000ms exceeded' }), true) + assert.equal(isTimeoutError({ code: 'ETIMEDOUT' }), true) + assert.equal(isTimeoutError({ message: 'timeout exceeded' }), true) + assert.equal(isTimeoutError({ code: 'ERR_NETWORK', message: 'Network Error' }), false) + assert.equal(isTimeoutError(null), false) +}) diff --git a/frontend/src/utils/requestTimeouts.ts b/frontend/src/utils/requestTimeouts.ts new file mode 100644 index 00000000..8e82c935 --- /dev/null +++ b/frontend/src/utils/requestTimeouts.ts @@ -0,0 +1,52 @@ +// Timeout budgets for HTTP requests whose duration is dominated by payload +// transfer rather than server processing. +// +// The axios instance uses a 30s default, which is right for JSON calls but +// unreachable for file uploads: MAX_FILE_SIZE_MB is deployment-configurable +// (200MB is a realistic value) and no ordinary uplink pushes that in 30s. +// Callers used to work around this by passing an explicit timeout, which only +// some of them remembered to do. + +/** + * Lower bound for any upload, regardless of size. Matches the value the skill + * and model upload call sites already pass explicitly. + */ +export const UPLOAD_TIMEOUT_FLOOR_MS = 5 * 60 * 1000 + +/** + * Worst-case sustained uplink we budget for: 10MB per minute (~170KB/s). + * Deliberately pessimistic — the timeout is a ceiling that only matters when a + * transfer stalls, so an over-generous budget costs nothing on healthy links. + */ +const UPLOAD_BYTES_PER_MINUTE = 10 * 1024 * 1024 + +/** Total byte size of every Blob/File carried by a FormData payload. */ +export function uploadPayloadBytes(data: unknown): number { + if (typeof FormData === 'undefined' || !(data instanceof FormData)) return 0 + let total = 0 + data.forEach((value) => { + if (typeof Blob !== 'undefined' && value instanceof Blob) total += value.size + }) + return total +} + +/** + * Timeout budget for an upload payload: the floor for small payloads, scaling + * linearly beyond it. + */ +export function uploadTimeoutMs(data: unknown): number { + const scaled = Math.ceil((uploadPayloadBytes(data) / UPLOAD_BYTES_PER_MINUTE) * 60_000) + return Math.max(UPLOAD_TIMEOUT_FLOOR_MS, scaled) +} + +/** + * Whether a rejected request timed out, as opposed to failing to reach the + * server at all. Both arrive without `error.response`, but reporting a timeout + * as "check your network connection" sends people chasing the wrong problem. + */ +export function isTimeoutError(error: unknown): boolean { + if (!error || typeof error !== 'object') return false + const { code, message } = error as { code?: unknown; message?: unknown } + if (code === 'ECONNABORTED' || code === 'ETIMEDOUT') return true + return typeof message === 'string' && /timeout/i.test(message) +}