Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(client): 保留请求失败的原始异常日志

liugaowei91441fab7887
diff --git a/apps/desktop/src/main/__tests__/ossPublicUpload.test.ts b/apps/desktop/src/main/__tests__/ossPublicUpload.test.ts
index 4b5d5f06b1..a3e631c7ce 100644
--- a/apps/desktop/src/main/__tests__/ossPublicUpload.test.ts
+++ b/apps/desktop/src/main/__tests__/ossPublicUpload.test.ts
@@ -34,6 +34,18 @@ function makeDeps(fetchImpl: PublicUploadDeps['fetchImpl']): PublicUploadDeps {
const BODY = new Uint8Array([1, 2, 3]);
describe('uploadPublicAsset', () => {
+ it.each(['presign', 'put'] as const)('logs the original %s failure without leaking signed URLs', async (stage) => {
+ const onError = vi.fn();
+ const deps = makeDeps(async (url) => {
+ if (stage === 'put' && url.endsWith('/api/oss/presign-put')) return jsonResponse(200, PRESIGN_OK);
+ throw new Error(`socket closed: https://bucket.example.invalid/image?Signature=private-signature`);
+ });
+ const result = await uploadPublicAsset({ ...deps, onError }, { scene: 'avatar', contentType: 'image/png', body: BODY });
+ expect(result).toEqual({ ok: false, stage, status: 0 });
+ expect(onError).toHaveBeenCalledExactlyOnceWith(stage, expect.stringContaining('socket closed'));
+ expect(JSON.stringify(onError.mock.calls)).not.toContain('private-signature');
+ });
+
it('成功链路:presign 带 Bearer/scene/size,PUT 原样携带返回 headers', async () => {
const calls: Array<{ url: string; init: RequestInit | undefined }> = [];
const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => {
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index caa3d208f8..d7619b38a0 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -36,6 +36,31 @@ describe('serverApiFetch', () => {
vi.clearAllMocks();
});
+ it('keeps an unfamiliar original error and its cause while redacting secrets before logging', async () => {
+ const cause = Object.assign(new Error('proxy refused tunnel'), { code: 'NEW_PROXY_FAILURE' });
+ const error = new TypeError('fetch failed: https://api.example.invalid/?key=private-value', { cause });
+ Object.assign(error, { request: { body: 'private request body', token: 'private-token' } });
+ mocks.netFetch.mockRejectedValueOnce(error);
+ await expect(serverApiFetch('/api/resource', { baseUrl: 'https://api.example.invalid' })).rejects.toBeTruthy();
+ const logged = JSON.stringify(mocks.logger.error.mock.calls);
+ expect(logged).toContain('fetch failed');
+ expect(logged).toContain('proxy refused tunnel');
+ expect(logged).toContain('NEW_PROXY_FAILURE');
+ expect(logged).not.toContain('private-value');
+ expect(logged).not.toContain('private request body');
+ expect(logged).not.toContain('private-token');
+ });
+
+ it('logs the original response parse failure without changing the existing empty-response error', async () => {
+ mocks.netFetch.mockResolvedValueOnce({ ok: true, status: 200,
+ json: async () => { throw new SyntaxError('Unexpected end of JSON input'); } });
+ await expect(serverApiFetch('/api/resource', { baseUrl: 'https://api.example.invalid' }))
+ .rejects.toMatchObject({ code: 'EMPTY_RESPONSE', statusCode: 200 });
+ expect(mocks.logger.warn).toHaveBeenCalledWith(
+ 'response read failed', '/api/resource', { status: 200 }, 'Unexpected end of JSON input',
+ );
+ });
+
it('TOKEN_EXPIRED refresh 后用新 token 和重新生成的 body 重试', async () => {
mocks.getAccessToken.mockReturnValueOnce('token-a').mockReturnValueOnce('token-b');
mocks.refresh.mockResolvedValue(true);
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 12daf1f97d..b13a561b9b 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -97,6 +97,7 @@ import {
import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures';
import { createLogger } from './logger';
+import { requestErrorMessage } from './requestErrorMessage';
import { AuthOwnerChangeShellGate } from './authOwnerChangeShellGate';
import {
isGhostSkillProjectionBoundaryStableForOwner,
@@ -463,6 +464,9 @@ function createAuthClient(
clientType: 'desktop',
locale: getResolvedMainLocale(),
fetch: scenarioFetch ?? (async (input, init) => net.fetch(input, init as RequestInit)),
+ onRequestError: (apiPath, status, error) => {
+ log.warn('auth request failed', apiPath, { realm, status }, requestErrorMessage(error));
+ },
});
}
@@ -1658,7 +1662,10 @@ async function commitDesktopRefreshCredentials(
}
},
{ waitWhileBusyAfterRotation: true },
- );
+ ).catch((error) => {
+ log.warn('refresh credential save failed', { realm }, requestErrorMessage(error));
+ throw error;
+ });
}
/**
@@ -2292,8 +2299,15 @@ async function apiFetch<T>(
const retryAt = response.status === 429 ? retryAfterDeadline(response) : undefined;
let data: T;
try { data = (await response.json()) as T; }
- catch { return { ok: false, status: response.status, data: null as T, retryAt }; }
+ catch (error) {
+ log.warn('auth response read failed', apiPath, { status: response.status }, requestErrorMessage(error));
+ return { ok: false, status: response.status, data: null as T, retryAt };
+ }
const errorCode = (data as AuthErrorResponse | null)?.error?.code;
+ if (!response.ok) {
+ log.warn('auth response rejected', apiPath, { status: response.status },
+ requestErrorMessage((data as AuthErrorResponse | null)?.error));
+ }
if (response.status === 401 && errorCode === 'ACCOUNT_UNAVAILABLE' && currentUser) {
// Internal auth-server calls (profile/feature flags/refresh) do not pass
// through serverApiClient, but share the same terminal auth contract.
@@ -2301,7 +2315,8 @@ async function apiFetch<T>(
}
return { ok: response.ok, status: response.status, data,
...(retryAt !== undefined ? { retryAt } : {}) };
- } catch {
+ } catch (error) {
+ log.warn('auth request failed', apiPath, requestErrorMessage(error));
return { ok: false, status: 0, data: null as T };
} finally {
if (timer !== undefined) clearTimeout(timer);
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 1e6de79d3d..988ac4f3ee 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -6117,6 +6117,7 @@ const registerIpcHandlers = () => {
// 资料直写 auth-server,头像经 oss-server 预签名直传) ──
const profileEditLog = createLogger('profileEdit');
+ const publicUploadLog = createLogger('serverApiClient:public-upload');
const profileEditDeps: profileEdit.ProfileEditDeps = {
getCurrentUserId: () => authManager.getCurrentUserId(),
getAccountScopeKey: activeOwnerScopeKey,
@@ -6140,6 +6141,7 @@ const registerIpcHandlers = () => {
fetchImpl: (input, init) => net.fetch(input, init),
getBaseUrl: () => getClientEndpoint('ossApiBaseUrl'),
getToken: () => authManager.getAccessToken(),
+ onError: (stage, message) => publicUploadLog.warn('avatar upload failed', stage, message),
},
{ scene: 'avatar', contentType: mimeType, body: buffer },
);
diff --git a/apps/desktop/src/main/log-upload/__tests__/logSink.test.ts b/apps/desktop/src/main/log-upload/__tests__/logSink.test.ts
index 4e78816078..efaeb8c3c9 100644
--- a/apps/desktop/src/main/log-upload/__tests__/logSink.test.ts
+++ b/apps/desktop/src/main/log-upload/__tests__/logSink.test.ts
@@ -233,6 +233,7 @@ describe('sendLogs', () => {
const result = await sendLogs({ fetchImpl }, TARGET, META, [record(1)]);
- expect(result).toEqual({ ok: false, batches: 0, sentRecords: 0, status: 0 });
+ expect(result).toEqual({ ok: false, batches: 0, sentRecords: 0, status: 0,
+ error: 'getaddrinfo ENOTFOUND' });
});
});
diff --git a/apps/desktop/src/main/log-upload/__tests__/uploadRunner.test.ts b/apps/desktop/src/main/log-upload/__tests__/uploadRunner.test.ts
index 6d1af8fa42..b2e95ce34b 100644
--- a/apps/desktop/src/main/log-upload/__tests__/uploadRunner.test.ts
+++ b/apps/desktop/src/main/log-upload/__tests__/uploadRunner.test.ts
@@ -323,7 +323,8 @@ describe('失败与空结果:标记必须保留', () => {
it('上传失败(离线)⇒ 还原标记', async () => {
const { deps, markers } = harness({
- send: vi.fn(async () => ({ ok: false as const, batches: 0, sentRecords: 0, status: 0 })),
+ send: vi.fn(async () => ({ ok: false as const, batches: 0, sentRecords: 0, status: 0, error: 'getaddrinfo ENOTFOUND' })),
+ log: { info: vi.fn(), warn: vi.fn() },
});
const outcome = await runUpload(deps, {
@@ -333,6 +334,7 @@ describe('失败与空结果:标记必须保留', () => {
});
expect(outcome).toEqual({ kind: 'failed', status: 0 });
+ expect(deps.log.warn).toHaveBeenCalledWith(expect.stringContaining('log upload failed'), 'getaddrinfo ENOTFOUND');
expect(markers.releaseClaimed).toHaveBeenCalledTimes(1);
expect(markers.resolveClaimed).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/log-upload/logSink.ts b/apps/desktop/src/main/log-upload/logSink.ts
index 9dd941891d..0d3fd43635 100644
--- a/apps/desktop/src/main/log-upload/logSink.ts
+++ b/apps/desktop/src/main/log-upload/logSink.ts
@@ -17,6 +17,7 @@
import { BATCH_TIMEOUT_MS, MAX_BATCH_BYTES, MAX_LOGS_PER_BATCH } from './limits';
import type { LogUploadMeta, LogUploadTarget, UploadRecord } from './types';
+import { requestErrorMessage } from '../requestErrorMessage';
export interface LogSinkDeps {
/** 生产实现为 `outboundFetch`(吃系统代理);测试注入内存 fake。 */
@@ -26,7 +27,7 @@ export interface LogSinkDeps {
export type LogSinkResult =
| { ok: true; batches: number; records: number }
/** status 0 = 网络层失败(离线 / DNS / 超时)。 */
- | { ok: false; batches: number; sentRecords: number; status: number };
+ | { ok: false; batches: number; sentRecords: number; status: number; error?: string };
/** 单条上报记录在 wire 上的形状。值全部是字符串——web tracking 只接受字符串字段。 */
function toWireLog(record: UploadRecord, uploadCode: string): Record<string, string> {
@@ -117,7 +118,7 @@ async function postBatch(
deps: LogSinkDeps,
url: string,
body: string,
-): Promise<{ ok: boolean; status: number }> {
+): Promise<{ ok: boolean; status: number; error?: string }> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), BATCH_TIMEOUT_MS);
try {
@@ -136,9 +137,9 @@ async function postBatch(
signal: controller.signal,
});
return { ok: res.status >= 200 && res.status < 300, status: res.status };
- } catch {
+ } catch (error) {
// 网络层失败(离线 / DNS / abort):status 0,调用方据此保留待补传标记。
- return { ok: false, status: 0 };
+ return { ok: false, status: 0, error: requestErrorMessage(error) };
} finally {
clearTimeout(timer);
}
@@ -170,7 +171,8 @@ export async function sendLogs(
});
const res = await postBatch(deps, url, body);
if (!res.ok) {
- return { ok: false, batches: i, sentRecords, status: res.status };
+ return { ok: false, batches: i, sentRecords, status: res.status,
+ ...(res.error !== undefined ? { error: res.error } : {}) };
}
sentRecords += batches[i].length;
}
diff --git a/apps/desktop/src/main/log-upload/uploadRunner.ts b/apps/desktop/src/main/log-upload/uploadRunner.ts
index b7466dda37..a9e2e4998b 100644
--- a/apps/desktop/src/main/log-upload/uploadRunner.ts
+++ b/apps/desktop/src/main/log-upload/uploadRunner.ts
@@ -159,6 +159,7 @@ async function runUploadInner(
deps.log.warn(
`log upload failed: code=${uploadCode} status=${result.status} ` +
`batches=${result.batches} sentRecords=${result.sentRecords}`,
+ result.error,
);
return { kind: 'failed', status: result.status };
}
diff --git a/apps/desktop/src/main/ossPublicUpload.ts b/apps/desktop/src/main/ossPublicUpload.ts
index 52457cc36f..5b2f9215ff 100644
--- a/apps/desktop/src/main/ossPublicUpload.ts
+++ b/apps/desktop/src/main/ossPublicUpload.ts
@@ -14,6 +14,8 @@
* IPC 错误语义由上层业务体(profileEdit)统一映射。
*/
+import { requestErrorMessage } from './requestErrorMessage';
+
/** presign-put 成功响应(只校验消费到的字段)。 */
export interface PresignPutResponse {
putUrl: string;
@@ -34,6 +36,7 @@ export interface PublicUploadDeps {
getBaseUrl(): string;
/** 当前 access token;未登录返回 null。 */
getToken(): string | null;
+ onError?: (stage: 'presign' | 'put', message: string) => void;
}
/** presign 是纯本地签名计算,15s 足够;PUT 按 5MB 上限 + 慢网余量放宽。 */
@@ -88,6 +91,10 @@ export async function uploadPublicAsset(
if (!token) {
return { ok: false, stage: 'presign', status: 0, code: 'NOT_AUTHENTICATED' };
}
+ const logError = (stage: 'presign' | 'put', error: unknown) => {
+ try { deps.onError?.(stage, requestErrorMessage(error)); }
+ catch { /* Logging must not change the upload result. */ }
+ };
let presign: PresignPutResponse;
try {
@@ -113,7 +120,9 @@ export async function uploadPublicAsset(
try {
const data = (await response.json()) as { error?: { code?: string } } | null;
code = data?.error?.code;
- } catch {
+ logError('presign', data?.error);
+ } catch (error) {
+ logError('presign', error);
// 非 JSON 错误体,只保留 status
}
return { ok: false, stage: 'presign', status: response.status, ...(code ? { code } : {}) };
@@ -123,7 +132,8 @@ export async function uploadPublicAsset(
return { ok: false, stage: 'presign', status: response.status, code: 'MALFORMED_RESPONSE' };
}
presign = parsed;
- } catch {
+ } catch (error) {
+ logError('presign', error);
return { ok: false, stage: 'presign', status: 0 };
}
@@ -142,7 +152,8 @@ export async function uploadPublicAsset(
if (!response.ok) {
return { ok: false, stage: 'put', status: response.status };
}
- } catch {
+ } catch (error) {
+ logError('put', error);
return { ok: false, stage: 'put', status: 0 };
}
diff --git a/apps/desktop/src/main/requestErrorMessage.ts b/apps/desktop/src/main/requestErrorMessage.ts
new file mode 100644
index 0000000000..332f62ec2c
--- /dev/null
+++ b/apps/desktop/src/main/requestErrorMessage.ts
@@ -0,0 +1,21 @@
+import { redact } from './log-upload/redact';
+
+/** Keep the original explanation (including nested fetch causes), not request/response objects. */
+export function requestErrorMessage(error: unknown): string {
+ try {
+ const messages: string[] = [];
+ for (let depth = 0; error != null && depth < 4; depth++) {
+ if (typeof error !== 'object') {
+ messages.push(String(error));
+ break;
+ }
+ const value = error as { message?: unknown; code?: unknown; cause?: unknown };
+ const message = typeof value.message === 'string' ? value.message : 'Unknown error';
+ messages.push(typeof value.code === 'string' ? `${message} (${value.code})` : message);
+ error = value.cause;
+ }
+ return redact(messages.join('\nCaused by: ') || 'Unknown error').slice(0, 8000);
+ } catch {
+ return '[error message unavailable]';
+ }
+}
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index 91e334ab62..a09f3e2cfa 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -14,6 +14,7 @@ import * as authManager from './authManager';
import { getResolvedMainLocale } from './i18n.js';
import { createLogger } from './logger';
+import { requestErrorMessage } from './requestErrorMessage';
const log = createLogger('serverApiClient');
@@ -106,7 +107,10 @@ async function rawFetch<T>(apiPath: string, opts: ApiFetchOptions): Promise<RawR
let data: T | null = null;
try {
data = (await response.json()) as T;
- } catch {
+ } catch (error) {
+ log.warn('response read failed', opts.logLabel ?? redactedLogPath(apiPath),
+ { status: response.status },
+ opts.redactErrorDetails || opts.logLabel ? '[response details hidden]' : requestErrorMessage(error));
data = null;
}
return { ok: response.ok, status: response.status, data };
@@ -118,7 +122,7 @@ async function rawFetch<T>(apiPath: string, opts: ApiFetchOptions): Promise<RawR
'method=' + method,
);
} else {
- log.error('fetch failed', opts.logLabel ?? apiPath, err);
+ log.error('fetch failed', opts.logLabel ?? apiPath, requestErrorMessage(err));
}
return { ok: false, status: 0, data: null };
} finally {
diff --git a/apps/mobile/src/__tests__/apiClient.test.ts b/apps/mobile/src/__tests__/apiClient.test.ts
index 50beb4d8b3..85be592213 100644
--- a/apps/mobile/src/__tests__/apiClient.test.ts
+++ b/apps/mobile/src/__tests__/apiClient.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { i18n } from '@/i18n';
+import { setMobileDebugSink } from '@/debug/mobileDebugLog';
+import { serializeMobileDebugRecord } from '@/debug/mobileDebugRecord';
import {
ApiError,
apiFetchRaw,
@@ -15,6 +17,36 @@ describe('apiFetchRaw', () => {
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
+ setMobileDebugSink(undefined);
+ });
+
+ it.each([new SyntaxError('Unexpected end of JSON input'), new TypeError('response stream closed')])(
+ 'rejects a failed successful-response body and logs its original message: %s', async (error) => {
+ const logs: string[] = [];
+ setMobileDebugSink((level, scope, args) => { logs.push(serializeMobileDebugRecord(level, scope, args)); });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200,
+ json: async () => { throw error; } }));
+ await expect(apiFetchRaw('/api/resource', { baseUrl: 'https://api.example.invalid' }))
+ .rejects.toMatchObject({ code: 'INVALID_RESPONSE', status: 200 });
+ expect(logs.join('')).toContain(error.message);
+ },
+ );
+
+ it('logs the original transport cause through the existing redactor before mapping the UI error', async () => {
+ const logs: string[] = [];
+ setMobileDebugSink((level, scope, args) => { logs.push(serializeMobileDebugRecord(level, scope, args)); });
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Network request failed', {
+ cause: new Error('proxy rejected CONNECT https://api.example.invalid/?key=private-key'),
+ })));
+ await expect(apiFetchRaw('/api/resource', { baseUrl: 'https://api.example.invalid' }))
+ .rejects.toMatchObject({ code: 'NETWORK_UNAVAILABLE' });
+ expect(logs.join('')).toContain('proxy rejected CONNECT');
+ expect(logs.join('')).not.toContain('private-key');
+ });
+
+ it('still accepts an explicitly empty 204 response', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 204 })));
+ await expect(apiFetchRaw('/api/resource', { baseUrl: 'https://api.example.invalid' })).resolves.toBeNull();
});
it('sends extra headers without letting them replace auth or content type', async () => {
@@ -145,10 +177,13 @@ describe('apiFetchRaw', () => {
});
it('parses top-level device-link relay errors', async () => {
+ const logs: string[] = [];
+ setMobileDebugSink((level, scope, args) => { logs.push(serializeMobileDebugRecord(level, scope, args)); });
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: false,
status: 403,
- json: async () => ({ code: 'REMOTE_DISABLED', message: 'remote disabled' }),
+ json: async () => ({ code: 'REMOTE_DISABLED', message: 'remote disabled',
+ details: { reason: 'private server details' } }),
} as Response)));
await expect(apiFetchRaw('/api/device-link/devices', {
@@ -157,7 +192,10 @@ describe('apiFetchRaw', () => {
code: 'REMOTE_DISABLED',
status: 403,
message: 'remote disabled',
+ details: { reason: 'private server details' },
});
+ expect(logs.join('')).toContain('remote disabled');
+ expect(logs.join('')).not.toContain('private server details');
});
it('notifies the terminal auth boundary for ACCOUNT_UNAVAILABLE', async () => {
diff --git a/apps/mobile/src/api/client.ts b/apps/mobile/src/api/client.ts
index 8280fb1527..71f719817d 100644
--- a/apps/mobile/src/api/client.ts
+++ b/apps/mobile/src/api/client.ts
@@ -1,4 +1,5 @@
import { i18n } from '@/i18n';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
export class ApiError extends Error {
constructor(
@@ -75,7 +76,14 @@ export async function apiFetchRaw<T>(
let nextData: unknown = null;
try {
nextData = await nextResponse.json();
- } catch {
+ } catch (error) {
+ if (nextResponse.status === 204 || nextResponse.status === 205) {
+ return { response: nextResponse, data: null };
+ }
+ mobileDebugLog('warn', 'network', 'response read failed', { status: nextResponse.status }, error);
+ if (nextResponse.ok) {
+ throw new ApiError('INVALID_RESPONSE', nextResponse.status, i18n.t('apiErrors.requestFailed'));
+ }
nextData = null;
}
return { response: nextResponse, data: nextData };
@@ -95,6 +103,9 @@ export async function apiFetchRaw<T>(
response = result.response;
data = result.data;
} catch (err) {
+ if (!(err instanceof ApiError) || err.code === 'REQUEST_TIMEOUT') {
+ mobileDebugLog('warn', 'network', 'request failed', err);
+ }
if (err instanceof ApiError) throw err;
if (isAbortError(err)) {
throw new ApiError('REQUEST_TIMEOUT', 0, i18n.t('apiErrors.requestTimeout'));
@@ -118,6 +129,8 @@ export async function apiFetchRaw<T>(
if (!response.ok) {
const error = readError(data);
const code = error.code ?? `HTTP_${response.status}`;
+ const failure = new ApiError(code, response.status, error.message ?? i18n.t('apiErrors.requestFailed'), error.details);
+ mobileDebugLog('warn', 'network', 'response rejected', { status: response.status, code }, failure.message);
if (response.status === 401 && code === 'ACCOUNT_UNAVAILABLE') {
try {
await accountUnavailableHandler?.();
@@ -125,7 +138,7 @@ export async function apiFetchRaw<T>(
// Preserve the original typed API error even if local cleanup fails.
}
}
- throw new ApiError(code, response.status, error.message ?? i18n.t('apiErrors.requestFailed'), error.details);
+ throw failure;
}
return data as T;
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index bda65e0b1e..b4795dbaf6 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -47,6 +47,7 @@ import {
// 生产构建由 metro resolveRequest 把整模块替换为空 stub(metro.config.js),
// 运行时另有 __DEV__ guard 双保险。
import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
import {
apiFetchRaw,
@@ -3445,6 +3446,9 @@ function authClientFor(
clientType: 'mobile',
locale: getAuthLocale(),
fetch: scenarioFetch ?? (async (input, init) => fetch(input, init)),
+ onRequestError: (path, status, error) => {
+ mobileDebugLog('warn', 'auth', 'request failed', { path, region, status }, error);
+ },
});
}
diff --git a/apps/mobile/src/debug/mobileDebugLog.ts b/apps/mobile/src/debug/mobileDebugLog.ts
index 4eba21f861..feb53f2788 100644
--- a/apps/mobile/src/debug/mobileDebugLog.ts
+++ b/apps/mobile/src/debug/mobileDebugLog.ts
@@ -1,5 +1,7 @@
/** Phone-local instrumentation only. Never pass session bodies, request payloads or credentials. */
export type MobileDebugScope =
+ | "auth"
+ | "network"
| "device-link"
| "recovery"
| "lifecycle"
diff --git a/docs/dev-rules/log-upload-and-redaction.md b/docs/dev-rules/log-upload-and-redaction.md
index cc0053261e..406f1b3de1 100644
--- a/docs/dev-rules/log-upload-and-redaction.md
+++ b/docs/dev-rules/log-upload-and-redaction.md
@@ -273,6 +273,8 @@ Mobile 的设置 → 调试 / 开发者提供 Debug 开关、导出与手动上
保留级别、错误原因与堆栈,
`mobileDebugRecord.ts` 在落盘前过滤敏感字段、凭证、地址参数等;禁止传入消息正文、请求体或完整鉴权信息,
不接管全局 console,不重复保存被控端任务记录。
+ `auth` / `network` 在错误转换前记录原始异常及原因,仍走上述落盘脱敏;不记录成功认证响应,
+ 不扩展上传摘要白名单,也不改变 Debug 开关。
- 详细日志在 `Paths.document/cindy-debug/`,NDJSON 文件每份最多 1 MiB、最多 8 份、保留最近 7 天。
每 2 秒及前后台切换时批量落盘;内存待写最多 512 KiB,溢出或写失败在后续记录中标明丢失,不能无限重试堆积。
突然杀进程可能丢失尚未落盘的最后一批,JS 停摆只能在恢复后测得。Documents 属 App 持久容器,可能随系统备份。
diff --git a/packages/auth-client/src/__tests__/client.test.ts b/packages/auth-client/src/__tests__/client.test.ts
index 98e32fda96..3bf4d4969c 100644
--- a/packages/auth-client/src/__tests__/client.test.ts
+++ b/packages/auth-client/src/__tests__/client.test.ts
@@ -33,6 +33,40 @@ function client(fetch: AuthFetch = vi.fn(async () => response(200, {}))) {
}
describe("CindyAuthClient", () => {
+ it.each(["request", "response"] as const)("reports the original %s error before mapping it", async (stage) => {
+ const original = new TypeError("socket closed", { cause: new Error("proxy rejected CONNECT") });
+ const onRequestError = vi.fn();
+ const instance = new CindyAuthClient({
+ baseUrl: "https://auth.example.com", region: "cn", deviceId: "device-1", clientType: "desktop",
+ fetch: async () => {
+ if (stage === "request") throw original;
+ return { ok: true, status: 200, json: async () => { throw original; } };
+ },
+ onRequestError,
+ });
+ await expect(instance.refresh("unused-token")).rejects.toMatchObject({
+ code: stage === "request" ? "NETWORK_ERROR" : "INVALID_RESPONSE",
+ });
+ expect(onRequestError).toHaveBeenCalledExactlyOnceWith(
+ "/api/auth/refresh", stage === "request" ? 0 : 200, original,
+ );
+ });
+
+ it("keeps server error messages and ignores a failing error logger", async () => {
+ const onRequestError = vi.fn(() => { throw new Error("logger unavailable"); });
+ const instance = new CindyAuthClient({
+ baseUrl: "https://auth.example.com", region: "cn", deviceId: "device-1", clientType: "desktop",
+ fetch: async () => response(401, { error: { code: "INVALID_REFRESH_TOKEN", message: "Refresh token was revoked" } }),
+ onRequestError,
+ });
+ await expect(instance.refresh("unused-token")).rejects.toMatchObject({
+ code: "INVALID_REFRESH_TOKEN", message: "Refresh token was revoked",
+ });
+ expect(onRequestError).toHaveBeenCalledExactlyOnceWith(
+ "/api/auth/refresh", 401, expect.objectContaining({ message: "Refresh token was revoked" }),
+ );
+ });
+
it.each([
["120", 120_000],
["Wed, 07 Oct 2026 06:02:00 GMT", 120_000],
diff --git a/packages/auth-client/src/client.ts b/packages/auth-client/src/client.ts
index 179e4c5de1..d602a988b7 100644
--- a/packages/auth-client/src/client.ts
+++ b/packages/auth-client/src/client.ts
@@ -57,6 +57,8 @@ export interface AuthClientOptions {
locale?: string;
fetch: AuthFetch;
timeoutMs?: number;
+ /** Original failure before UI error mapping; platform adapters handle log redaction. */
+ onRequestError?: (path: string, status: number, error: unknown) => void;
}
/** Structured auth-server failure preserved across platform adapters. */
@@ -534,6 +536,7 @@ export class CindyAuthClient {
...(timeoutMs > 0 || external ? { signal: controller.signal } : {}),
});
} catch (error) {
+ this.logRequestError(path, 0, error);
throw this.describeTransportFailure(error, external);
}
@@ -543,6 +546,7 @@ export class CindyAuthClient {
try {
data = await response.json();
} catch (error) {
+ this.logRequestError(path, response.status, error);
// body 读取同样可能因取消/超时中断,此时按传输失败归类而不是"响应非法 JSON"
if (error instanceof Error && error.name === "AbortError") {
throw this.describeTransportFailure(error, external);
@@ -576,10 +580,13 @@ export class CindyAuthClient {
parsed.data.message ??
"Authentication request failed")
: "Authentication request failed";
- throw new AuthApiError(code, response.status, message, retryAt);
+ const error = new AuthApiError(code, response.status, message, retryAt);
+ this.logRequestError(path, response.status, error);
+ throw error;
}
const parsed = schema.safeParse(data);
if (!parsed.success) {
+ this.logRequestError(path, response.status, parsed.error);
throw new AuthApiError(
"INVALID_RESPONSE",
response.status,
@@ -593,6 +600,14 @@ export class CindyAuthClient {
}
}
+ private logRequestError(path: string, status: number, error: unknown): void {
+ try {
+ this.options.onRequestError?.(path, status, error);
+ } catch {
+ // A logging failure cannot affect auth, retries or rotated credentials.
+ }
+ }
+
/** 传输层中断的归类:调用方取消与超时都表现为 AbortError,按来源区分。 */
private describeTransportFailure(
error: unknown,